Skip to content

Commit

Permalink
[ Edit ] major new edits and hange, exposing a flow for beta testers …
Browse files Browse the repository at this point in the history
…to use langsync directly
  • Loading branch information
anasfik committed Sep 28, 2023
1 parent 40cbd1c commit 9aa3305
Show file tree
Hide file tree
Showing 18 changed files with 178 additions and 41 deletions.
Empty file removed .langsync/config.hive
Empty file.
Empty file removed .langsync/config.lock
Empty file.
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +0,0 @@
// TODO: add confirmation to logout command.
16 changes: 4 additions & 12 deletions bin/langsync.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,6 @@ import 'package:langsync/src/etc/utils.dart';
Future<void> main(List<String> args) async {
final configDir = utils.localeDataDir();
final langSyncDir = await Directory('${configDir.path}/langsync').create();
final a = utils.isValidApiKeyFormatted(
'1939cf5177f5ae3805c24cc56c03a8186969c8e15a26bcbf1ab3caf96daacabb',
);

Hive.init(langSyncDir.path);

Expand All @@ -17,13 +14,8 @@ Future<void> main(List<String> args) async {
await _flushThenExit(await LangsyncCommandRunner().run(args));
}

/// Flushes the stdout and stderr streams, then exits the program with the given
/// status code.
///
/// This returns a Future that will never complete, since the program will have
/// exited already. This is useful to prevent Future chains from proceeding
/// after you've decided to exit.
Future<void> _flushThenExit(int status) {
return Future.wait<void>([stdout.close(), stderr.close()])
.then<void>((_) => exit(status));
Future<void> _flushThenExit(int status) async {
await Future.wait<void>([stdout.close(), stderr.close()]);

exit(status);
}
Binary file modified bin/langsync.exe
Binary file not shown.
7 changes: 0 additions & 7 deletions langsync.yaml

This file was deleted.

10 changes: 5 additions & 5 deletions lib/src/command_runner.dart
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ class LangsyncCommandRunner extends CompletionCommandRunner<int> {
addCommand(AccountCommand(logger: _logger));
addCommand(ConfigCommand(logger: _logger));
addCommand(SupportedLangsCommand(logger: _logger));
addCommand(UpdateCommand(logger: _logger, pubUpdater: _pubUpdater));
// addCommand(UpdateCommand(logger: _logger, pubUpdater: _pubUpdater));
addCommand(StartCommand(logger: _logger));
}

Expand Down Expand Up @@ -124,10 +124,10 @@ class LangsyncCommandRunner extends CompletionCommandRunner<int> {
exitCode = await super.runCommand(topLevelResults);
}

// Check for updates
if (topLevelResults.command?.name != UpdateCommand.commandName) {
await _checkForUpdates();
}
// // Check for updates
// if (topLevelResults.command?.name != UpdateCommand.commandName) {
// await _checkForUpdates();
// }

return exitCode;
}
Expand Down
7 changes: 2 additions & 5 deletions lib/src/commands/account_command/account_command.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import 'dart:async';

import 'package:args/command_runner.dart';
import 'package:langsync/src/commands/account_command/sub_commands/api_key_command.dart';
import 'package:langsync/src/commands/account_command/sub_commands/auth_command.dart';
import 'package:langsync/src/commands/account_command/sub_commands/info_command.dart';
import 'package:langsync/src/commands/account_command/sub_commands/logout_command.dart';
Expand All @@ -13,6 +14,7 @@ class AccountCommand extends Command<int> {
addSubcommand(AuthCommand(logger: _logger));
addSubcommand(InfoCommand(logger: _logger));
addSubcommand(LogoutCommand(logger: _logger));
addSubcommand(ApiKeyCommand(logger: _logger));
}

@override
Expand All @@ -22,9 +24,4 @@ class AccountCommand extends Command<int> {
String get name => 'account';

final Logger _logger;

@override
FutureOr<int>? run() {
return super.run();
}
}
71 changes: 71 additions & 0 deletions lib/src/commands/account_command/sub_commands/api_key_command.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import 'dart:async';

import 'package:args/command_runner.dart';
import 'package:langsync/src/etc/extensions.dart';
import 'package:langsync/src/etc/networking/client.dart';
import 'package:mason_logger/mason_logger.dart';

class ApiKeyCommand extends Command<int> {
ApiKeyCommand({
required this.logger,
});

final Logger logger;

@override
String get description => 'Create your unique API key';

@override
String get name => 'apiKey';

@override
FutureOr<int>? run() async {
final userSure = logger.confirm(
"You're about to create a brand new unique API key, do you want to continue?");
if (!userSure) {
logger.info('Aborted!');
return 0;
}

logger.info('\n');

final userName = logger.prompt(
'Please enter your desired username (will be used to identify you): ');

if (userName.isEmpty) {
logger.err("Username can't be empty!");
return 1;
}

final progress = logger.progress('Creating your API key...');

try {
final apiKeyDoc = await NetClient.instance.createApiKey(userName);

progress.complete('API key created successfully!');
logger.info('\n');

logger
// ..info('Your username: ${apiKeyDoc.username}')
..success('Your API key: ${apiKeyDoc.apiKey}')
..info('\n')
..warn(
"Please make sure to save your API key somewhere safe, as you won't be able to retrieve it again!",
)
..info('\n')
..info(
"run 'langsync account auth' to configure LangSync with that API key to start using it.",
);

return ExitCode.success.code;
} catch (e) {
logger.customErr(
progress: progress,
update: 'Failed to create API key!',
error: e,
);

return ExitCode.software.code;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,9 @@ class InfoCommand extends Command<int> {
}

return ExitCode.success.code;
} catch (e) {
} catch (e, s) {
print(s);

logger.customErr(
error: e,
progress: fetchingProgress,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import 'package:langsync/src/etc/extensions.dart';
import 'package:langsync/src/etc/networking/client.dart';
import 'package:mason_logger/mason_logger.dart';

// TODO: openai offers 3 requests/min.

class SupportedLangsCommand extends Command<int> {
SupportedLangsCommand({
required this.logger,
Expand Down
6 changes: 3 additions & 3 deletions lib/src/etc/controllers/yaml.dart
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,6 @@ abstract class YamlController {
static bool validateConfigFields(Map parsedYaml) {
final langsyncConfig = parsedYaml['langsync'];

// TODO: validate source file and output dir.

if (langsyncConfig == null) {
throw Exception('langsync.yaml file is missing a `langsync` key.');
} else {
Expand All @@ -90,7 +88,9 @@ abstract class YamlController {
throw Exception(
'langsync.yaml file is missing a `source` key under `langsync`.',
);
} else if (outputDir == null) {
}

if (outputDir == null) {
throw Exception(
'langsync.yaml file is missing a `output` key under `langsync`.',
);
Expand Down
38 changes: 38 additions & 0 deletions lib/src/etc/models/Localization_doc.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import 'package:equatable/equatable.dart';

class LocalizationDoc extends Equatable {
const LocalizationDoc({
required this.createdAt,
required this.partitionId,
required this.jsonPartsLength,
this.outputLangs,
});

final DateTime createdAt;
final String partitionId;
final int jsonPartsLength;
final List<String>? outputLangs;

@override
List<Object?> get props => [
createdAt,
partitionId,
jsonPartsLength,
outputLangs,
];

factory LocalizationDoc.fromJson(Map<String, dynamic> json) {
return LocalizationDoc(
createdAt: DateTime.parse(json['createdAt'] as String),
partitionId: json['partitionId'] as String,
jsonPartsLength: json['jsonPartsLength'] is int
? json['jsonPartsLength'] as int
: int.parse(json['jsonPartsLength'] as String),
outputLangs: json['outputLangs'] != null
? (json['outputLangs'] as List<dynamic>)
.map((dynamic e) => e as String)
.toList()
: null,
);
}
}
21 changes: 21 additions & 0 deletions lib/src/etc/models/api_key_res.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import 'package:equatable/equatable.dart';

class APIKeyResponse extends Equatable {
const APIKeyResponse({
required this.username,
required this.apiKey,
});

factory APIKeyResponse.fromJson(Map<String, dynamic> json) {
return APIKeyResponse(
username: json['username'] as String,
apiKey: json['apiKey'] as String,
);
}

final String username;
final String apiKey;

@override
List<Object?> get props => [username, apiKey];
}
22 changes: 20 additions & 2 deletions lib/src/etc/models/user_info.dart
Original file line number Diff line number Diff line change
@@ -1,41 +1,59 @@
import 'package:equatable/equatable.dart';
import 'package:langsync/src/etc/extensions.dart';
import 'package:langsync/src/etc/models/Localization_doc.dart';

class UserInfo extends Equatable {
const UserInfo({
required this.userId,
required this.createdAt,
required this.apiKeysLength,
required this.localizationDocs,
});

factory UserInfo.fromJson(Map<String, dynamic> json) {
final userJson = json['user'];

print(userJson['localizationDocs'].runtimeType);

return UserInfo(
userId: userJson['userId'] as String,
createdAt: DateTime.parse(userJson['createdAt'] as String),
apiKeysLength: userJson['apiKeysLength'] is int
? userJson['apiKeysLength'] as int
: int.parse(userJson['apiKeysLength'] as String),
localizationDocs: (userJson['localizationDocs'] as List<dynamic>)
.map((dynamic e) =>
LocalizationDoc.fromJson(e as Map<String, dynamic>))
.toList(),
);
}

final String userId;
final DateTime createdAt;
final int apiKeysLength;
final List<LocalizationDoc> localizationDocs;

@override
List<Object?> get props => [
userId,
createdAt,
apiKeysLength,
localizationDocs,
];

Map<String, dynamic> toJson() {
return <String, dynamic>{
'User ID': userId,
'User Account Creation Time': createdAt.toProperHumanReadableDate(),
'available API keys': apiKeysLength,
'User Account Creation Date':
'${createdAt.toProperHumanReadableDate()} - ${createdAt.toIso8601String()}',
'Available API keys': apiKeysLength,
'Processed Localizations': localizationDocs.length,
'Most Recent Localization ID': localizationDocs.isNotEmpty
? localizationDocs.last.partitionId
: 'You have no processed localizations.',
'Most Recent Localization Date': localizationDocs.isNotEmpty
? '${localizationDocs.last.createdAt.toProperHumanReadableDate()} - ${localizationDocs.last.createdAt.toIso8601String()}'
: 'You have no processed localizations.',
};
}
}
10 changes: 9 additions & 1 deletion lib/src/etc/networking/client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import 'dart:convert';
import 'dart:io';

import 'package:http/http.dart' as http;
import 'package:langsync/src/etc/models/api_key_res.dart';
import 'package:langsync/src/etc/models/config.dart';
import 'package:langsync/src/etc/models/partition.dart';
import 'package:langsync/src/etc/models/result_locale.dart';
Expand Down Expand Up @@ -32,7 +33,6 @@ class NetClient {
'langs': lang,
}, (res) {
final map = <String, bool>{};
print(res);

final list = (res['checkResultList'] as List<dynamic>).cast<String>();

Expand Down Expand Up @@ -181,4 +181,12 @@ class NetClient {
},
);
}

Future<APIKeyResponse> createApiKey(String userName) {
return _makeRes('/create-account-with-api-key-beta', 'POST', {}, {
'username': userName,
}, (res) {
return APIKeyResponse.fromJson(res);
});
}
}
2 changes: 1 addition & 1 deletion lib/src/version.dart
Original file line number Diff line number Diff line change
@@ -1 +1 @@
const packageVersion = '0.0.3';
const packageVersion = '0.0.6';
2 changes: 1 addition & 1 deletion pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name: langsync
description: A Very Good Project created by Very Good CLI.
version: 0.0.3
version: 0.0.6
publish_to: none

environment:
Expand Down

0 comments on commit 9aa3305

Please sign in to comment.