Skip to content

Commit

Permalink
replace data service with github service
Browse files Browse the repository at this point in the history
  • Loading branch information
codenameakshay committed Nov 14, 2021
1 parent f9412a1 commit 8d2cbc2
Show file tree
Hide file tree
Showing 13 changed files with 735 additions and 46 deletions.
17 changes: 17 additions & 0 deletions lib/model/commit_user.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import 'package:json_annotation/json_annotation.dart';

part 'commit_user.g.dart';

/// Model class for a committer of a commit.
@JsonSerializable()
class CommitUser {
CommitUser(this.name, this.email);

final String? name;
final String? email;

factory CommitUser.fromJson(Map<String, dynamic> input) =>
_$CommitUserFromJson(input);

Map<String, dynamic> toJson() => _$CommitUserToJson(this);
}
18 changes: 18 additions & 0 deletions lib/model/commit_user.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions lib/model/create_file.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import 'package:json_annotation/json_annotation.dart';
import 'package:odin/model/commit_user.dart';

part 'create_file.g.dart';

@JsonSerializable()
class CreateFile {
CreateFile(
{this.path, this.content, this.message, this.branch, this.committer});

String? path;
String? message;
String? content;
String? branch;
CommitUser? committer;

factory CreateFile.fromJson(Map<String, dynamic> json) =>
_$CreateFileFromJson(json);

Map<String, dynamic> toJson() => _$CreateFileToJson(this);
}
26 changes: 26 additions & 0 deletions lib/model/create_file.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

92 changes: 92 additions & 0 deletions lib/model/github_error.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/// Error Generated by [GitHub]
class GitHubError implements Exception {
final String? message;
final String? apiUrl;
final Object? source;

const GitHubError(this.message, {this.apiUrl, this.source});

@override
String toString() => 'GitHub Error: $message';
}

class NotReady extends GitHubError {
const NotReady(String path)
: super(
'Not ready. Try again later',
apiUrl: path,
);
}

/// GitHub Entity was not found
class NotFound extends GitHubError {
const NotFound(
String msg,
) : super(msg);
}

class BadRequest extends GitHubError {
const BadRequest([String? msg = 'Not Found']) : super(msg);
}

/// GitHub Repository was not found
class RepositoryNotFound extends NotFound {
const RepositoryNotFound(String repo) : super('Repository Not Found: $repo');
}

/// Release not found
class ReleaseNotFound extends NotFound {
const ReleaseNotFound.fromTagName(String? tagName)
: super('Release for tagName $tagName Not Found.');
}

/// GitHub User was not found
class UserNotFound extends NotFound {
const UserNotFound(String user) : super('User Not Found: $user');
}

/// GitHub Organization was not found
class OrganizationNotFound extends NotFound {
const OrganizationNotFound(String? organization)
: super('Organization Not Found: $organization');
}

/// GitHub Team was not found
class TeamNotFound extends NotFound {
const TeamNotFound(int id) : super('Team Not Found: $id');
}

/// Access was forbidden to a resource
class AccessForbidden extends GitHubError {
const AccessForbidden() : super('Access Forbidden');
}

/// Client hit the rate limit.
class RateLimitHit extends GitHubError {
const RateLimitHit() : super('Rate Limit Hit');
}

/// A GitHub Server Error
class ServerError extends GitHubError {
ServerError(int statusCode, String? message)
: super('${message ?? 'Server Error'} ($statusCode)');
}

/// An Unknown Error
class UnknownError extends GitHubError {
const UnknownError([String? message]) : super(message ?? 'Unknown Error');
}

/// GitHub Client was not authenticated
class NotAuthenticated extends GitHubError {
const NotAuthenticated() : super('Client not Authenticated');
}

class InvalidJSON extends BadRequest {
const InvalidJSON([String? message = 'Invalid JSON']) : super(message);
}

class ValidationFailed extends GitHubError {
const ValidationFailed([String message = 'Validation Failed'])
: super(message);
}
66 changes: 66 additions & 0 deletions lib/model/github_json.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import 'dart:convert';

/// Creates a Model Object from the JSON [input]
typedef JSONConverter<S, T> = T Function(S input);

final RegExp githubDateRemoveRegExp = RegExp(r'\.\d*');
String? dateToGitHubIso8601(DateTime? date) {
if (date == null) {
return null;
}
// Regex removes the milliseconds.
return date.toUtc().toIso8601String().replaceAll(githubDateRemoveRegExp, '');
}

