Skip to content

add network loader #35

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lib/localize_and_translate.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export 'package:localize_and_translate/src/assets/asset_loader_network.dart';
export 'package:localize_and_translate/src/assets/asset_loader_root_bundle_json.dart';
export 'package:localize_and_translate/src/constants/enums.dart';
export 'package:localize_and_translate/src/core/localize_and_translate.dart';
Expand Down
67 changes: 67 additions & 0 deletions lib/src/assets/asset_loader_network.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:localize_and_translate/src/assets/asset_loader_base.dart';
import 'package:localize_and_translate/src/constants/db_keys.dart';
import 'package:localize_and_translate/src/db/usecases.dart';
import 'package:localize_and_translate/src/models/m_localization.dart';

/// [AssetLoaderNetwork] is the asset loader for root bundle.
/// It loads the assets from the root bundle.
class AssetLoaderNetwork implements AssetLoaderBase {
/// [AssetLoaderNetwork] constructor
/// [endPoint] is the path of the json endPoint
const AssetLoaderNetwork(this.endPoint);

/// [endPoint] is the path of the json endPoint
final String endPoint;

@override
Future<Map<String, dynamic>> load() async {
final Dio dio = Dio(
BaseOptions(
connectTimeout: const Duration(seconds: 30),
receiveTimeout: const Duration(seconds: 30),
sendTimeout: const Duration(seconds: 30),
headers: const <String, dynamic>{
'Accept': 'application/json',
'Content-Type': 'application/json',
},
receiveDataWhenStatusError: true,
),
);

final List<Locale> data = DBUseCases.localesFromDBString(DBUseCases.read(DBKeys.locales));
final Map<String, dynamic> result = <String, dynamic>{};

for (final Locale locale in data) {
final Response<dynamic> response = await dio.get(
endPoint,
queryParameters: <String, dynamic>{
'lang': locale.languageCode,
},
);

MLocalization mLocalization = MLocalization();

if (response.data is Map<String, dynamic>) {
mLocalization = MLocalization.fromJson(response.data as Map<String, dynamic>);
}

final Map<String, dynamic> newValues = <String, dynamic>{};
final Map<String, String> flatten = mLocalization.flattenLocalization();

for (final String key in flatten.keys) {
newValues[DBKeys.buildPrefix(
key: key,
languageCode: locale.languageCode,
countryCode: locale.countryCode,
)] = flatten[key];
}

result.addAll(newValues);
}

debugPrint('--LocalizeAndTranslate-- Translated Strings: ${result.length}');
return result;
}
}
7 changes: 2 additions & 5 deletions lib/src/assets/asset_loader_root_bundle_json.dart
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ class AssetLoaderRootBundleJson implements AssetLoaderBase {

@override
Future<Map<String, dynamic>> load() async {
final AssetManifest assetManifest =
await AssetManifest.loadFromAssetBundle(rootBundle);
final AssetManifest assetManifest = await AssetManifest.loadFromAssetBundle(rootBundle);
final Iterable<String> paths = assetManifest.listAssets().where(
(String element) => element.contains(directory),
);
Expand All @@ -33,9 +32,7 @@ class AssetLoaderRootBundleJson implements AssetLoaderBase {

if (fileNameNoExtension.contains('-')) {
languageCode = fileNameNoExtension.split('-').first;
countryCode = fileNameNoExtension.split('-').length > 2
? fileNameNoExtension.split('-').elementAt(1)
: null;
countryCode = fileNameNoExtension.split('-').length > 2 ? fileNameNoExtension.split('-').elementAt(1) : null;
} else {
languageCode = fileNameNoExtension;
}
Expand Down
3 changes: 3 additions & 0 deletions lib/src/constants/db_keys.dart
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ class DBKeys {
required String languageCode,
required String? countryCode,
}) {
if (countryCode == 'null') {
countryCode = '';
}
return 'tr__${languageCode}_${countryCode ?? ''}_$key';
}
}
83 changes: 83 additions & 0 deletions lib/src/models/m_localization.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/// [MLocalization] is a model class that represents the localization data.
class MLocalization {
/// [MLocalization] constructor
MLocalization({this.screens});

/// [fromJson] is a factory method that creates a [MLocalization] instance from a JSON object.
factory MLocalization.fromJson(Map<String, dynamic> json) {
final Map<String, MLocalizationNode> screens = <String, MLocalizationNode>{};
json.forEach((String key, dynamic value) {
if (key != 'version') {
screens[key] = MLocalizationNode.fromJson(value as Map<String, dynamic>);
}
});
return MLocalization(
screens: screens,
);
}

/// [flattenLocalization] is a method that flattens the localization data.
Map<String, String> flattenLocalization() {
final Map<String, String> flatMap = <String, String>{};

void flatten(Map<String, MLocalizationNode>? nodes, String parentKey) {
if (nodes == null) {
return;
}

nodes.forEach((String key, MLocalizationNode node) {
final String currentKey = parentKey.isEmpty ? key : '$parentKey.$key';

if (node.title != null) {
// If it's a leaf, add it to the flat map
flatMap[currentKey] = node.title!;
} else if (node.children != null) {
// If it has children, continue flattening
flatten(node.children, currentKey);
}
});
}

flatten(screens, '');
return flatMap;
}

/// [screens] is a map of screen names to their respective [MLocalizationNode].
final Map<String, MLocalizationNode>? screens;
}

/// [MLocalizationNode] is a model class that represents a node in the localization data.
class MLocalizationNode {
/// [MLocalizationNode] constructor
MLocalizationNode({this.title, this.children});

/// [fromJson] is a factory method that creates a [MLocalizationNode] instance from a JSON object.
factory MLocalizationNode.fromJson(Map<String, dynamic> json) {
// Check if the current JSON object has no nested structure
final bool isLeafNode = json.values.every((dynamic value) => value is String || value is! Map);

if (isLeafNode) {
// If all values are non-map types, treat this as a leaf node
return MLocalizationNode(title: json['title'] as String?);
}

// Otherwise, recursively parse children
final Map<String, MLocalizationNode> children = <String, MLocalizationNode>{};
json.forEach((String key, dynamic value) {
if (value is Map<String, dynamic>) {
children[key] = MLocalizationNode.fromJson(value);
}
});

return MLocalizationNode(children: children);
}

/// [isLeaf] is a boolean that indicates if this node is a leaf node.
bool get isLeaf => title != null;

/// [title] is the localized string for this node.
final String? title;

/// [children] is a map of child nodes.
final Map<String, MLocalizationNode>? children;
}
1 change: 1 addition & 0 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ dependencies:
hive: ^2.2.3
hive_flutter: ^1.1.0
intl: ^0.18.1
dio: ^5.7.0

dev_dependencies:
flutter_test:
Expand Down