Compare commits

...

7 Commits

Author SHA1 Message Date
405d388db0 v1.4.6+67
All checks were successful
Flutter Schmutter / build (push) Successful in 3m46s
2025-06-23 02:51:49 +02:00
e30635304b ... 2025-06-22 17:24:43 +02:00
7a1f76ee85 v1.4.5+66
All checks were successful
Flutter Schmutter / build (push) Successful in 3m34s
2025-06-22 03:40:13 +02:00
95f6dcfe2b v1.4.4+65
All checks were successful
Flutter Schmutter / build (push) Successful in 3m35s
2025-06-22 03:02:18 +02:00
7f0743808a logo schmogo 2025-06-21 18:50:00 +02:00
840395bb69 v1.4.3+64
All checks were successful
Flutter Schmutter / build (push) Successful in 3m33s
2025-06-21 16:48:28 +02:00
7a88c23e57 v1.4.2+63
All checks were successful
Flutter Schmutter / build (push) Successful in 3m51s
2025-06-21 16:28:57 +02:00
23 changed files with 717 additions and 419 deletions

View File

@ -4,8 +4,8 @@
# This file should be version controlled and should not be manually edited. # This file should be version controlled and should not be manually edited.
version: version:
revision: "8b18dde77fa59ba7f87540c05d1aba787198e77a" revision: "01fde956f0d13551843a44ae16eda7ca87478603"
channel: "master" channel: "beta"
project_type: app project_type: app
@ -13,27 +13,8 @@ project_type: app
migration: migration:
platforms: platforms:
- platform: root - platform: root
create_revision: 8b18dde77fa59ba7f87540c05d1aba787198e77a create_revision: 01fde956f0d13551843a44ae16eda7ca87478603
base_revision: 8b18dde77fa59ba7f87540c05d1aba787198e77a base_revision: 01fde956f0d13551843a44ae16eda7ca87478603
- platform: android
create_revision: 8b18dde77fa59ba7f87540c05d1aba787198e77a
base_revision: 8b18dde77fa59ba7f87540c05d1aba787198e77a
- platform: ios
create_revision: 8b18dde77fa59ba7f87540c05d1aba787198e77a
base_revision: 8b18dde77fa59ba7f87540c05d1aba787198e77a
- platform: linux
create_revision: 8b18dde77fa59ba7f87540c05d1aba787198e77a
base_revision: 8b18dde77fa59ba7f87540c05d1aba787198e77a
- platform: macos
create_revision: 8b18dde77fa59ba7f87540c05d1aba787198e77a
base_revision: 8b18dde77fa59ba7f87540c05d1aba787198e77a
- platform: web
create_revision: 8b18dde77fa59ba7f87540c05d1aba787198e77a
base_revision: 8b18dde77fa59ba7f87540c05d1aba787198e77a
- platform: windows
create_revision: 8b18dde77fa59ba7f87540c05d1aba787198e77a
base_revision: 8b18dde77fa59ba7f87540c05d1aba787198e77a
# User provided section # User provided section
# List of Local paths (relative to this file) that should be # List of Local paths (relative to this file) that should be

View File

