Attachments

This commit is contained in:
LittleSheep 2024-05-18 22:23:36 +08:00
parent 2d66315922
commit 2fad1067fa
16 changed files with 577 additions and 23 deletions

View File

@ -1,5 +1,6 @@
import 'package:flutter/material.dart';
import 'package:get/route_manager.dart';
import 'package:get/get.dart';
import 'package:solian/providers/auth.dart';
import 'package:solian/router.dart';
import 'package:solian/theme.dart';
import 'package:solian/translations.dart';
@ -24,6 +25,9 @@ class SolianApp extends StatelessWidget {
translations: SolianMessages(),
locale: Get.deviceLocale,
fallbackLocale: const Locale('en', 'US'),
onInit: () {
Get.lazyPut(() => AuthProvider());
},
builder: (context, child) {
return Overlay(
initialEntries: [

View File

@ -63,7 +63,7 @@ class Post {
categories: json["categories"],
reactions: json["reactions"],
replies: json["replies"],
attachments: json["attachments"],
attachments: json["attachments"] != null ? List<String>.from(json["attachments"]) : null,
replyId: json["reply_id"],
repostId: json["repost_id"],
realmId: json["realm_id"],

100
lib/providers/auth.dart Normal file
View File

@ -0,0 +1,100 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:get/get.dart';
import 'package:get/get_connect/http/src/request/request.dart';
import 'package:solian/models/account.dart';
import 'package:solian/services.dart';
import 'package:oauth2/oauth2.dart' as oauth2;
class AuthProvider extends GetConnect {
final deviceEndpoint = Uri.parse('/api/notifications/subscribe');
final tokenEndpoint = Uri.parse('/api/auth/token');
final userinfoEndpoint = Uri.parse('/api/users/me');
final redirectUrl = Uri.parse('solian://auth');
static const clientId = 'solian';
static const clientSecret = '_F4%q2Eea3';
static const storage = FlutterSecureStorage();
@override
void onInit() {
httpClient.baseUrl = ServiceFinder.services['passport'];
applyAuthenticator();
}
oauth2.Credentials? credentials;
Future<Request<T?>> reqAuthenticator<T>(Request<T?> request) async {
if (credentials != null && credentials!.isExpired) {
final resp = await post('/api/auth/token', {
'refresh_token': credentials!.refreshToken,
'grant_type': 'refresh_token',
});
if (resp.statusCode != 200) {
throw Exception(resp.bodyString);
}
credentials = oauth2.Credentials(
resp.body['access_token'],
refreshToken: resp.body['refresh_token'],
idToken: resp.body['access_token'],
tokenEndpoint: tokenEndpoint,
expiration: DateTime.now().add(const Duration(minutes: 3)),
);
storage.write(key: 'auth_credentials', value: jsonEncode(credentials!.toJson()));
}
if (credentials != null) {
request.headers['Authorization'] = 'Bearer ${credentials!.accessToken}';
}
return request;
}
void applyAuthenticator() {
isAuthorized.then((status) async {
final content = await storage.read(key: 'auth_credentials');
credentials = oauth2.Credentials.fromJson(jsonDecode(content!));
if (status) {
httpClient.addAuthenticator(reqAuthenticator);
}
});
}
Future<oauth2.Credentials> signin(BuildContext context, String username, String password) async {
final resp = await oauth2.resourceOwnerPasswordGrant(
tokenEndpoint,
username,
password,
identifier: clientId,
secret: clientSecret,
scopes: ['*'],
basicAuth: false,
);
credentials = oauth2.Credentials(
resp.credentials.accessToken,
refreshToken: resp.credentials.refreshToken!,
idToken: resp.credentials.accessToken,
tokenEndpoint: tokenEndpoint,
expiration: DateTime.now().add(const Duration(minutes: 3)),
);
storage.write(key: 'auth_credentials', value: jsonEncode(credentials!.toJson()));
applyAuthenticator();
return credentials!;
}
void signout() {
storage.deleteAll();
}
Future<bool> get isAuthorized => storage.containsKey(key: 'auth_credentials');
Future<Response<Account>> get profile => get('/api/users/me', decoder: (data) => Account.fromJson(data));
}

View File

@ -0,0 +1,20 @@
import 'package:flutter/material.dart';
import 'package:solian/models/attachment.dart';
import 'package:solian/services.dart';
class AttachmentItem extends StatelessWidget {
final Attachment item;
const AttachmentItem({super.key, required this.item});
@override
Widget build(BuildContext context) {
return Hero(
tag: Key('a${item.uuid}'),
child: Image.network(
'${ServiceFinder.services['paperclip']}/api/attachments/${item.uuid}',
fit: BoxFit.cover,
),
);
}
}

View File

@ -0,0 +1,11 @@
import 'package:get/get.dart';
import 'package:solian/services.dart';
class AttachmentListProvider extends GetConnect {
@override
void onInit() {
httpClient.baseUrl = ServiceFinder.services['paperclip'];
}
Future<Response> getMetadata(String uuid) => get('/api/attachments/$uuid/meta');
}

View File

@ -53,17 +53,22 @@ class _HomeScreenState extends State<HomeScreen> {
}
return RefreshIndicator(
onRefresh: () => getPosts(),
onRefresh: () {
_data.clear();
_pageKey = 0;
_dataTotal = null;
return getPosts();
},
child: ListView.separated(
itemCount: _data.length,
itemBuilder: (BuildContext context, int index) {
final item = _data[index];
return InkWell(
child: PostItem(item: item).paddingSymmetric(horizontal: 18, vertical: 8),
return GestureDetector(
child: PostItem(key: Key('p${item.alias}'), item: item),
onTap: () {},
);
},
separatorBuilder: (_, __) => const Divider(thickness: 0.3),
separatorBuilder: (_, __) => const Divider(thickness: 0.3, height: 0.3),
),
);
}

View File

@ -7,11 +7,15 @@ class SolianMessages extends Translations {
'page': 'Page',
'home': 'Home',
'account': 'Account',
'matureContent': 'Mature Content',
'matureContentCaption': 'The content is rated and may not suitable for everyone to view'
},
'zh_CN': {
'page': '页面',
'home': '首页',
'account': '账号',
'matureContent': '成人内容',
'matureContentCaption': '该内容可能会对您的社会关系产生影响,请确认四下环境后再查看'
}
};
}

View File

@ -0,0 +1,162 @@
import 'dart:ui';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:solian/models/attachment.dart';
import 'package:solian/providers/content/attachment_item.dart';
import 'package:solian/providers/content/attachment_list.dart';
class AttachmentList extends StatefulWidget {
final List<String> attachmentsId;
const AttachmentList({super.key, required this.attachmentsId});
@override
State<AttachmentList> createState() => _AttachmentListState();
}
class _AttachmentListState extends State<AttachmentList> {
bool _isLoading = true;
bool _showMature = false;
double _aspectRatio = 1;
List<Attachment?> _attachmentsMeta = List.empty();
void getMetadataList() {
final AttachmentListProvider provider = Get.find();
if (widget.attachmentsId.isEmpty) {
return;
} else {
_attachmentsMeta = List.filled(widget.attachmentsId.length, null);
}
int progress = 0;
for (var idx = 0; idx < widget.attachmentsId.length; idx++) {
provider.getMetadata(widget.attachmentsId[idx]).then((resp) {
progress++;
_attachmentsMeta[idx] = Attachment.fromJson(resp.body);
if (progress == widget.attachmentsId.length) {
setState(() {
calculateAspectRatio();
_isLoading = false;
});
}
});
}
}
void calculateAspectRatio() {
int portrait = 0, square = 0, landscape = 0;
for (var entry in _attachmentsMeta) {
if (entry!.metadata?['ratio'] != null) {
if (entry.metadata!['ratio'] > 1) {
landscape++;
} else if (entry.metadata!['ratio'] == 1) {
square++;
} else {
portrait++;
}
}
}
if (portrait > square && portrait > landscape) {
_aspectRatio = 9 / 16;
}
if (landscape > square && landscape > portrait) {
_aspectRatio = 16 / 9;
} else {
_aspectRatio = 1;
}
}
@override
void initState() {
Get.lazyPut(() => AttachmentListProvider());
super.initState();
getMetadataList();
}
@override
Widget build(BuildContext context) {
if (widget.attachmentsId.isEmpty) {
return Container();
}
if (_isLoading) {
return AspectRatio(
aspectRatio: _aspectRatio,
child: Container(
decoration: BoxDecoration(color: Theme.of(context).colorScheme.surfaceVariant),
child: const Center(
child: CircularProgressIndicator(),
),
),
);
}
return CarouselSlider.builder(
options: CarouselOptions(
aspectRatio: _aspectRatio,
viewportFraction: 1,
enableInfiniteScroll: false,
),
itemCount: _attachmentsMeta.length,
itemBuilder: (context, idx, _) {
final element = _attachmentsMeta[idx];
return GestureDetector(
child: Container(
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(color: Theme.of(context).colorScheme.surfaceVariant),
child: Stack(
fit: StackFit.expand,
children: [
AttachmentItem(key: Key('a${element!.uuid}'), item: element),
if (element.isMature && !_showMature)
BackdropFilter(
filter: ImageFilter.blur(sigmaX: 20, sigmaY: 20),
child: Container(
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.5),
),
),
),
if (element.isMature && !_showMature)
Center(
child: Container(
constraints: const BoxConstraints(maxWidth: 280),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.visibility_off, color: Colors.white, size: 32),
const SizedBox(height: 8),
Text(
'matureContent'.tr,
style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 16),
),
Text(
'matureContentCaption'.tr,
style: const TextStyle(color: Colors.white),
textAlign: TextAlign.center,
),
],
),
),
),
],
),
),
onTap: () {
if (!_showMature && _attachmentsMeta.any((e) => e!.isMature)) {
setState(() => _showMature = true);
} else {
// Open detail box
}
},
);
},
);
}
}