/// Internal class for Json encoding
/// that should be used instead of `dart:convert`.
///
/// It contains methods that ensures that converted Json
/// will work with the GitHub API.
class GitHubJson {
const GitHubJson._();

/// Called only if an object is of a non primitive type.
///
/// If [object] is a [DateTime], it converts it to a String whose format is compatible with the API.
/// Else, it uses the default behavior of [JsonEncoder] which is to call `toJson` method onto [object].
///
/// If [object] is not a [DateTime] and don't have a `toJson` method, an exception will be thrown
/// but handled by [JsonEncoder].
/// Do not catch it.
static dynamic _toEncodable(dynamic object) {
if (object is DateTime) {
return dateToGitHubIso8601(object);
}
// `toJson` could return a [Map] or a [List],
// so we have to delete null values in them.
return _checkObject(object.toJson());
}

/// Encodes [object] to a Json String compatible with the GitHub API.
/// It should be used instead of `jsonEncode`.
///
/// Equivalent to `jsonEncode` except that
/// it converts [DateTime] to a proper String for the GitHub API,
/// and it also deletes keys associated with null values in maps before converting them.
///
/// The obtained String can be decoded using `jsonDecode`.
static String encode(Object object, {String? indent}) {
final encoder = JsonEncoder.withIndent(indent, _toEncodable);
return encoder.convert(_checkObject(object));
}

/// Deletes keys associated with null values
/// in every map contained in [object].
static dynamic _checkObject(dynamic object) {
if (object is Map) {
return Map.fromEntries(object.entries
.where((e) => e.value != null)
.map((e) => MapEntry(e.key, _checkObject(e.value))));
}
if (object is List) {
return object.map(_checkObject).toList();
}
return object;
}
}
8 changes: 5 additions & 3 deletions lib/pages/home_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import 'package:odin/painters/odin_logo_painter.dart';
import 'package:odin/painters/ripple_painter.dart';
import 'package:odin/services/data_service.dart';
import 'package:odin/services/file_picker_service.dart';
import 'package:odin/services/github_service.dart';
import 'package:odin/services/locator.dart';
import 'package:odin/services/zip_service.dart';
import 'package:odin/widgets/window_top_bar.dart';
Expand All @@ -30,7 +31,8 @@ class _HomePageState extends State<HomePage>
bool _dragging = false;
bool _loading = false;
String? _fileLink;
final _ds = locator<DataService>();
// final _ds = locator<DataService>();
final _gs = locator<GithubService>();
final _zs = locator<ZipService>();
final _fps = locator<FilepickerService>();
@override
Expand Down Expand Up @@ -96,9 +98,9 @@ class _HomePageState extends State<HomePage>
detail.urls.map((e) => File(e.toFilePath())).toList();
final zippedFile =
await _zs.zipFile(fileToZips: fileToZips);
_fileLink = await _ds.uploadFileAnonymous(zippedFile);
_fileLink = await _gs.uploadFileAnonymous(zippedFile);
} else {
_fileLink = await _ds.uploadFileAnonymous(
_fileLink = await _gs.uploadFileAnonymous(
File(detail.urls.first.toFilePath()));
}
}
Expand Down
64 changes: 32 additions & 32 deletions lib/services/data_service.dart
Original file line number Diff line number Diff line change
@@ -1,35 +1,35 @@
import 'dart:convert';
import 'dart:io';
// import 'dart:convert';
// import 'dart:io';

import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:github/github.dart';
import 'package:intl/intl.dart';
import 'package:odin/services/locator.dart';
import 'package:odin/services/random_service.dart';
import 'package:odin/services/shortner_service.dart';
import 'package:path/path.dart' as path;
// import 'package:flutter_dotenv/flutter_dotenv.dart';
// import 'package:github/github.dart';
// import 'package:intl/intl.dart';
// import 'package:odin/services/locator.dart';
// import 'package:odin/services/random_service.dart';
// import 'package:odin/services/shortner_service.dart';
// import 'package:path/path.dart' as path;

class DataService {
final ShortnerService _shortnerService = locator<ShortnerService>();
final RandomService _randomService = locator<RandomService>();
final _env = dotenv.env;
final _gh =
GitHub(auth: Authentication.withToken(dotenv.env['GITHUB_TOKEN']));
// class DataService {
// final ShortnerService _shortnerService = locator<ShortnerService>();
// final RandomService _randomService = locator<RandomService>();
// final _env = dotenv.env;
// final _gh =
// GitHub(auth: Authentication.withToken(dotenv.env['GITHUB_TOKEN']));

Future<String> uploadFileAnonymous(File file) async {
final uploadTime = DateFormat('dd-MM-yyyy hh:mm:ss').format(DateTime.now());
final _ghFile = await _gh.repositories.createFile(
RepositorySlug(
_env['GITHUB_USERNAME'] ?? '', _env['GITHUB_REPO_NAME'] ?? ''),
CreateFile(
content: base64Encode(file.readAsBytesSync()),
message: "☄️ -> '${path.basename(file.path)}' | $uploadTime",
path:
"${_randomService.getRandomString(15)}/${path.basename(file.path)}",
),
);
final _downloadLink = await _shortnerService.shortUrl(
url: _ghFile.content?.downloadUrl ?? '');
return _downloadLink ?? '';
}
}
// Future<String> uploadFileAnonymous(File file) async {
// final uploadTime = DateFormat('dd-MM-yyyy hh:mm:ss').format(DateTime.now());
// final _ghFile = await _gh.repositories.createFile(
// RepositorySlug(
// _env['GITHUB_USERNAME'] ?? '', _env['GITHUB_REPO_NAME'] ?? ''),
// CreateFile(
// content: base64Encode(file.readAsBytesSync()),
// message: "☄️ -> '${path.basename(file.path)}' | $uploadTime",
// path:
// "${_randomService.getRandomString(15)}/${path.basename(file.path)}",
// ),
// );
// final _downloadLink = await _shortnerService.shortUrl(
// url: _ghFile.content?.downloadUrl ?? '');
// return _downloadLink ?? '';
// }
// }
8 changes: 5 additions & 3 deletions lib/services/file_picker_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:odin/services/data_service.dart';
import 'package:odin/services/github_service.dart';
import 'package:odin/services/locator.dart';
import 'package:odin/services/zip_service.dart';

class FilepickerService {
final _dataService = locator<DataService>();
// final _dataService = locator<DataService>();
final _githubService = locator<GithubService>();
final _zipService = locator<ZipService>();

Future<String?> getFiles() async {
Expand All @@ -18,9 +20,9 @@ class FilepickerService {
final int length = files.length;
if (length > 1) {
final zippedFile = await _zipService.zipFile(fileToZips: files);
_path = await _dataService.uploadFileAnonymous(zippedFile);
_path = await _githubService.uploadFileAnonymous(zippedFile);
} else {
_path = await _dataService.uploadFileAnonymous(files.first);
_path = await _githubService.uploadFileAnonymous(files.first);
}
} else {
// User canceled the picker
Expand Down
Loading

0 comments on commit 8d2cbc2

Please sign in to comment.