Files
tatuchat/lib/pages/apps/apps.dart
Welton Moura 6c689d1f34
Some checks failed
Main Deploy Workflow / deploy_web (push) Has been cancelled
Main Deploy Workflow / deploy_playstore_internal (push) Has been cancelled
Close stale issues and PRs / stale (push) Has been cancelled
feat: tela de apps com logos/menu de exclusao, correcao de tema nas mini apps e sidebar de navegacao
2026-09-19 00:08:35 -03:00

130 lines
4.5 KiB
Dart

// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
//
// SPDX-License-Identifier: AGPL-3.0-or-later
import 'dart:convert';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:material_ui/material_ui.dart';
import 'package:matrix/matrix.dart';
import 'package:tatchat/config/miniapp_config.dart';
import 'package:tatchat/config/setting_keys.dart';
import 'package:tatchat/utils/miniapp_meta.dart';
import 'package:tatchat/utils/miniapp_store.dart';
import 'package:tatchat/widgets/matrix.dart';
import 'apps_view.dart';
class Apps extends StatefulWidget {
const Apps({super.key});
@override
AppsController createState() => AppsController();
}
class AppsController extends State<Apps> {
Client get client => Matrix.of(context).client;
Future<void> installMiniApp(String appId) async {
await client.installMiniApp(appId);
if (!mounted) return;
setState(() {});
}
Future<void> uninstallMiniApp(String appId) async {
await client.uninstallMiniApp(appId);
if (!mounted) return;
setState(() {});
}
/// Lets the user pick a `.html` file from their device and imports it as a
/// custom mini app.
Future<void> importMiniAppFromFile() async {
final file = await FilePicker.pickFile(
type: FileType.custom,
allowedExtensions: ['html', 'htm'],
);
if (file == null) return;
final bytes = await file.readAsBytes();
await _importHtml(html: _decodeBytes(bytes));
if (!mounted) return;
setState(() {});
}
/// Fetches an HTML document from [url] and imports it as a custom mini app.
///
/// On web, the browser enforces CORS, so fetching a page that does not send
/// `Access-Control-Allow-Origin` fails with a `ClientException`. In that case
/// we transparently retry through a CORS proxy (if configured) so the import
/// still works.
Future<void> importMiniAppFromUrl(String url) async {
if (url.trim().isEmpty) return;
final response = await _fetchViaCorsProxy(Uri.parse(url));
if (response.statusCode != 200) {
throw Exception('${response.statusCode} ${response.reasonPhrase}');
}
await _importHtml(html: response.body);
if (!mounted) return;
setState(() {});
}
/// Fetches [url]. On web, if the initial request fails (usually because the
/// target server lacks CORS headers), retries through the configured CORS
/// proxy. Returns the successful response or rethrows the last error.
Future<http.Response> _fetchViaCorsProxy(Uri uri) async {
try {
final response = await http.get(uri);
if (response.statusCode == 200) return response;
// Non-200 (e.g. 404): fall through to the proxy only for CORS errors.
if (!kIsWeb) return response;
} catch (e) {
if (!kIsWeb) rethrow;
Logs().w('Direct download failed, trying CORS proxy', e);
}
final proxy = AppSettings.miniAppCorsProxy.value;
if (kIsWeb && proxy.isNotEmpty) {
final separator = proxy.contains('?') ? '&' : '?';
final proxied = await http.get(Uri.parse('$proxy$separator$uri'));
if (proxied.statusCode == 200) return proxied;
throw Exception('${proxied.statusCode} ${proxied.reasonPhrase}');
}
throw Exception(
'The server does not allow cross-origin requests (CORS). '
'Import the file manually or set a CORS proxy in the settings.',
);
}
String _decodeBytes(List<int> bytes) {
for (final encoding in const [utf8, latin1]) {
try {
return encoding.decode(bytes);
} catch (_) {}
}
return latin1.decode(bytes, allowInvalid: true);
}
/// Reads the mini app manifest from the meta tags of [html], validates it
/// and installs the app. The manifest `id` is used as the account data key.
///
/// Throws a [FormatException] when the document lacks the required meta
/// tags, or an [Exception] when the id is already taken.
Future<void> _importHtml({required String html}) async {
final meta = parseMiniAppMeta(html);
if (availableMiniApps.any((app) => app.id == meta.id)) {
throw Exception(
'The mini app id "${meta.id}" is reserved and cannot be reused',
);
}
if (client.isMiniAppInstalled(meta.id)) {
throw Exception('A mini app with id "${meta.id}" is already installed');
}
await client.importMiniApp(meta: meta, html: html);
}
@override
Widget build(BuildContext context) => AppsView(this);
}