✨ Attachments
This commit is contained in:
@ -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: [
|
||||
|
@ -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
100
lib/providers/auth.dart
Normal 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));
|
||||
}
|
20
lib/providers/content/attachment_item.dart
Normal file
20
lib/providers/content/attachment_item.dart
Normal 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,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
11
lib/providers/content/attachment_list.dart
Normal file
11
lib/providers/content/attachment_list.dart
Normal 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');
|
||||
}
|
@ -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),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
@ -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': '该内容可能会对您的社会关系产生影响,请确认四下环境后再查看'
|
||||
}
|
||||
};
|
||||
}
|
||||
|
162
lib/widgets/attachments/attachment_list.dart
Normal file
162
lib/widgets/attachments/attachment_list.dart
Normal 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
|
||||
}
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
@ -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()),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
Reference in New Issue
Block a user