View File

@ -4,6 +4,7 @@ import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:get/get_utils/get_utils.dart';
import 'package:solian/models/post.dart';
import 'package:solian/widgets/account/account_avatar.dart';
import 'package:solian/widgets/attachments/attachment_list.dart';
import 'package:timeago/timeago.dart' show format;
class PostItem extends StatefulWidget {
@ -18,27 +19,41 @@ class PostItem extends StatefulWidget {
class _PostItemState extends State<PostItem> {
@override
Widget build(BuildContext context) {
return Row(
return Column(
children: [
AccountAvatar(content: widget.item.author.avatar),
Expanded(
child: Column(
children: [
Row(
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
AccountAvatar(content: widget.item.author.avatar),
Expanded(
child: Column(
children: [
Text(widget.item.author.nick, style: const TextStyle(fontWeight: FontWeight.bold)).paddingOnly(left: 8),
Text(format(widget.item.createdAt, locale: 'en_short')).paddingOnly(left: 4),
Row(
children: [
Text(
widget.item.author.nick,
style: const TextStyle(fontWeight: FontWeight.bold),
).paddingOnly(left: 8),
Text(format(widget.item.createdAt, locale: 'en_short')).paddingOnly(left: 4),
],
),
Markdown(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
data: widget.item.content,
padding: const EdgeInsets.all(0),
).paddingSymmetric(horizontal: 8),
],
),
Markdown(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
data: widget.item.content,
padding: const EdgeInsets.all(0),
).paddingSymmetric(horizontal: 8),
],
),
)
)
],
).paddingOnly(
top: 18,
bottom: (widget.item.attachments?.isNotEmpty ?? false) ? 10 : 18,
right: 16,
left: 16,
),
AttachmentList(attachmentsId: widget.item.attachments ?? List.empty()),
],
);
}

View File

@ -6,6 +6,10 @@
#include "generated_plugin_registrant.h"
#include <flutter_secure_storage_linux/flutter_secure_storage_linux_plugin.h>
void fl_register_plugins(FlPluginRegistry* registry) {
g_autoptr(FlPluginRegistrar) flutter_secure_storage_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterSecureStorageLinuxPlugin");
flutter_secure_storage_linux_plugin_register_with_registrar(flutter_secure_storage_linux_registrar);
}

View File

@ -3,6 +3,7 @@
#
list(APPEND FLUTTER_PLUGIN_LIST
flutter_secure_storage_linux
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST

View File

@ -5,6 +5,10 @@
import FlutterMacOS
import Foundation
import flutter_secure_storage_macos
import path_provider_foundation
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
FlutterSecureStoragePlugin.register(with: registry.registrar(forPlugin: "FlutterSecureStoragePlugin"))
PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin"))
}

View File

@ -25,6 +25,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.1.1"
carousel_slider:
dependency: "direct main"
description:
name: carousel_slider
sha256: "9c695cc963bf1d04a47bd6021f68befce8970bcd61d24938e1fb0918cf5d9c42"
url: "https://pub.dev"
source: hosted
version: "4.2.1"
characters:
dependency: transitive
description:
@ -49,6 +57,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.18.0"
crypto:
dependency: transitive
description:
name: crypto
sha256: ff625774173754681d66daaf4a448684fb04b78f902da9cb3d308c19cc5e8bab
url: "https://pub.dev"
source: hosted
version: "3.0.3"
cupertino_icons:
dependency: "direct main"
description:
@ -65,11 +81,27 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.3.1"
ffi:
dependency: transitive
description:
name: ffi
sha256: "493f37e7df1804778ff3a53bd691d8692ddf69702cf4c1c1096a2e41b4779e21"
url: "https://pub.dev"
source: hosted
version: "2.1.2"
flutter:
dependency: "direct main"
description: flutter
source: sdk
version: "0.0.0"
flutter_animate:
dependency: "direct main"
description:
name: flutter_animate
sha256: "7c8a6594a9252dad30cc2ef16e33270b6248c4dedc3b3d06c86c4f3f4dc05ae5"
url: "https://pub.dev"
source: hosted
version: "4.5.0"
flutter_lints:
dependency: "direct dev"
description:
@ -86,6 +118,62 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.7.1"
flutter_secure_storage:
dependency: "direct main"
description:
name: flutter_secure_storage
sha256: "8496a89eea74e23f92581885f876455d9d460e71201405dffe5f55dfe1155864"
url: "https://pub.dev"
source: hosted
version: "9.2.1"
flutter_secure_storage_linux:
dependency: transitive
description:
name: flutter_secure_storage_linux
sha256: "4d91bfc23047422cbcd73ac684bc169859ee766482517c22172c86596bf1464b"
url: "https://pub.dev"
source: hosted
version: "1.2.1"
flutter_secure_storage_macos:
dependency: transitive
description:
name: flutter_secure_storage_macos
sha256: b768a7dab26d6186b68e2831b3104f8968154f0f4fdbf66e7c2dd7bdf299daaf
url: "https://pub.dev"
source: hosted
version: "3.1.1"
flutter_secure_storage_platform_interface:
dependency: transitive
description:
name: flutter_secure_storage_platform_interface
sha256: cf91ad32ce5adef6fba4d736a542baca9daf3beac4db2d04be350b87f69ac4a8
url: "https://pub.dev"
source: hosted
version: "1.1.2"
flutter_secure_storage_web:
dependency: transitive
description:
name: flutter_secure_storage_web
sha256: f4ebff989b4f07b2656fb16b47852c0aab9fed9b4ec1c70103368337bc1886a9
url: "https://pub.dev"
source: hosted
version: "1.2.1"
flutter_secure_storage_windows:
dependency: transitive
description:
name: flutter_secure_storage_windows
sha256: b20b07cb5ed4ed74fc567b78a72936203f587eba460af1df11281c9326cd3709
url: "https://pub.dev"
source: hosted
version: "3.1.2"
flutter_shaders:
dependency: transitive
description:
name: flutter_shaders
sha256: "02750b545c01ff4d8e9bbe8f27a7731aa3778402506c67daa1de7f5fc3f4befe"
url: "https://pub.dev"
source: hosted
version: "0.1.2"
flutter_test:
dependency: "direct dev"
description: flutter
@ -112,6 +200,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "14.1.1"
http:
dependency: transitive
description:
name: http
sha256: "761a297c042deedc1ffbb156d6e2af13886bb305c2a343a4d972504cd67dd938"
url: "https://pub.dev"
source: hosted
version: "1.2.1"
http_parser:
dependency: transitive
description:
name: http_parser
sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b"
url: "https://pub.dev"
source: hosted
version: "4.0.2"
intl:
dependency: transitive
description:
@ -120,6 +224,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.19.0"
js:
dependency: transitive
description:
name: js
sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3
url: "https://pub.dev"
source: hosted
version: "0.6.7"
leak_tracker:
dependency: transitive
description:
@ -192,6 +304,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.14.0"
oauth2:
dependency: "direct main"
description:
name: oauth2
sha256: c4013ef62be37744efdc0861878fd9e9285f34db1f9e331cc34100d7674feb42
url: "https://pub.dev"
source: hosted
version: "2.0.2"
path:
dependency: transitive
description:
@ -200,6 +320,70 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.9.0"
path_provider:
dependency: transitive
description:
name: path_provider
sha256: c9e7d3a4cd1410877472158bee69963a4579f78b68c65a2b7d40d1a7a88bb161
url: "https://pub.dev"
source: hosted
version: "2.1.3"
path_provider_android:
dependency: transitive
description:
name: path_provider_android
sha256: a248d8146ee5983446bf03ed5ea8f6533129a12b11f12057ad1b4a67a2b3b41d
url: "https://pub.dev"
source: hosted
version: "2.2.4"
path_provider_foundation:
dependency: transitive
description:
name: path_provider_foundation
sha256: f234384a3fdd67f989b4d54a5d73ca2a6c422fa55ae694381ae0f4375cd1ea16
url: "https://pub.dev"
source: hosted
version: "2.4.0"
path_provider_linux:
dependency: transitive
description:
name: path_provider_linux
sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279
url: "https://pub.dev"
source: hosted
version: "2.2.1"
path_provider_platform_interface:
dependency: transitive
description:
name: path_provider_platform_interface
sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334"
url: "https://pub.dev"
source: hosted
version: "2.1.2"
path_provider_windows:
dependency: transitive
description:
name: path_provider_windows
sha256: "8bc9f22eee8690981c22aa7fc602f5c85b497a6fb2ceb35ee5a5e5ed85ad8170"
url: "https://pub.dev"
source: hosted
version: "2.2.1"
platform:
dependency: transitive
description:
name: platform
sha256: "12220bb4b65720483f8fa9450b4332347737cf8213dd2840d8b2c823e47243ec"
url: "https://pub.dev"
source: hosted
version: "3.1.4"
plugin_platform_interface:
dependency: transitive
description:
name: plugin_platform_interface
sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02"
url: "https://pub.dev"
source: hosted
version: "2.1.8"
sky_engine:
dependency: transitive
description: flutter
@ -261,6 +445,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.6.1"
typed_data:
dependency: transitive
description:
name: typed_data
sha256: facc8d6582f16042dd49f2463ff1bd6e2c9ef9f3d5da3d9b087e244a7b564b3c
url: "https://pub.dev"
source: hosted
version: "1.3.2"
vector_math:
dependency: transitive
description:
@ -277,6 +469,30 @@ packages:
url: "https://pub.dev"
source: hosted
version: "13.0.0"
web:
dependency: transitive
description:
name: web
sha256: "97da13628db363c635202ad97068d47c5b8aa555808e7a9411963c533b449b27"
url: "https://pub.dev"
source: hosted
version: "0.5.1"
win32:
dependency: transitive
description:
name: win32
sha256: "0eaf06e3446824099858367950a813472af675116bf63f008a4c2a75ae13e9cb"
url: "https://pub.dev"
source: hosted
version: "5.5.0"
xdg_directories:
dependency: transitive
description:
name: xdg_directories
sha256: faea9dee56b520b55a566385b84f2e8de55e7496104adada9962e0bd11bcff1d
url: "https://pub.dev"
source: hosted
version: "1.0.4"
sdks:
dart: ">=3.3.4 <4.0.0"
flutter: ">=3.19.0"

View File

@ -39,6 +39,10 @@ dependencies:
get: ^4.6.6
timeago: ^3.6.1
flutter_markdown: ^0.7.1
flutter_animate: ^4.5.0
flutter_secure_storage: ^9.2.1
oauth2: ^2.0.2
carousel_slider: ^4.2.1
dev_dependencies:
flutter_test:

View File

@ -6,6 +6,9 @@
#include "generated_plugin_registrant.h"
#include <flutter_secure_storage_windows/flutter_secure_storage_windows_plugin.h>
void RegisterPlugins(flutter::PluginRegistry* registry) {
FlutterSecureStorageWindowsPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("FlutterSecureStorageWindowsPlugin"));
}

View File

@ -3,6 +3,7 @@
#
list(APPEND FLUTTER_PLUGIN_LIST
flutter_secure_storage_windows
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST