Implement fetchJson for workplace web

This commit is contained in:
Dang Dat committed 2026-09-03 17:26:41 +07:00
1 parent 5a98d63e63
commit 255bd4eacd
15 files changed
+213 -97

No files matched your search

+1 -1
View File
@@ -75,7 +75,7 @@ class AppConfig {
static bool get isCozyIntegrationEnabled => dotenv.get('COZY_INTEGRATION', fallback: 'false') == 'true';
static String get cozyExternalBridgeVersion => dotenv.get('COZY_EXTERNAL_BRIDGE_VERSION', fallback: '0.16.1');
static String get cozyExternalBridgeVersion => dotenv.get('COZY_EXTERNAL_BRIDGE_VERSION', fallback: '1.3.0');
static bool get isForceEmailQueryEnabled =>
dotenv.get('FORCE_EMAIL_QUERY', fallback: 'false') == 'true';
+2 -2
View File
@@ -1440,8 +1440,8 @@ packages:
dependency: "direct main"
description:
path: "."
ref: master
resolved-ref: "6d75bb18cd57740dfb55a4a4d73b15ca724905b1"
ref: "fix/cozy-external-bridge-script-url"
resolved-ref: "24567b0585afdd23183f7b09506f4b3231ec5eb6"
url: "https://github.com/linagora/linagora-design-flutter.git"
source: git
version: "0.3.1"
+1 -1
View File
@@ -325,7 +325,7 @@ dependency_overrides:
linagora_design_flutter:
git:
url: https://github.com/linagora/linagora-design-flutter.git
ref: master
ref: fix/cozy-external-bridge-script-url
### Original dependency is abandoned, so we use fork
intl_generator:
@@ -0,0 +1 @@
export 'cozy_bridge_stub.dart' if (dart.library.html) 'cozy_bridge_web.dart';
@@ -0,0 +1,13 @@
/// Non-web fallback: there is no cozy external bridge outside the browser.
abstract final class CozyBridge {
static bool get isSupported => false;
static bool get isAvailable => false;
static Future<dynamic> fetchJson({
required String method,
required String path,
required Map<String, dynamic> body,
}) =>
throw UnsupportedError('Cozy bridge is only available on web');
}
@@ -0,0 +1,41 @@
// ignore_for_file: avoid_web_libraries_in_flutter
import 'dart:convert';
import 'dart:js_interop';
import 'dart:js_interop_unsafe';
// Read fresh on every access: setupBridge() replaces window._cozyBridge wholesale.
@JS('window._cozyBridge')
external JSObject? get _bridge;
@JS('JSON.stringify')
external String _stringify(JSAny? value);
extension type _CozyBridgeJs(JSObject _) implements JSObject {
external JSPromise<JSAny?> fetchJSON(JSObject options);
}
/// Proxies requests through the cozy external bridge to the container app,
/// which owns the stack session — so no token exchange is needed.
abstract final class CozyBridge {
/// Web reaches Drive only through the container app, never directly.
static bool get isSupported => true;
/// `fetchJSON` is only attached once `setupBridge` succeeds, so its presence
/// also proves we are inside the container iframe.
static bool get isAvailable => _bridge?.has('fetchJSON') ?? false;
static Future<dynamic> fetchJson({
required String method,
required String path,
required Map<String, dynamic> body,
}) async {
final bridge = _bridge;
if (bridge == null) throw StateError('Cozy bridge unavailable');
final options =
{'method': method, 'path': path, 'body': body}.jsify() as JSObject;
final result = await _CozyBridgeJs(bridge).fetchJSON(options).toDart;
// JSON round-trip instead of dartify(), which would yield Map<Object?, Object?>.
return result == null ? null : jsonDecode(_stringify(result));
}
}
@@ -1,14 +1,11 @@
import '../../domain/entity/workplace_action_config.dart';
import '../../domain/entity/workplace_intent.dart';
import '../../domain/entity/workplace_theme.dart';
import '../../domain/entity/workplace_intent_config.dart';
abstract class WorkplaceDataSource {
Future<WorkplaceIntent> createIntent({
required Uri platformUrl,
required String accessToken,
required WorkplaceActionConfig addAsLink,
WorkplaceActionConfig? addAsAttachment,
required WorkplaceTheme theme,
String? accessToken,
required WorkplaceIntentConfig config,
});
Future<String> exchangeToken(Uri platformUrl, String oidcIdToken);
}
@@ -8,10 +8,11 @@ import '../datasource/workplace_datasource.dart';
import '../model/workplace_enums.dart';
import '../model/workplace_intent_request.dart';
import '../model/workplace_intent_response.dart';
import '../bridge/cozy_bridge.dart';
import '../workplace_dio.dart';
import '../../domain/entity/workplace_action_config.dart';
import '../../domain/entity/workplace_intent.dart';
import '../../domain/entity/workplace_theme.dart';
import '../../domain/exceptions/workplace_exceptions.dart';
import '../../domain/entity/workplace_intent_config.dart';
class WorkplaceDataSourceImpl implements WorkplaceDataSource {
WorkplaceDataSourceImpl();
@@ -27,11 +28,26 @@ class WorkplaceDataSourceImpl implements WorkplaceDataSource {
@override
Future<WorkplaceIntent> createIntent({
required Uri platformUrl,
required String accessToken,
required WorkplaceActionConfig addAsLink,
WorkplaceActionConfig? addAsAttachment,
required WorkplaceTheme theme,
String? accessToken,
required WorkplaceIntentConfig config,
}) async {
final body = _buildIntentRequest(config);
// The container app already holds the stack session, so no bearer token.
if (CozyBridge.isSupported) {
if (!CozyBridge.isAvailable) throw WorkplaceBridgeUnavailableException();
final data = await CozyBridge.fetchJson(
method: 'POST',
path: '/intents',
body: body,
);
return parseIntentResponse(data);
}
if (accessToken == null) {
throw StateError('Drive access token is required');
}
final response = await WorkplaceDio.instance.post(
platformUrl.replace(
pathSegments: [
@@ -46,11 +62,7 @@ class WorkplaceDataSourceImpl implements WorkplaceDataSource {
options: Options(
headers: {'Authorization': 'Bearer $accessToken'},
),
data: _buildIntentRequest(
addAsLink: addAsLink,
addAsAttachment: addAsAttachment,
theme: theme,
),
data: body,
);
return parseIntentResponse(response.data);
}
@@ -78,11 +90,8 @@ class WorkplaceDataSourceImpl implements WorkplaceDataSource {
);
}
Map<String, dynamic> _buildIntentRequest({
required WorkplaceActionConfig addAsLink,
WorkplaceActionConfig? addAsAttachment,
required WorkplaceTheme theme,
}) => WorkplaceIntentRequest(
Map<String, dynamic> _buildIntentRequest(WorkplaceIntentConfig config) =>
WorkplaceIntentRequest(
data: WorkplaceIntentDataRequest(
type: WorkplaceDataRequestType.intents,
attributes: WorkplaceIntentAttributesRequest(
@@ -90,11 +99,11 @@ class WorkplaceDataSourceImpl implements WorkplaceDataSource {
type: WorkplaceDocType.files,
permissions: [WorkplacePermission.get],
data: WorkplaceFilePickerConfigRequest(
sharingLink: WorkplaceActionConfigRequest.fromEntity(addAsLink),
downloadLink: addAsAttachment == null
sharingLink: WorkplaceActionConfigRequest.fromEntity(config.addAsLink),
downloadLink: config.addAsAttachment == null
? null
: WorkplaceActionConfigRequest.fromEntity(addAsAttachment),
theme: WorkplaceThemeConfigRequest.fromEntity(theme),
: WorkplaceActionConfigRequest.fromEntity(config.addAsAttachment!),
theme: WorkplaceThemeConfigRequest.fromEntity(config.theme),
),
),
),
@@ -1,7 +1,6 @@
import '../datasource/workplace_datasource.dart';
import '../../domain/entity/workplace_action_config.dart';
import '../../domain/entity/workplace_intent.dart';
import '../../domain/entity/workplace_theme.dart';
import '../../domain/entity/workplace_intent_config.dart';
import '../../domain/repository/workplace_repository.dart';
class WorkplaceRepositoryImpl implements WorkplaceRepository {
@@ -12,16 +11,12 @@ class WorkplaceRepositoryImpl implements WorkplaceRepository {
@override
Future<WorkplaceIntent> createIntent({
required Uri platformUrl,
required String accessToken,
required WorkplaceActionConfig addAsLink,
WorkplaceActionConfig? addAsAttachment,
required WorkplaceTheme theme,
String? accessToken,
required WorkplaceIntentConfig config,
}) => _dataSource.createIntent(
platformUrl: platformUrl,
accessToken: accessToken,
addAsLink: addAsLink,
addAsAttachment: addAsAttachment,
theme: theme,
config: config,
);
@override
@@ -0,0 +1,23 @@
import 'package:equatable/equatable.dart';
import 'workplace_action_config.dart';
import 'workplace_theme.dart';
/// The picker shape an intent asks Drive for: which actions to offer and how
/// to render them.
class WorkplaceIntentConfig with EquatableMixin {
final WorkplaceActionConfig addAsLink;
/// Null hides the attachment button.
final WorkplaceActionConfig? addAsAttachment;
final WorkplaceTheme theme;
const WorkplaceIntentConfig({
required this.addAsLink,
this.addAsAttachment,
required this.theme,
});
@override
List<Object?> get props => [addAsLink, addAsAttachment, theme];
}
@@ -2,6 +2,9 @@ class WorkplaceCreateIntentException implements Exception {}
class WorkplaceExchangeTokenException implements Exception {}
/// Web reaches Drive only through the container app's bridge.
class WorkplaceBridgeUnavailableException implements Exception {}
class DriveIntentErrorException implements Exception {}
class DriveIntentPageLoadException implements Exception {
@@ -1,14 +1,11 @@
import '../entity/workplace_action_config.dart';
import '../entity/workplace_intent.dart';
import '../entity/workplace_theme.dart';
import '../entity/workplace_intent_config.dart';
abstract class WorkplaceRepository {
Future<WorkplaceIntent> createIntent({
required Uri platformUrl,
required String accessToken,
required WorkplaceActionConfig addAsLink,
WorkplaceActionConfig? addAsAttachment,
required WorkplaceTheme theme,
String? accessToken,
required WorkplaceIntentConfig config,
});
Future<String> exchangeToken(Uri platformUrl, String oidcIdToken);
}
@@ -1,8 +1,7 @@
import 'package:core/presentation/state/failure.dart';
import 'package:core/presentation/state/success.dart';
import 'package:dartz/dartz.dart';
import '../entity/workplace_action_config.dart';
import '../entity/workplace_theme.dart';
import '../entity/workplace_intent_config.dart';
import '../repository/workplace_repository.dart';
import '../state/workplace_intent_state.dart';
@@ -13,19 +12,15 @@ class CreateDriveIntentInteractor {
Stream<Either<Failure, Success>> execute(
Uri platformUrl,
String accessToken, {
required WorkplaceActionConfig addAsLink,
WorkplaceActionConfig? addAsAttachment,
required WorkplaceTheme theme,
String? accessToken, {
required WorkplaceIntentConfig config,
}) async* {
try {
yield Right(CreatingWorkplaceIntent());
final intent = await _repository.createIntent(
platformUrl: platformUrl,
accessToken: accessToken,
addAsLink: addAsLink,
addAsAttachment: addAsAttachment,
theme: theme,
config: config,
);
yield Right(CreateWorkplaceIntentSuccess(intent));
} catch (e) {
@@ -4,12 +4,14 @@ import 'package:core/presentation/resources/image_paths.dart';
import 'package:core/presentation/state/failure.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:workplace/data/bridge/cozy_bridge.dart';
import 'package:workplace/data/datasource_impl/workplace_datasource_impl.dart';
import 'package:workplace/data/model/workplace_enums.dart';
import 'package:workplace/data/model/workplace_intent_request.dart';
import 'package:workplace/data/repository_impl/workplace_repository_impl.dart';
import 'package:workplace/domain/entity/workplace_action_config.dart';
import 'package:workplace/domain/entity/workplace_intent.dart';
import 'package:workplace/domain/entity/workplace_intent_config.dart';
import 'package:workplace/domain/entity/workplace_theme.dart';
import 'package:workplace/domain/exceptions/workplace_exceptions.dart';
import 'package:workplace/presentation/model/drive_pick_state.dart';
@@ -55,10 +57,15 @@ class WorkplaceComposerAttachmentExtension implements ComposerAttachmentPlugin {
Uri platformUrl, {
required WorkplaceFilePickerConfigRequest filePickerConfig,
}) async {
final oidcToken = oidcTokenGetter();
if (oidcToken == null) throw StateError('OIDC token is unavailable');
final accessToken = await _exchangeAccessToken(platformUrl, oidcToken);
if (accessToken == null) throw StateError('Drive access token exchange failed');
// Mobile has no container app, so it authenticates against Drive directly;
// on web the bridge proxies through a session that already exists.
String? accessToken;
if (!CozyBridge.isSupported) {
final oidcToken = oidcTokenGetter();
if (oidcToken == null) throw StateError('OIDC token is unavailable');
accessToken = await _exchangeAccessToken(platformUrl, oidcToken);
if (accessToken == null) throw StateError('Drive access token exchange failed');
}
return _createIntent(
platformUrl,
accessToken,
@@ -92,25 +99,27 @@ class WorkplaceComposerAttachmentExtension implements ComposerAttachmentPlugin {
Future<WorkplaceIntent> _createIntent(
Uri platformUrl,
String accessToken, {
String? accessToken, {
required WorkplaceFilePickerConfigRequest filePickerConfig,
}) async {
WorkplaceIntent? intent;
await for (final either in _createIntentInteractor.execute(
platformUrl,
accessToken,
addAsLink: WorkplaceActionConfig(label: filePickerConfig.sharingLink.label),
addAsAttachment: filePickerConfig.downloadLink == null
? null
: WorkplaceActionConfig(
label: filePickerConfig.downloadLink!.label,
maxFileSize: filePickerConfig.downloadLink!.maxFileSize,
availableSize: filePickerConfig.downloadLink!.availableSize,
),
theme: switch (filePickerConfig.theme.type) {
WorkplaceThemeType.light => WorkplaceTheme.light,
WorkplaceThemeType.dark => WorkplaceTheme.dark,
},
config: WorkplaceIntentConfig(
addAsLink: WorkplaceActionConfig(label: filePickerConfig.sharingLink.label),
addAsAttachment: filePickerConfig.downloadLink == null
? null
: WorkplaceActionConfig(
label: filePickerConfig.downloadLink!.label,
maxFileSize: filePickerConfig.downloadLink!.maxFileSize,
availableSize: filePickerConfig.downloadLink!.availableSize,
),
theme: switch (filePickerConfig.theme.type) {
WorkplaceThemeType.light => WorkplaceTheme.light,
WorkplaceThemeType.dark => WorkplaceTheme.dark,
},
),
)) {
either.fold(
(failure) {
@@ -7,6 +7,7 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:workplace/data/datasource_impl/workplace_datasource_impl.dart';
import 'package:workplace/data/workplace_dio.dart';
import 'package:workplace/domain/entity/workplace_action_config.dart';
import 'package:workplace/domain/entity/workplace_intent_config.dart';
import 'package:workplace/domain/entity/workplace_theme.dart';
/// Captures the last request and returns a fixed JSON response.
@@ -247,9 +248,11 @@ void main() {
final result = await datasource.createIntent(
platformUrl: Uri.parse('https://platform.example.com'),
accessToken: 'test-token',
addAsLink: const WorkplaceActionConfig(label: 'https://link.url'),
addAsAttachment: const WorkplaceActionConfig(label: 'https://attach.url'),
theme: WorkplaceTheme.light,
config: const WorkplaceIntentConfig(
addAsLink: WorkplaceActionConfig(label: 'https://link.url'),
addAsAttachment: WorkplaceActionConfig(label: 'https://attach.url'),
theme: WorkplaceTheme.light,
),
);
expect(result.intentId, equals('intent-abc'));
@@ -263,9 +266,11 @@ void main() {
await datasource.createIntent(
platformUrl: Uri.parse('https://platform.example.com/api/'),
accessToken: 'test-token',
addAsLink: const WorkplaceActionConfig(label: 'https://link.url'),
addAsAttachment: const WorkplaceActionConfig(label: 'https://attach.url'),
theme: WorkplaceTheme.light,
config: const WorkplaceIntentConfig(
addAsLink: WorkplaceActionConfig(label: 'https://link.url'),
addAsAttachment: WorkplaceActionConfig(label: 'https://attach.url'),
theme: WorkplaceTheme.light,
),
);
expect(
@@ -281,9 +286,11 @@ void main() {
await datasource.createIntent(
platformUrl: Uri.parse('https://platform.example.com'),
accessToken: 'test-token',
addAsLink: const WorkplaceActionConfig(label: 'https://link.url'),
addAsAttachment: const WorkplaceActionConfig(label: 'https://attach.url'),
theme: WorkplaceTheme.light,
config: const WorkplaceIntentConfig(
addAsLink: WorkplaceActionConfig(label: 'https://link.url'),
addAsAttachment: WorkplaceActionConfig(label: 'https://attach.url'),
theme: WorkplaceTheme.light,
),
);
expect(
@@ -299,9 +306,11 @@ void main() {
await datasource.createIntent(
platformUrl: Uri.parse('https://platform.example.com'),
accessToken: 'my-secret-token',
addAsLink: const WorkplaceActionConfig(label: 'https://link.url'),
addAsAttachment: const WorkplaceActionConfig(label: 'https://attach.url'),
theme: WorkplaceTheme.light,
config: const WorkplaceIntentConfig(
addAsLink: WorkplaceActionConfig(label: 'https://link.url'),
addAsAttachment: WorkplaceActionConfig(label: 'https://attach.url'),
theme: WorkplaceTheme.light,
),
);
expect(
@@ -317,9 +326,11 @@ void main() {
await datasource.createIntent(
platformUrl: Uri.parse('https://platform.example.com'),
accessToken: 'test-token',
addAsLink: const WorkplaceActionConfig(label: 'https://link.url'),
addAsAttachment: const WorkplaceActionConfig(label: 'https://attach.url'),
theme: WorkplaceTheme.dark,
config: const WorkplaceIntentConfig(
addAsLink: WorkplaceActionConfig(label: 'https://link.url'),
addAsAttachment: WorkplaceActionConfig(label: 'https://attach.url'),
theme: WorkplaceTheme.dark,
),
);
// Normalize through jsonEncode so nested Dart objects are fully serialized
@@ -348,13 +359,15 @@ void main() {
await datasource.createIntent(
platformUrl: Uri.parse('https://platform.example.com'),
accessToken: 'test-token',
addAsLink: const WorkplaceActionConfig(label: 'https://link.url'),
addAsAttachment: const WorkplaceActionConfig(
label: 'https://attach.url',
maxFileSize: 5000,
availableSize: 4500,
config: const WorkplaceIntentConfig(
addAsLink: WorkplaceActionConfig(label: 'https://link.url'),
addAsAttachment: WorkplaceActionConfig(
label: 'https://attach.url',
maxFileSize: 5000,
availableSize: 4500,
),
theme: WorkplaceTheme.light,
),
theme: WorkplaceTheme.light,
);
final body = jsonDecode(jsonEncode(adapter.capturedOptions!.data)) as Map<String, dynamic>;
@@ -374,8 +387,10 @@ void main() {
await datasource.createIntent(
platformUrl: Uri.parse('https://platform.example.com'),
accessToken: 'test-token',
addAsLink: const WorkplaceActionConfig(label: 'https://link.url'),
theme: WorkplaceTheme.light,
config: const WorkplaceIntentConfig(
addAsLink: WorkplaceActionConfig(label: 'https://link.url'),
theme: WorkplaceTheme.light,
),
);
final body = jsonDecode(jsonEncode(adapter.capturedOptions!.data)) as Map<String, dynamic>;
@@ -386,6 +401,22 @@ void main() {
expect(config['downloadLink'], isNull);
});
test('Should reject a null access token when the cozy bridge is unavailable', () async {
WorkplaceDio.setInstance(Dio()..httpClientAdapter = _MockAdapter(intentResponse));
expect(
() => datasource.createIntent(
platformUrl: Uri.parse('https://platform.example.com'),
accessToken: null,
config: const WorkplaceIntentConfig(
addAsLink: WorkplaceActionConfig(label: 'https://link.url'),
theme: WorkplaceTheme.light,
),
),
throwsA(isA<StateError>()),
);
});
test('Should propagate DioException on network error', () async {
WorkplaceDio.setInstance(Dio()..httpClientAdapter = _ErrorAdapter());
@@ -393,9 +424,11 @@ void main() {
() => datasource.createIntent(
platformUrl: Uri.parse('https://platform.example.com'),
accessToken: 'test-token',
addAsLink: const WorkplaceActionConfig(label: 'https://link.url'),
addAsAttachment: const WorkplaceActionConfig(label: 'https://attach.url'),
theme: WorkplaceTheme.light,
config: const WorkplaceIntentConfig(
addAsLink: WorkplaceActionConfig(label: 'https://link.url'),
addAsAttachment: WorkplaceActionConfig(label: 'https://attach.url'),
theme: WorkplaceTheme.light,
),
),
throwsA(isA<DioException>()),
);