@ -1,5 +1,5 @@
# fApp # fApp
![f0ck.me Logo](https://git.lat/f0ck/fApp/raw/branch/master/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png) ![f0ck.me Logo](https://git.lat/f0ck/fApp/raw/branch/master/assets/images/menu.webp)
## Overview ## Overview
fApp is the mobile application for the website [f0ck.me](https://f0ck.me). This app provides a user-friendly interface to access the content of the website and utilize its features conveniently from your mobile device. fApp is the mobile application for the website [f0ck.me](https://f0ck.me). This app provides a user-friendly interface to access the content of the website and utilize its features conveniently from your mobile device.

View File

@ -2,16 +2,17 @@ import 'dart:convert';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:encrypt_shared_preferences/provider.dart'; import 'package:encrypt_shared_preferences/provider.dart';
import 'package:http/http.dart' as http;
import 'package:f0ckapp/models/user.dart';
class AuthController extends GetxController { class AuthController extends GetxController {
final EncryptedSharedPreferencesAsync storage = final EncryptedSharedPreferencesAsync storage =
EncryptedSharedPreferencesAsync.getInstance(); EncryptedSharedPreferencesAsync.getInstance();
final GetConnect http = GetConnect();
RxnString token = RxnString(); RxnString token = RxnString();
RxnInt userId = RxnInt(); Rxn<User> user = Rxn<User>();
RxnString avatarUrl = RxnString();
RxnString username = RxnString();
RxBool isLoading = false.obs; RxBool isLoading = false.obs;
RxnString error = RxnString(); RxnString error = RxnString();
@ -38,7 +39,8 @@ class AuthController extends GetxController {
if (token.value != null) { if (token.value != null) {
try { try {
await http.post( await http.post(
Uri.parse('https://api.f0ck.me/logout'), 'https://api.f0ck.me/logout',
{},
headers: { headers: {
'Authorization': 'Bearer ${token.value}', 'Authorization': 'Bearer ${token.value}',
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -47,9 +49,7 @@ class AuthController extends GetxController {
} catch (_) {} } catch (_) {}
} }
token.value = null; token.value = null;
userId.value = null; user.value = null;
avatarUrl.value = null;
username.value = null;
await storage.remove('token'); await storage.remove('token');
} }
@ -57,20 +57,18 @@ class AuthController extends GetxController {
isLoading.value = true; isLoading.value = true;
error.value = null; error.value = null;
try { try {
final http.Response response = await http.post( final Response<dynamic> response = await http.post(
Uri.parse('https://api.f0ck.me/login'), 'https://api.f0ck.me/login',
json.encode({'username': username, 'password': password}),
headers: {'Content-Type': 'application/json'}, headers: {'Content-Type': 'application/json'},
body: json.encode({'username': username, 'password': password}),
); );
if (response.statusCode == 200) { if (response.statusCode == 200) {
final dynamic data = json.decode(response.body); final dynamic data = response.body is String
? json.decode(response.body)
: response.body;
if (data['token'] != null) { if (data['token'] != null) {
await saveToken(data['token']); await saveToken(data['token']);
userId.value = data['userid']; user.value = User.fromJson(data);
avatarUrl.value = data['avatar'] != null
? 'https://f0ck.me/t/${data['avatar']}.webp'
: null;
this.username.value = data['user'];
return true; return true;
} else { } else {
error.value = 'Kein Token erhalten'; error.value = 'Kein Token erhalten';
@ -89,19 +87,15 @@ class AuthController extends GetxController {
Future<void> fetchUserInfo() async { Future<void> fetchUserInfo() async {
if (token.value == null) return; if (token.value == null) return;
try { try {
final http.Response response = await http.get( final Response<dynamic> response = await http.get(
Uri.parse('https://api.f0ck.me/login/check'), 'https://api.f0ck.me/login/check',
headers: {'Authorization': 'Bearer ${token.value}'}, headers: {'Authorization': 'Bearer ${token.value}'},
); );
if (response.statusCode == 200) { if (response.statusCode == 200) {
final dynamic data = json.decode(response.body); final dynamic data = response.body is String
userId.value = data['userid'] != null ? json.decode(response.body)
? int.tryParse(data['userid'].toString()) : response.body;
: null; user.value = User.fromJson(data);
avatarUrl.value = data['avatar'] != null
? 'https://f0ck.me/t/${data['avatar']}.webp'
: null;
username.value = data['user'];
} else { } else {
await logout(); await logout();
} }

View File

@ -1,18 +1,14 @@
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:encrypt_shared_preferences/provider.dart';
import 'package:f0ckapp/models/feed.dart'; import 'package:f0ckapp/models/feed.dart';
import 'package:f0ckapp/models/item.dart'; import 'package:f0ckapp/models/item.dart';
import 'package:f0ckapp/services/api.dart'; import 'package:f0ckapp/services/api.dart';
import 'package:f0ckapp/utils/animatedtransition.dart';
const List<String> mediaTypes = ["alles", "image", "video", "audio"]; const List<String> mediaTypes = ["alles", "image", "video", "audio"];
const List<String> mediaModes = ["sfw", "nsfw", "untagged", "all"]; const List<String> mediaModes = ["sfw", "nsfw", "untagged", "all"];
class MediaController extends GetxController { class MediaController extends GetxController {
final ApiService _api = Get.find<ApiService>(); final ApiService _api = Get.find<ApiService>();
final EncryptedSharedPreferencesAsync storage =
EncryptedSharedPreferencesAsync.getInstance();
RxList<MediaItem> items = <MediaItem>[].obs; RxList<MediaItem> items = <MediaItem>[].obs;
RxBool loading = false.obs; RxBool loading = false.obs;
@ -23,10 +19,6 @@ class MediaController extends GetxController {
RxInt modeIndex = 0.obs; RxInt modeIndex = 0.obs;
RxInt random = 0.obs; RxInt random = 0.obs;
Rxn<String> tag = Rxn<String>(null); Rxn<String> tag = Rxn<String>(null);
RxBool muted = false.obs;
Rx<PageTransition> transitionType = PageTransition.opacity.obs;
RxBool drawerSwipeEnabled = true.obs;
RxInt crossAxisCount = 0.obs;
void setTypeIndex(int idx) { void setTypeIndex(int idx) {
typeIndex.value = idx; typeIndex.value = idx;
@ -135,55 +127,10 @@ class MediaController extends GetxController {
} }
} }
void toggleMuted() {
muted.value = !muted.value;
}
void setMuted(bool value) {
muted.value = value;
}
Future<void> setTransitionType(PageTransition type) async {
transitionType.value = type;
await saveSettings();
}
Future<void> setCrossAxisCount(int value) async {
crossAxisCount.value = value;
await saveSettings();
}
Future<void> setDrawerSwipeEnabled(bool enabled) async {
drawerSwipeEnabled.value = enabled;
await saveSettings();
}
void toggleRandom() { void toggleRandom() {
random.value = random.value == 1 ? 0 : 1; random.value = random.value == 1 ? 0 : 1;
fetchInitial(); fetchInitial();
} }
@override
void onInit() async {
super.onInit();
await loadSettings();
}
Future<void> loadSettings() async {
muted.value = await storage.getBoolean('muted') ?? false;
crossAxisCount.value = await storage.getInt('crossAxisCount') ?? 0;
drawerSwipeEnabled.value =
await storage.getBoolean('drawerSwipeEnabled') ?? true;
transitionType.value =
PageTransition.values[await storage.getInt('transitionType') ?? 0];
}
Future<void> saveSettings() async {
await storage.setBoolean('muted', muted.value);
await storage.setInt('crossAxisCount', crossAxisCount.value);
await storage.setBoolean('drawerSwipeEnabled', drawerSwipeEnabled.value);
await storage.setInt('transitionType', transitionType.value.index);
}
bool get isRandomEnabled => random.value == 1; bool get isRandomEnabled => random.value == 1;
} }

View File

@ -0,0 +1,81 @@
import 'package:encrypt_shared_preferences/provider.dart';
import 'package:get/get.dart';
import 'package:f0ckapp/utils/animatedtransition.dart';
class _StorageKeys {
static const String muted = 'muted';
static const String crossAxisCount = 'crossAxisCount';
static const String drawerSwipeEnabled = 'drawerSwipeEnabled';
static const String transitionType = 'transitionType';
}
class SettingsController extends GetxController {
final EncryptedSharedPreferencesAsync storage =
EncryptedSharedPreferencesAsync.getInstance();
RxBool muted = false.obs;
Rx<PageTransition> transitionType = PageTransition.opacity.obs;
RxBool drawerSwipeEnabled = true.obs;
RxInt crossAxisCount = 0.obs;
RxInt videoControlsTimerNotifier = 0.obs;
RxInt hideControlsNotifier = 0.obs;
@override
void onInit() {
super.onInit();
loadSettings();
}
void toggleMuted() {
muted.value = !muted.value;
saveSettings();
}
void setMuted(bool value) {
muted.value = value;
saveSettings();
}
Future<void> setTransitionType(PageTransition type) async {
transitionType.value = type;
await saveSettings();
}
Future<void> setCrossAxisCount(int value) async {
crossAxisCount.value = value;
await saveSettings();
}
Future<void> setDrawerSwipeEnabled(bool enabled) async {
drawerSwipeEnabled.value = enabled;
await saveSettings();
}
void resetVideoControlsTimer() => videoControlsTimerNotifier.value++;
void hideVideoControls() => hideControlsNotifier.value++;
Future<void> loadSettings() async {
muted.value = await storage.getBoolean(_StorageKeys.muted) ?? false;
crossAxisCount.value =
await storage.getInt(_StorageKeys.crossAxisCount) ?? 0;
drawerSwipeEnabled.value =
await storage.getBoolean(_StorageKeys.drawerSwipeEnabled) ?? true;
transitionType.value = PageTransition
.values[await storage.getInt(_StorageKeys.transitionType) ?? 0];
}
Future<void> saveSettings() async {
await storage.setBoolean(_StorageKeys.muted, muted.value);
await storage.setInt(_StorageKeys.crossAxisCount, crossAxisCount.value);
await storage.setBoolean(
_StorageKeys.drawerSwipeEnabled,
drawerSwipeEnabled.value,
);
await storage.setInt(
_StorageKeys.transitionType,
transitionType.value.index,
);
}
}

View File

@ -186,7 +186,6 @@ final ThemeData f0ck95Theme = ThemeData(
backgroundColor: const Color(0xFFE0E0E0), backgroundColor: const Color(0xFFE0E0E0),
foregroundColor: Colors.black, foregroundColor: Colors.black,
elevation: 4, elevation: 4,
centerTitle: true,
), ),
textTheme: const TextTheme( textTheme: const TextTheme(
bodyLarge: TextStyle(color: Colors.black), bodyLarge: TextStyle(color: Colors.black),

View File

@ -4,6 +4,7 @@ import 'package:encrypt_shared_preferences/provider.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:f0ckapp/services/api.dart'; import 'package:f0ckapp/services/api.dart';
import 'package:f0ckapp/controller/settingscontroller.dart';
import 'package:f0ckapp/controller/authcontroller.dart'; import 'package:f0ckapp/controller/authcontroller.dart';
import 'package:f0ckapp/controller/localizationcontroller.dart'; import 'package:f0ckapp/controller/localizationcontroller.dart';
import 'package:f0ckapp/controller/themecontroller.dart'; import 'package:f0ckapp/controller/themecontroller.dart';
@ -24,6 +25,7 @@ void main() async {
Get.put(AuthController()); Get.put(AuthController());
Get.put(ApiService()); Get.put(ApiService());
Get.put(SettingsController());
Get.put(MediaController()); Get.put(MediaController());
final ThemeController themeController = Get.put(ThemeController()); final ThemeController themeController = Get.put(ThemeController());

View File

@ -7,6 +7,9 @@ class MediaItem {
final int mode; final int mode;
final List<Tag>? tags; final List<Tag>? tags;
final List<Favorite>? favorites; final List<Favorite>? favorites;
final String? username;
final String? userchannel;
final String? usernetwork;
MediaItem({ MediaItem({
required this.id, required this.id,
@ -17,6 +20,9 @@ class MediaItem {
required this.mode, required this.mode,
this.tags = const [], this.tags = const [],
this.favorites = const [], this.favorites = const [],
this.username,
this.userchannel,
this.usernetwork,
}); });
String get thumbnailUrl => 'https://f0ck.me/t/$id.webp'; String get thumbnailUrl => 'https://f0ck.me/t/$id.webp';
@ -33,6 +39,9 @@ class MediaItem {
int? mode, int? mode,
List<Tag>? tags, List<Tag>? tags,
List<Favorite>? favorites, List<Favorite>? favorites,
String? username,
String? userchannel,
String? usernetwork,
}) { }) {
return MediaItem( return MediaItem(
id: id ?? this.id, id: id ?? this.id,
@ -43,6 +52,9 @@ class MediaItem {
mode: mode ?? this.mode, mode: mode ?? this.mode,
tags: tags ?? this.tags, tags: tags ?? this.tags,
favorites: favorites ?? this.favorites, favorites: favorites ?? this.favorites,
username: username ?? this.username,
userchannel: userchannel ?? this.userchannel,
usernetwork: usernetwork ?? this.usernetwork,
); );
} }
@ -64,6 +76,9 @@ class MediaItem {
?.map((e) => Favorite.fromJson(e)) ?.map((e) => Favorite.fromJson(e))
.toList() ?? .toList() ??
[], [],
username: json['username'],
userchannel: json['userchannel'],
usernetwork: json['usernetwork'],
); );
} }
} }
@ -97,8 +112,8 @@ class Favorite {
factory Favorite.fromJson(Map<String, dynamic> json) { factory Favorite.fromJson(Map<String, dynamic> json) {
return Favorite( return Favorite(
userId: json['user_id'], userId: json['userId'],
username: json['user'], username: json['username'],
avatar: json['avatar'], avatar: json['avatar'],
); );
} }

17
lib/models/user.dart Normal file
View File

@ -0,0 +1,17 @@
class User {
final int id;
final String username;
final String? avatarUrl;
User({required this.id, required this.username, this.avatarUrl});
factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['userid'],
username: json['user'],
avatarUrl: json['avatar'] != null
? 'https://f0ck.me/t/${json['avatar']}.webp'
: null,
);
}
}

View File

@ -5,17 +5,20 @@ import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_cache_manager/file.dart'; import 'package:flutter_cache_manager/file.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart'; import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:pullex/pullex.dart';
import 'package:share_plus/share_plus.dart'; import 'package:share_plus/share_plus.dart';
import 'package:f0ckapp/services/api.dart';
import 'package:f0ckapp/widgets/tagfooter.dart'; import 'package:f0ckapp/widgets/tagfooter.dart';
import 'package:f0ckapp/utils/animatedtransition.dart'; import 'package:f0ckapp/utils/animatedtransition.dart';
import 'package:f0ckapp/controller/authcontroller.dart'; import 'package:f0ckapp/controller/authcontroller.dart';
import 'package:f0ckapp/widgets/actiontag.dart';
import 'package:f0ckapp/widgets/favoritesection.dart'; import 'package:f0ckapp/widgets/favoritesection.dart';
import 'package:f0ckapp/screens/fullscreen.dart'; import 'package:f0ckapp/screens/fullscreen.dart';
import 'package:f0ckapp/widgets/end_drawer.dart'; import 'package:f0ckapp/widgets/end_drawer.dart';
import 'package:f0ckapp/controller/settingscontroller.dart';
import 'package:f0ckapp/controller/mediacontroller.dart'; import 'package:f0ckapp/controller/mediacontroller.dart';
import 'package:f0ckapp/models/item.dart'; import 'package:f0ckapp/models/item.dart';
import 'package:f0ckapp/widgets/tagsection.dart';
import 'package:f0ckapp/widgets/video_widget.dart'; import 'package:f0ckapp/widgets/video_widget.dart';
enum ShareAction { media, directLink, postLink } enum ShareAction { media, directLink, postLink }
@ -31,9 +34,11 @@ class MediaDetailScreen extends StatefulWidget {
class _MediaDetailScreenState extends State<MediaDetailScreen> { class _MediaDetailScreenState extends State<MediaDetailScreen> {
PageController? _pageController; PageController? _pageController;
final MediaController mediaController = Get.find<MediaController>(); final MediaController mediaController = Get.find<MediaController>();
final SettingsController settingsController = Get.find<SettingsController>();
final AuthController authController = Get.find<AuthController>(); final AuthController authController = Get.find<AuthController>();
final _currentIndex = 0.obs; final RxInt _currentIndex = 0.obs;
final _mediaSaverChannel = const MethodChannel('MediaShit'); final MethodChannel _mediaSaverChannel = const MethodChannel('MediaShit');
final Map<int, PullexRefreshController> _refreshControllers = {};
bool _isLoading = true; bool _isLoading = true;
bool _itemNotFound = false; bool _itemNotFound = false;
@ -102,10 +107,35 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
..snackbar('hehe', message, snackPosition: SnackPosition.BOTTOM); ..snackbar('hehe', message, snackPosition: SnackPosition.BOTTOM);
} }
Future<void> _onRefresh(
int itemId,
PullexRefreshController controller,
) async {
if (mediaController.loading.value) {
controller.refreshCompleted();
return;
}
try {
final MediaItem item = await ApiService().fetchItemById(itemId);
final int index = mediaController.items.indexWhere(
(item) => item.id == itemId,
);
if (index != -1) {
mediaController.items[index] = item;
mediaController.items.refresh();
}
controller.refreshCompleted();
} catch (e) {
_showMsg('Fehler beim Aktualisieren: $e');
controller.refreshFailed();
}
}
void _onPageChanged(int idx) { void _onPageChanged(int idx) {
if (idx != _currentIndex.value) { if (idx != _currentIndex.value) {
_currentIndex.value = idx; _currentIndex.value = idx;
final item = mediaController.items[idx]; final MediaItem item = mediaController.items[idx];
if (item.mime.startsWith('image/') && !_readyItemIds.contains(item.id)) { if (item.mime.startsWith('image/') && !_readyItemIds.contains(item.id)) {
setState(() => _readyItemIds.add(item.id)); setState(() => _readyItemIds.add(item.id));
} }
@ -147,7 +177,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
item.mediaUrl, item.mediaUrl,
); );
final Uint8List bytes = await file.readAsBytes(); final Uint8List bytes = await file.readAsBytes();
final params = ShareParams( final ShareParams params = ShareParams(
files: [XFile.fromData(bytes, mimeType: item.mime)], files: [XFile.fromData(bytes, mimeType: item.mime)],
); );
await SharePlus.instance.share(params); await SharePlus.instance.share(params);
@ -174,6 +204,9 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
@override @override
void dispose() { void dispose() {
_pageController?.dispose(); _pageController?.dispose();
for (PullexRefreshController controller in _refreshControllers.values) {
controller.dispose();
}
super.dispose(); super.dispose();
} }
@ -216,123 +249,158 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
); );
} }
return Obx( return Obx(() {
() => PageView.builder( if (mediaController.items.isEmpty ||
controller: _pageController!, _currentIndex.value >= mediaController.items.length) {
itemCount: mediaController.items.length, return Scaffold(
onPageChanged: _onPageChanged, appBar: AppBar(title: const Text('Fehler')),
itemBuilder: (context, index) { body: const Center(child: Text('Keine Items zum Anzeigen.')),
final MediaItem item = mediaController.items[index]; );
final bool isReady = _readyItemIds.contains(item.id); }
final MediaItem currentItem = mediaController.items[_currentIndex.value];
return Scaffold( return Scaffold(
endDrawer: EndDrawer(), endDrawer: const EndDrawer(),
endDrawerEnableOpenDragGesture: endDrawerEnableOpenDragGesture:
mediaController.drawerSwipeEnabled.value, settingsController.drawerSwipeEnabled.value,
appBar: AppBar( appBar: AppBar(
title: Text('f0ck #${item.id}'), title: Text('f0ck #${currentItem.id}'),
actions: [ actions: [
IconButton( IconButton(
icon: const Icon(Icons.fullscreen), icon: const Icon(Icons.fullscreen),
onPressed: () { onPressed: () {
Get.to( Get.to(
FullScreenMediaView(item: item), FullScreenMediaView(item: currentItem),
fullscreenDialog: true, fullscreenDialog: true,
); );
}, },
),
IconButton(
icon: const Icon(Icons.download),
onPressed: () async {
await _downloadMedia(item);
},
),
PopupMenuButton<ShareAction>(
onSelected: (value) => _handleShareAction(value, item),
itemBuilder: (context) => _shareMenuItems,
icon: const Icon(Icons.share),
),
Builder(
builder: (context) => IconButton(
icon: const Icon(Icons.menu),
onPressed: () {
Scaffold.of(context).openEndDrawer();
},
),
),
],
), ),
body: SingleChildScrollView( IconButton(
child: Column( icon: const Icon(Icons.download),
crossAxisAlignment: CrossAxisAlignment.stretch, onPressed: () async => await _downloadMedia(currentItem),
children: [ ),
AnimatedBuilder( PopupMenuButton<ShareAction>(
animation: _pageController!, onSelected: (value) => _handleShareAction(value, currentItem),
builder: (context, child) { itemBuilder: (context) => _shareMenuItems,
return buildAnimatedTransition( icon: const Icon(Icons.share),
context: context, ),
pageController: _pageController!, Builder(
index: index, builder: (context) => IconButton(
controller: mediaController, icon: const Icon(Icons.menu),
child: child!, onPressed: () => Scaffold.of(context).openEndDrawer(),
); ),
}, ),
child: Obx( ],
() => _buildMedia(item, index == _currentIndex.value), ),
), body: PageView.builder(
), controller: _pageController!,
const SizedBox(height: 16), itemCount: mediaController.items.length,
if (isReady) onPageChanged: _onPageChanged,
Padding( itemBuilder: (context, index) {
padding: const EdgeInsets.symmetric(horizontal: 16.0), final MediaItem item = mediaController.items[index];
child: Column( final bool isReady = _readyItemIds.contains(item.id);
crossAxisAlignment: CrossAxisAlignment.center, final ScrollController scrollController = ScrollController();
children: [ final PullexRefreshController refreshController =
Wrap( _refreshControllers.putIfAbsent(
spacing: 6.0, item.id,
runSpacing: 4.0, () => PullexRefreshController(),
alignment: WrapAlignment.center, );
children: [
...item.tags?.map( return Stack(
(tag) => ActionTag( children: [
tag, PullexRefresh(
(tag.tag == 'sfw' || tag.tag == 'nsfw') onRefresh: () => _onRefresh(item.id, refreshController),
? (onTagTap) => {} header: const WaterDropHeader(),
: (onTagTap) { controller: refreshController,
mediaController.setTag(onTagTap); child: CustomScrollView(
Get.offAllNamed('/'); controller: scrollController,
}, slivers: [
), SliverToBoxAdapter(
) ?? child: AnimatedBuilder(
[], animation: _pageController!,
], builder: (context, child) {
return buildAnimatedTransition(
context: context,
pageController: _pageController!,
index: index,
child: child!,
);
},
child: Obx(
() =>
_buildMedia(item, index == _currentIndex.value),
), ),
Obx( ),
() => Visibility( ),
visible: authController.isLoggedIn, if (isReady)
child: Padding( SliverFillRemaining(
padding: const EdgeInsets.only(top: 20.0), hasScrollBody: false,
child: FavoriteSection( fillOverscroll: true,
item: item, child: GestureDetector(
index: index, onTap: () => settingsController.hideVideoControls(),
), behavior: HitTestBehavior.translucent,
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [TagSection(tags: item.tags ?? [])],
), ),
), ),
), ),
], ),
const SliverToBoxAdapter(
child: SafeArea(child: SizedBox.shrink()),
), ),
) ],
else ),
const SizedBox.shrink(), ),
], Obx(() {
), if (!authController.isLoggedIn) {
), return const SizedBox.shrink();
persistentFooterButtons: mediaController.tag.value != null }
? [TagFooter()] final MediaItem currentItem =
: null, mediaController.items[_currentIndex.value];
); return DraggableScrollableSheet(
}, initialChildSize: 0.11,
), minChildSize: 0.11,
); maxChildSize: 0.245,
snap: true,
builder: (context, scrollController) => ListView(
controller: scrollController,
padding: const EdgeInsets.only(left: 16, right: 16),
children: [
FavoriteSection(
item: currentItem,
index: _currentIndex.value,
),
const SizedBox(height: 16),
Text(
"Dateigröße: ${(currentItem.size / 1024).toStringAsFixed(1)} KB",
style: Theme.of(context).textTheme.bodySmall,
),
Text(
"Typ: ${currentItem.mime}",
style: Theme.of(context).textTheme.bodySmall,
),
Text(
"ID: ${currentItem.id}",
style: Theme.of(context).textTheme.bodySmall,
),
Text(
"Hochgeladen am: ${DateTime.fromMillisecondsSinceEpoch(currentItem.stamp * 1000)}",
style: Theme.of(context).textTheme.bodySmall,
),
],
),
);
}),
],
);
},
),
persistentFooterButtons: mediaController.tag.value != null
? [TagFooter()]
: null,
);
});
} }
} }

View File

@ -8,6 +8,7 @@ import 'package:f0ckapp/utils/customsearchdelegate.dart';
import 'package:f0ckapp/widgets/end_drawer.dart'; import 'package:f0ckapp/widgets/end_drawer.dart';
import 'package:f0ckapp/widgets/filter_bar.dart'; import 'package:f0ckapp/widgets/filter_bar.dart';
import 'package:f0ckapp/widgets/media_tile.dart'; import 'package:f0ckapp/widgets/media_tile.dart';
import 'package:f0ckapp/controller/settingscontroller.dart';
import 'package:f0ckapp/controller/mediacontroller.dart'; import 'package:f0ckapp/controller/mediacontroller.dart';
class MediaGrid extends StatefulWidget { class MediaGrid extends StatefulWidget {
@ -20,6 +21,7 @@ class MediaGrid extends StatefulWidget {
class _MediaGrid extends State<MediaGrid> { class _MediaGrid extends State<MediaGrid> {
final ScrollController _scrollController = ScrollController(); final ScrollController _scrollController = ScrollController();
final MediaController _mediaController = Get.put(MediaController()); final MediaController _mediaController = Get.put(MediaController());
final SettingsController _settingsController = Get.put(SettingsController());
final PullexRefreshController _refreshController = PullexRefreshController( final PullexRefreshController _refreshController = PullexRefreshController(
initialRefresh: false, initialRefresh: false,
); );
@ -35,6 +37,7 @@ class _MediaGrid extends State<MediaGrid> {
_body = _MediaGridBody( _body = _MediaGridBody(
refreshController: _refreshController, refreshController: _refreshController,
mediaController: _mediaController, mediaController: _mediaController,
settingsController: _settingsController,
scrollController: _scrollController, scrollController: _scrollController,
); );
} }
@ -52,7 +55,7 @@ class _MediaGrid extends State<MediaGrid> {
() => Scaffold( () => Scaffold(
endDrawer: const EndDrawer(), endDrawer: const EndDrawer(),
endDrawerEnableOpenDragGesture: endDrawerEnableOpenDragGesture:
_mediaController.drawerSwipeEnabled.value, _settingsController.drawerSwipeEnabled.value,
bottomNavigationBar: FilterBar(scrollController: _scrollController), bottomNavigationBar: FilterBar(scrollController: _scrollController),
appBar: _appBar, appBar: _appBar,
body: _body, body: _body,
@ -121,20 +124,23 @@ class _MediaGridBody extends StatelessWidget {
const _MediaGridBody({ const _MediaGridBody({
required this.refreshController, required this.refreshController,
required this.mediaController, required this.mediaController,
required this.settingsController,
required this.scrollController, required this.scrollController,
}); });
final PullexRefreshController refreshController; final PullexRefreshController refreshController;
final MediaController mediaController; final MediaController mediaController;
final SettingsController settingsController;
final ScrollController scrollController; final ScrollController scrollController;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return PullexRefresh( return PullexRefresh(
controller: refreshController, controller: refreshController,
enablePullDown: true, enablePullDown: true,
enablePullUp: true, enablePullUp: true,
header: const MaterialHeader(), header: const WaterDropHeader(),
onRefresh: () async { onRefresh: () async {
try { try {
await mediaController.handleRefresh(); await mediaController.handleRefresh();
@ -157,7 +163,7 @@ class _MediaGridBody extends StatelessWidget {
shrinkWrap: true, shrinkWrap: true,
padding: const EdgeInsets.all(4), padding: const EdgeInsets.all(4),
itemCount: mediaController.items.length, itemCount: mediaController.items.length,
gridDelegate: mediaController.crossAxisCount.value == 0 gridDelegate: settingsController.crossAxisCount.value == 0
? const SliverGridDelegateWithMaxCrossAxisExtent( ? const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 150, maxCrossAxisExtent: 150,
crossAxisSpacing: 5, crossAxisSpacing: 5,
@ -165,7 +171,7 @@ class _MediaGridBody extends StatelessWidget {
childAspectRatio: 1, childAspectRatio: 1,
) )
: SliverGridDelegateWithFixedCrossAxisCount( : SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: mediaController.crossAxisCount.value, crossAxisCount: settingsController.crossAxisCount.value,
crossAxisSpacing: 5, crossAxisSpacing: 5,
mainAxisSpacing: 5, mainAxisSpacing: 5,
childAspectRatio: 1, childAspectRatio: 1,

View File

@ -4,7 +4,7 @@ import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:f0ckapp/controller/localizationcontroller.dart'; import 'package:f0ckapp/controller/localizationcontroller.dart';
import 'package:f0ckapp/controller/mediacontroller.dart'; import 'package:f0ckapp/controller/settingscontroller.dart';
import 'package:f0ckapp/utils/animatedtransition.dart'; import 'package:f0ckapp/utils/animatedtransition.dart';
class SettingsPage extends StatefulWidget { class SettingsPage extends StatefulWidget {
@ -15,8 +15,8 @@ class SettingsPage extends StatefulWidget {
} }
class _SettingsPageState extends State<SettingsPage> { class _SettingsPageState extends State<SettingsPage> {
final MediaController controller = Get.find(); final SettingsController settingsController = Get.find<SettingsController>();
final LocalizationController localizationController = Get.find(); final LocalizationController localizationController = Get.find<LocalizationController>();
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@ -34,7 +34,7 @@ class _SettingsPageState extends State<SettingsPage> {
title: Text('settings_numberofcolumns_title'.tr), title: Text('settings_numberofcolumns_title'.tr),
trailing: Obx( trailing: Obx(
() => DropdownButton<int>( () => DropdownButton<int>(
value: controller.crossAxisCount.value, value: settingsController.crossAxisCount.value,
dropdownColor: const Color.fromARGB(255, 43, 43, 43), dropdownColor: const Color.fromARGB(255, 43, 43, 43),
iconEnabledColor: Colors.white, iconEnabledColor: Colors.white,
items: [0, 3, 4, 5].map((int value) { items: [0, 3, 4, 5].map((int value) {
@ -51,7 +51,7 @@ class _SettingsPageState extends State<SettingsPage> {
}).toList(), }).toList(),
onChanged: (int? newValue) async { onChanged: (int? newValue) async {
if (newValue != null) { if (newValue != null) {
await controller.setCrossAxisCount(newValue); await settingsController.setCrossAxisCount(newValue);
} }
}, },
), ),
@ -62,7 +62,7 @@ class _SettingsPageState extends State<SettingsPage> {
title: Text('settings_pageanimation_title'.tr), title: Text('settings_pageanimation_title'.tr),
trailing: Obx( trailing: Obx(
() => DropdownButton<PageTransition>( () => DropdownButton<PageTransition>(
value: controller.transitionType.value, value: settingsController.transitionType.value,
dropdownColor: const Color.fromARGB(255, 43, 43, 43), dropdownColor: const Color.fromARGB(255, 43, 43, 43),
iconEnabledColor: Colors.white, iconEnabledColor: Colors.white,
items: PageTransition.values.map((PageTransition type) { items: PageTransition.values.map((PageTransition type) {
@ -91,7 +91,7 @@ class _SettingsPageState extends State<SettingsPage> {
}).toList(), }).toList(),
onChanged: (PageTransition? newValue) async { onChanged: (PageTransition? newValue) async {
if (newValue != null) { if (newValue != null) {
await controller.setTransitionType(newValue); await settingsController.setTransitionType(newValue);
} }
}, },
), ),
@ -102,9 +102,9 @@ class _SettingsPageState extends State<SettingsPage> {
SwitchListTile( SwitchListTile(
title: Text('settings_drawer_title'.tr), title: Text('settings_drawer_title'.tr),
subtitle: Text('settings_drawer_subtitle'.tr), subtitle: Text('settings_drawer_subtitle'.tr),
value: controller.drawerSwipeEnabled.value, value: settingsController.drawerSwipeEnabled.value,
onChanged: (bool value) async { onChanged: (bool value) async {
await controller.setDrawerSwipeEnabled(value); await settingsController.setDrawerSwipeEnabled(value);
setState(() {}); setState(() {});
}, },
), ),

View File

@ -1,12 +1,11 @@
import 'package:encrypt_shared_preferences/provider.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:f0ckapp/controller/authcontroller.dart';
import 'package:f0ckapp/models/item.dart'; import 'package:f0ckapp/models/item.dart';
import 'package:f0ckapp/models/feed.dart'; import 'package:f0ckapp/models/feed.dart';
class ApiService extends GetConnect { class ApiService extends GetConnect {
final EncryptedSharedPreferencesAsync storage = final AuthController _authController = Get.find<AuthController>();
EncryptedSharedPreferencesAsync.getInstance();
Future<Feed> fetchItems({ Future<Feed> fetchItems({
int? older, int? older,
@ -16,7 +15,7 @@ class ApiService extends GetConnect {
int random = 0, int random = 0,
String? tag, String? tag,
}) async { }) async {
String? token = await storage.getString('token'); String? token = _authController.token.value;
final params = <String, String>{ final params = <String, String>{
'type': type.toString(), 'type': type.toString(),
'mode': mode.toString(), 'mode': mode.toString(),
@ -32,7 +31,7 @@ class ApiService extends GetConnect {
} }
final Response<dynamic> response = await get( final Response<dynamic> response = await get(
'https://api.f0ck.me/items_new/get', 'https://api.f0ck.me/items/get',
query: params, query: params,
headers: headers, headers: headers,
); );
@ -42,18 +41,40 @@ class ApiService extends GetConnect {
feed.items.sort((a, b) => b.id.compareTo(a.id)); feed.items.sort((a, b) => b.id.compareTo(a.id));
return feed; return feed;
} else { } else {
if (Get.isSnackbarOpen == false) { if (!Get.isSnackbarOpen) {
Get.snackbar('Fehler', 'Fehler beim Laden der Items'); Get.snackbar('Fehler', 'Fehler beim Laden der Items');
} }
throw Exception('Fehler beim Laden der Items'); throw Exception('Fehler beim Laden der Items');
} }
} }
Future<MediaItem> fetchItemById(int itemId) async {
String? token = _authController.token.value;
final Map<String, String> headers = <String, String>{};
if (token != null && token.isNotEmpty) {
headers['Authorization'] = 'Bearer $token';
}
final Response<dynamic> response = await get(
'https://api.f0ck.me/item/$itemId',
headers: headers,
);
if (response.status.code == 200 && response.body is Map<String, dynamic>) {
return MediaItem.fromJson(response.body as Map<String, dynamic>);
} else {
if (!Get.isSnackbarOpen) {
Get.snackbar('Fehler', 'Fehler beim Laden des Items');
}
throw Exception('Fehler beim Laden des Items');
}
}
Future<List<Favorite>?> toggleFavorite( Future<List<Favorite>?> toggleFavorite(
MediaItem item, MediaItem item,
bool isFavorite, bool isFavorite,
) async { ) async {
String? token = await storage.getString('token'); String? token = _authController.token.value;
if (token == null || token.isEmpty) return null; if (token == null || token.isEmpty) return null;
final Map<String, String> headers = { final Map<String, String> headers = {

View File

@ -1,6 +1,8 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:f0ckapp/controller/mediacontroller.dart'; import 'package:get/get.dart';
import 'package:f0ckapp/controller/settingscontroller.dart';
enum PageTransition { opacity, scale, slide, rotate, flip } enum PageTransition { opacity, scale, slide, rotate, flip }
@ -9,17 +11,17 @@ Widget buildAnimatedTransition({
required Widget child, required Widget child,
required PageController pageController, required PageController pageController,
required int index, required int index,
required MediaController controller,
}) { }) {
final SettingsController settingsController = Get.find<SettingsController>();
final double value = pageController.position.haveDimensions final double value = pageController.position.haveDimensions
? pageController.page! - index ? pageController.page! - index
: 0; : 0;
switch (controller.transitionType.value) { switch (settingsController.transitionType.value) {
case PageTransition.opacity: case PageTransition.opacity:
return Opacity( return Opacity(
opacity: Curves.easeOut.transform(1 - value.abs().clamp(0.0, 1.0)), opacity: Curves.easeOut.transform(1 - value.abs().clamp(0.0, 1.0)),
child: Transform(transform: Matrix4.identity(), child: child), child: child,
); );
case PageTransition.scale: case PageTransition.scale:
return Transform.scale( return Transform.scale(
@ -29,10 +31,7 @@ Widget buildAnimatedTransition({
child: child, child: child,
); );
case PageTransition.slide: case PageTransition.slide:
return Transform.translate( return child;
offset: Offset(300 * value.abs(), 0),
child: child,
);
case PageTransition.rotate: case PageTransition.rotate:
return Opacity( return Opacity(
opacity: (1 - value.abs()).clamp(0.0, 1.0), opacity: (1 - value.abs()).clamp(0.0, 1.0),

View File

@ -4,13 +4,13 @@ import 'dart:convert';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import 'package:f0ckapp/controller/mediacontroller.dart'; import 'package:f0ckapp/controller/mediacontroller.dart';
import 'package:f0ckapp/models/suggestion.dart'; import 'package:f0ckapp/models/suggestion.dart';
class CustomSearchDelegate extends SearchDelegate<String> { class CustomSearchDelegate extends SearchDelegate<String> {
final MediaController controller = Get.find<MediaController>(); final MediaController controller = Get.find<MediaController>();
final GetConnect http = GetConnect();
Timer? _debounceTimer; Timer? _debounceTimer;
List<Suggestion>? _suggestions; List<Suggestion>? _suggestions;
bool _isLoading = false; bool _isLoading = false;
@ -48,14 +48,16 @@ class CustomSearchDelegate extends SearchDelegate<String> {
} }
Future<List<Suggestion>> fetchSuggestions(String query) async { Future<List<Suggestion>> fetchSuggestions(String query) async {
final Uri uri = Uri.parse('https://api.f0ck.me/search/?q=$query'); final String url = 'https://api.f0ck.me/search/?q=$query';
try { try {
final http.Response response = await http final Response<dynamic> response = await http
.get(uri) .get(url)
.timeout(const Duration(seconds: 5)); .timeout(const Duration(seconds: 5));
if (response.statusCode == 200) { if (response.statusCode == 200) {
final dynamic decoded = jsonDecode(response.body); final dynamic decoded = response.body is String
? jsonDecode(response.body)
: response.body;
if (decoded is List) { if (decoded is List) {
final suggestions = decoded final suggestions = decoded
.map((item) => Suggestion.fromJson(item as Map<String, dynamic>)) .map((item) => Suggestion.fromJson(item as Map<String, dynamic>))
@ -66,7 +68,9 @@ class CustomSearchDelegate extends SearchDelegate<String> {
throw Exception('Unerwartetes Format: Es wurde eine Liste erwartet.'); throw Exception('Unerwartetes Format: Es wurde eine Liste erwartet.');
} }
} else if (response.statusCode == 400) { } else if (response.statusCode == 400) {
final dynamic error = jsonDecode(response.body); final dynamic error = response.body is String
? jsonDecode(response.body)
: response.body;
final String message = error is Map<String, dynamic> final String message = error is Map<String, dynamic>
? error['detail']?.toString() ?? 'Unbekannter Fehler.' ? error['detail']?.toString() ?? 'Unbekannter Fehler.'
: 'Unbekannter Fehler.'; : 'Unbekannter Fehler.';

View File

@ -28,11 +28,11 @@ class EndDrawer extends StatelessWidget {
children: [ children: [
Obx(() { Obx(() {
if (authController.token.value != null && if (authController.token.value != null &&
authController.avatarUrl.value != null) { authController.user.value?.avatarUrl != null) {
return DrawerHeader( return DrawerHeader(
decoration: BoxDecoration( decoration: BoxDecoration(
image: DecorationImage( image: DecorationImage(
image: NetworkImage(authController.avatarUrl.value!), image: NetworkImage(authController.user.value!.avatarUrl!),
fit: BoxFit.cover, fit: BoxFit.cover,
alignment: Alignment.topCenter, alignment: Alignment.topCenter,
), ),
@ -58,11 +58,11 @@ class EndDrawer extends StatelessWidget {
padding: const EdgeInsets.all(16.0), padding: const EdgeInsets.all(16.0),
child: Column( child: Column(
children: [ children: [
if (authController.username.value != null) if (authController.user.value?.username != null)
Padding( Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0), padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Text( child: Text(
'Hamlo ${authController.username.value!}', 'Hamlo ${authController.user.value?.username}',
style: const TextStyle(fontWeight: FontWeight.bold), style: const TextStyle(fontWeight: FontWeight.bold),
), ),
), ),

View File

@ -18,7 +18,7 @@ class FavoriteSection extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final bool isFavorite = final bool isFavorite =
item.favorites?.any((f) => f.userId == authController.userId.value) ?? item.favorites?.any((f) => f.userId == authController.user.value?.id) ??
false; false;
return Row( return Row(

View File

@ -16,7 +16,7 @@ class MediaTile extends StatelessWidget {
fit: StackFit.expand, fit: StackFit.expand,
children: [ children: [
CachedNetworkImage( CachedNetworkImage(
imageUrl: 'https://f0ck.me/t/${item.id}.webp', imageUrl: item.thumbnailUrl,
fit: BoxFit.cover, fit: BoxFit.cover,
placeholder: (context, url) => Container(color: Colors.grey[900]), placeholder: (context, url) => Container(color: Colors.grey[900]),
errorWidget: (context, url, error) => errorWidget: (context, url, error) =>

View File

@ -0,0 +1,62 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:f0ckapp/models/item.dart';
import 'package:f0ckapp/widgets/actiontag.dart';
import 'package:f0ckapp/controller/mediacontroller.dart';
class TagSection extends StatefulWidget {
final List<Tag> tags;
const TagSection({super.key, required this.tags});
@override
State<TagSection> createState() => _TagSectionState();
}
class _TagSectionState extends State<TagSection> {
bool _areTagsExpanded = false;
@override
Widget build(BuildContext context) {
final MediaController mediaController = Get.find<MediaController>();
final bool hasMoreTags = widget.tags.length > 5;
final List<Tag> tagsToShow = _areTagsExpanded
? widget.tags
: widget.tags.take(5).toList();
return Column(
children: [
Wrap(
spacing: 6.0,
runSpacing: 4.0,
alignment: WrapAlignment.center,
children: [
...tagsToShow.map(
(tag) => ActionTag(
tag,
(tag.tag == 'sfw' || tag.tag == 'nsfw')
? (onTagTap) => {}
: (onTagTap) {
mediaController.setTag(onTagTap);
Get.offAllNamed('/');
},
),
),
],
),
if (hasMoreTags)
TextButton(
onPressed: () {
setState(() => _areTagsExpanded = !_areTagsExpanded);
},
child: Text(
_areTagsExpanded
? 'Weniger anzeigen'
: 'Alle ${widget.tags.length} Tags anzeigen',
),
),
],
);
}
}

View File

@ -1,8 +1,10 @@
import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:cached_video_player_plus/cached_video_player_plus.dart'; import 'package:cached_video_player_plus/cached_video_player_plus.dart';
class VideoControlsOverlay extends StatelessWidget { class VideoControlsOverlay extends StatefulWidget {
final CachedVideoPlayerPlusController controller; final CachedVideoPlayerPlusController controller;
final VoidCallback onOverlayTap; final VoidCallback onOverlayTap;
final bool muted; final bool muted;
@ -16,101 +18,175 @@ class VideoControlsOverlay extends StatelessWidget {
required this.onMuteToggle, required this.onMuteToggle,
}); });
@override
State<VideoControlsOverlay> createState() => _VideoControlsOverlayState();
}
class _VideoControlsOverlayState extends State<VideoControlsOverlay> {
bool _showSeekIndicator = false;
bool _isRewinding = false;
Timer? _hideTimer;
@override
void dispose() {
_hideTimer?.cancel();
super.dispose();
}
void _handleDoubleTap(TapDownDetails details) {
final double screenWidth = MediaQuery.of(context).size.width;
final bool isRewind = details.globalPosition.dx < screenWidth / 2;
widget.onOverlayTap();
Future(() {
if (isRewind) {
final Duration newPosition =
widget.controller.value.position - const Duration(seconds: 10);
widget.controller.seekTo(
newPosition < Duration.zero ? Duration.zero : newPosition,
);
} else {
final Duration newPosition =
widget.controller.value.position + const Duration(seconds: 10);
final Duration duration = widget.controller.value.duration;
widget.controller.seekTo(
newPosition > duration ? duration : newPosition,
);
}
});
_hideTimer?.cancel();
setState(() {
_showSeekIndicator = true;
_isRewinding = isRewind;
});
_hideTimer = Timer(const Duration(milliseconds: 500), () {
setState(() => _showSeekIndicator = false);
});
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Stack( return Stack(
alignment: Alignment.center, alignment: Alignment.center,
children: [ children: [
Row( GestureDetector(
mainAxisAlignment: MainAxisAlignment.center, onTap: widget.onOverlayTap,
children: [ onDoubleTapDown: _handleDoubleTap,
_ControlButton(Icons.replay_10, () { child: Container(color: Colors.transparent),
onOverlayTap(); ),
Duration newPosition = AnimatedOpacity(
controller.value.position - const Duration(seconds: 10); opacity: _showSeekIndicator ? 1.0 : 0.0,
if (newPosition < Duration.zero) newPosition = Duration.zero; duration: const Duration(milliseconds: 200),
controller.seekTo(newPosition); child: Align(
}), alignment: _isRewinding
const SizedBox(width: 40), ? Alignment.centerLeft
_ControlButton( : Alignment.centerRight,
controller.value.isPlaying ? Icons.pause : Icons.play_arrow, child: Padding(
() { padding: const EdgeInsets.symmetric(horizontal: 40.0),
onOverlayTap(); child: Icon(
controller.value.isPlaying _isRewinding
? controller.pause() ? Icons.fast_rewind_rounded
: controller.play(); : Icons.fast_forward_rounded,
}, color: Colors.white70,
size: 64, size: 60,
),
), ),
const SizedBox(width: 40), ),
_ControlButton(Icons.forward_10, () { ),
onOverlayTap(); IconButton(
Duration newPosition = icon: Icon(
controller.value.position + const Duration(seconds: 10); widget.controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
if (newPosition > controller.value.duration) { size: 64,
newPosition = controller.value.duration; ),
} onPressed: () {
controller.seekTo(newPosition); widget.onOverlayTap();
}), widget.controller.value.isPlaying
], ? widget.controller.pause()
: widget.controller.play();
},
), ),
Positioned( Positioned(
right: 12, right: 12,
bottom: 12, bottom: 12,
child: _ControlButton(muted ? Icons.volume_off : Icons.volume_up, () { child: IconButton(
onOverlayTap(); icon: Icon(
onMuteToggle(); widget.muted ? Icons.volume_off : Icons.volume_up,
}, size: 16), size: 16,
),
onPressed: () {
widget.onOverlayTap();
widget.onMuteToggle();
},
),
), ),
Align( Align(
alignment: Alignment.bottomCenter, alignment: Alignment.bottomCenter,
child: Padding( child: Padding(
padding: const EdgeInsets.only(bottom: 0), padding: const EdgeInsets.only(bottom: 0),
child: Stack( child: LayoutBuilder(
clipBehavior: Clip.none, builder: (context, constraints) {
children: [ return Stack(
Positioned( clipBehavior: Clip.none,
left: 10, children: [
bottom: 12, Positioned(
child: Text( left: 10,
'${_formatDuration(controller.value.position)} / ${_formatDuration(controller.value.duration)}', bottom: 12,
style: const TextStyle(color: Colors.white, fontSize: 12), child: Text(
), '${_formatDuration(widget.controller.value.position)} / ${_formatDuration(widget.controller.value.duration)}',
), style: const TextStyle(
Listener( color: Colors.white,
onPointerDown: (_) { fontSize: 12,
onOverlayTap(); ),
},
child: VideoProgressIndicator(
controller,
allowScrubbing: true,
padding: const EdgeInsets.only(top: 25.0),
colors: const VideoProgressColors(
playedColor: Colors.red,
backgroundColor: Colors.grey,
bufferedColor: Colors.white54,
),
),
),
if (controller.value.duration.inMilliseconds > 0)
Positioned(
left:
(controller.value.position.inMilliseconds /
controller.value.duration.inMilliseconds) *
MediaQuery.of(context).size.width -
6,
bottom: -4,
child: Container(
width: 12,
height: 12,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.red,
border: Border.all(color: Colors.red, width: 2),
), ),
), ),
), Listener(
], onPointerDown: (_) {
widget.onOverlayTap();
},
child: VideoProgressIndicator(
widget.controller,
allowScrubbing: true,
padding: const EdgeInsets.only(top: 25.0),
colors: VideoProgressColors(
playedColor: Theme.of(context).colorScheme.primary,
backgroundColor: Theme.of(
context,
).colorScheme.surface.withValues(alpha: 0.5),
bufferedColor: Theme.of(
context,
).colorScheme.secondary.withValues(alpha: 0.5),
),
),
),
if (widget.controller.value.duration.inMilliseconds > 0)
Positioned(
left:
(widget.controller.value.position.inMilliseconds /
widget
.controller
.value
.duration
.inMilliseconds) *
constraints.maxWidth -
6,
bottom: -4,
child: Container(
width: 12,
height: 12,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Theme.of(context).colorScheme.primary,
border: Border.all(
color: Theme.of(context).colorScheme.primary,
width: 2,
),
),
),
),
],
);
},
), ),
), ),
), ),
@ -118,30 +194,9 @@ class VideoControlsOverlay extends StatelessWidget {
); );
} }
String _formatDuration(Duration duration) { String _formatDuration(Duration? duration) {
if (duration == null) return '00:00';
String twoDigits(int n) => n.toString().padLeft(2, '0'); String twoDigits(int n) => n.toString().padLeft(2, '0');
return "${twoDigits(duration.inMinutes % 60)}:${twoDigits(duration.inSeconds % 60)}"; return "${twoDigits(duration.inMinutes % 60)}:${twoDigits(duration.inSeconds % 60)}";
} }
} }
class _ControlButton extends StatelessWidget {
final IconData icon;
final VoidCallback onPressed;
final double size;
const _ControlButton(this.icon, this.onPressed, {this.size = 24});
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.black.withValues(alpha: 0.4),
),
child: IconButton(
icon: Icon(icon, size: size),
onPressed: onPressed,
),
);
}
}

View File

@ -8,6 +8,7 @@ import 'package:get/get.dart';
import 'package:f0ckapp/models/item.dart'; import 'package:f0ckapp/models/item.dart';
import 'package:f0ckapp/widgets/video_controls_overlay.dart'; import 'package:f0ckapp/widgets/video_controls_overlay.dart';
import 'package:f0ckapp/controller/settingscontroller.dart';
import 'package:f0ckapp/controller/mediacontroller.dart'; import 'package:f0ckapp/controller/mediacontroller.dart';
class VideoWidget extends StatefulWidget { class VideoWidget extends StatefulWidget {
@ -29,9 +30,12 @@ class VideoWidget extends StatefulWidget {
} }
class _VideoWidgetState extends State<VideoWidget> { class _VideoWidgetState extends State<VideoWidget> {
final MediaController controller = Get.find<MediaController>(); final MediaController mediaController = Get.find<MediaController>();
late CachedVideoPlayerPlusController _controller; final SettingsController settingsController = Get.find<SettingsController>();
late CachedVideoPlayerPlusController videoController;
late Worker _muteWorker; late Worker _muteWorker;
late Worker _timerResetWorker;
late Worker _hideControlsWorker;
bool _showControls = false; bool _showControls = false;
Timer? _hideControlsTimer; Timer? _hideControlsTimer;
@ -39,38 +43,60 @@ class _VideoWidgetState extends State<VideoWidget> {
void initState() { void initState() {
super.initState(); super.initState();
_initController(); _initController();
_muteWorker = ever(controller.muted, (bool muted) { _muteWorker = ever(settingsController.muted, (bool muted) {
if (_controller.value.isInitialized) { if (videoController.value.isInitialized) {
_controller.setVolume(muted ? 0.0 : 1.0); videoController.setVolume(muted ? 0.0 : 1.0);
}
});
_timerResetWorker = ever(settingsController.videoControlsTimerNotifier, (
_,
) {
if (widget.isActive && mounted) {
if (!_showControls) {
setState(() => _showControls = true);
}
_startHideControlsTimer();
}
});
_hideControlsWorker = ever(settingsController.hideControlsNotifier, (_) {
if (mounted && _showControls) {
setState(() => _showControls = false);
_hideControlsTimer?.cancel();
} }
}); });
} }
Future<void> _initController() async { Future<void> _initController() async {
_controller = CachedVideoPlayerPlusController.networkUrl( videoController = CachedVideoPlayerPlusController.networkUrl(
Uri.parse(widget.details.mediaUrl), Uri.parse(widget.details.mediaUrl),
videoPlayerOptions: VideoPlayerOptions(mixWithOthers: true),
); );
await _controller.initialize(); await videoController.initialize();
widget.onInitialized?.call(); widget.onInitialized?.call();
if (!mounted) return; if (!mounted) return;
setState(() {}); videoController.setLooping(true);
_controller.addListener(() => setState(() {})); videoController.setVolume(settingsController.muted.value ? 0.0 : 1.0);
_controller.setLooping(true);
_controller.setVolume(controller.muted.value ? 0.0 : 1.0);
if (widget.isActive) { if (widget.isActive) {
_controller.play(); videoController.play();
} }
} }
@override @override
void didUpdateWidget(covariant VideoWidget oldWidget) { void didUpdateWidget(covariant VideoWidget oldWidget) {
super.didUpdateWidget(oldWidget); super.didUpdateWidget(oldWidget);
if (widget.details.mediaUrl != oldWidget.details.mediaUrl) {
videoController.dispose();
_initController();
return;
}
if (widget.isActive != oldWidget.isActive) { if (widget.isActive != oldWidget.isActive) {
if (widget.isActive) { if (widget.isActive) {
_controller.play(); videoController.play();
} else { } else {
_controller.pause(); videoController.pause();
} }
} }
} }
@ -78,26 +104,41 @@ class _VideoWidgetState extends State<VideoWidget> {
@override @override
void dispose() { void dispose() {
_muteWorker.dispose(); _muteWorker.dispose();
_controller.dispose(); _timerResetWorker.dispose();
_hideControlsWorker.dispose();
videoController.dispose();
_hideControlsTimer?.cancel(); _hideControlsTimer?.cancel();
super.dispose(); super.dispose();
} }
void _onTap({bool ctrlButton = false}) { void _startHideControlsTimer() {
if (!ctrlButton) { _hideControlsTimer?.cancel();
setState(() => _showControls = !_showControls); _hideControlsTimer = Timer(const Duration(seconds: 3), () {
} if (mounted) {
if (_showControls) {
_hideControlsTimer?.cancel();
_hideControlsTimer = Timer(const Duration(seconds: 2), () {
setState(() => _showControls = false); setState(() => _showControls = false);
}); }
});
}
void _onTap({bool ctrlButton = false}) {
if (ctrlButton) {
_startHideControlsTimer();
return;
}
final bool newShowState = !_showControls;
setState(() => _showControls = newShowState);
if (newShowState) {
_startHideControlsTimer();
} else {
_hideControlsTimer?.cancel();
} }
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final bool muted = controller.muted.value; final bool muted = settingsController.muted.value;
bool isAudio = widget.details.mime.startsWith('audio'); bool isAudio = widget.details.mime.startsWith('audio');
Widget mediaContent; Widget mediaContent;
@ -112,36 +153,43 @@ class _VideoWidgetState extends State<VideoWidget> {
), ),
); );
} else { } else {
mediaContent = _controller.value.isInitialized mediaContent = videoController.value.isInitialized
? CachedVideoPlayerPlus(_controller) ? CachedVideoPlayerPlus(videoController)
: const Center(child: CircularProgressIndicator()); : const Center(child: CircularProgressIndicator());
} }
return AspectRatio( return AspectRatio(
aspectRatio: _controller.value.isInitialized aspectRatio: videoController.value.isInitialized
? _controller.value.aspectRatio ? videoController.value.aspectRatio
: (isAudio ? 16 / 9 : 9 / 16), : (isAudio ? 16 / 9 : 9 / 16),
child: Stack( child: Stack(
alignment: Alignment.center, alignment: Alignment.center,
children: [ children: [
GestureDetector(onTap: _onTap, child: mediaContent), GestureDetector(onTap: _onTap, child: mediaContent),
if (_controller.value.isInitialized && _showControls) AnimatedBuilder(
Positioned.fill( animation: videoController,
child: GestureDetector( builder: (context, child) {
onTap: _onTap, if (videoController.value.isInitialized && _showControls) {
child: Container( return Positioned.fill(
color: Colors.black.withValues(alpha: 0.5), child: GestureDetector(
child: VideoControlsOverlay( onTap: _onTap,
controller: _controller, child: Container(
onOverlayTap: () => _onTap(ctrlButton: true), color: Colors.black.withValues(alpha: 0.5),
muted: muted, child: VideoControlsOverlay(
onMuteToggle: () { controller: videoController,
controller.toggleMuted(); onOverlayTap: () => _onTap(ctrlButton: true),
}, muted: muted,
onMuteToggle: () {
settingsController.toggleMuted();
},
),
),
), ),
), );
), }
), return const SizedBox.shrink();
},
),
], ],
), ),
); );

View File

@ -249,7 +249,7 @@ packages:
source: hosted source: hosted
version: "0.15.6" version: "0.15.6"
http: http:
dependency: "direct main" dependency: transitive
description: description:
name: http name: http
sha256: "2c11f3f94c687ee9bad77c171151672986360b2b001d109814ee7140b2cf261b" sha256: "2c11f3f94c687ee9bad77c171151672986360b2b001d109814ee7140b2cf261b"
@ -268,10 +268,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: js name: js
sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3 sha256: "53385261521cc4a0c4658fd0ad07a7d14591cf8fc33abbceae306ddb974888dc"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.6.7" version: "0.7.2"
json_rpc_2: json_rpc_2:
dependency: transitive dependency: transitive
description: description:
@ -761,10 +761,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: vm_service name: vm_service
sha256: ddfa8d30d89985b96407efce8acbdd124701f96741f2d981ca860662f1c0dc02 sha256: "45caa6c5917fa127b5dbcfbd1fa60b14e583afdc08bfc96dda38886ca252eb60"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "15.0.0" version: "15.0.2"
web: web:
dependency: transitive dependency: transitive
description: description:
@ -801,10 +801,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: win32 name: win32
sha256: "329edf97fdd893e0f1e3b9e88d6a0e627128cc17cc316a8d67fda8f1451178ba" sha256: "66814138c3562338d05613a6e368ed8cfb237ad6d64a9e9334be3f309acfca03"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "5.13.0" version: "5.14.0"
xdg_directories: xdg_directories:
dependency: transitive dependency: transitive
description: description:

View File

@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts # In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix. # of the product and file versions while build-number is used as the build suffix.
version: 1.4.1+62 version: 1.4.6+67
environment: environment:
sdk: ^3.9.0-100.2.beta sdk: ^3.9.0-100.2.beta
@ -30,7 +30,6 @@ environment:
dependencies: dependencies:
flutter: flutter:
sdk: flutter sdk: flutter
http: ^1.4.0
get: ^4.7.2 get: ^4.7.2
encrypt_shared_preferences: ^0.9.9 encrypt_shared_preferences: ^0.9.9
cached_network_image: ^3.4.1 cached_network_image: ^3.4.1