Skip to content
This repository has been archived by the owner on Nov 7, 2023. It is now read-only.

Commit

Permalink
refactor(appimage_updater): dispose possible things before restarting
Browse files Browse the repository at this point in the history
  • Loading branch information
zyrouge committed Oct 18, 2021
1 parent e65c746 commit 4369f76
Show file tree
Hide file tree
Showing 20 changed files with 188 additions and 5,871 deletions.
5 changes: 2 additions & 3 deletions cli/flutter-cli/build/linux/appimage/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { basename, dirname, join, relative } from "path";
import { dirname, join, relative } from "path";
import { ensureDir, readdir, readFile, rename, writeFile } from "fs-extra";
import { spawn, promisifyChildProcess } from "../../../../spawn";
import { getVersion } from "../../../../helpers/version";
import { Logger } from "../../../../logger";
import { config } from "../../../../config";

export const buildDir = join(config.base, "build/linux/x64/release/bundle");
import { buildDir } from "../";

const logger = new Logger("build:linux:appimage");

Expand Down
2 changes: 1 addition & 1 deletion cli/flutter-cli/build/linux/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { spawn, promisifyChildProcess } from "../../../spawn";
import { config } from "../../../config";
import { Logger } from "../../../logger";

export const buildDir = join(config.base, "build/windows/runner/Release");
export const buildDir = join(config.base, "build/linux/x64/release/bundle");

const logger = new Logger("build:linux");

Expand Down
2 changes: 1 addition & 1 deletion cli/flutter-cli/build/macos/dmg/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import { spawn, promisifyChildProcess } from "../../../../spawn";
import { getVersion } from "../../../../helpers/version";
import { Logger } from "../../../../logger";
import { config } from "../../../../config";
import { buildDir } from "../";

const icns = join(config.base, "build/macos/icon.icns");
export const buildDir = join(config.base, "build/macos/Build/Products/Release");

const logger = new Logger("build:macos:dmg");

Expand Down
2 changes: 1 addition & 1 deletion cli/flutter-cli/build/macos/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { spawn, promisifyChildProcess } from "../../../spawn";
import { config } from "../../../config";
import { Logger } from "../../../logger";

export const buildDir = join(config.base, "build/windows/runner/Release");
export const buildDir = join(config.base, "build/macos/Build/Products/Release");

const logger = new Logger("build:macos");

Expand Down
2 changes: 1 addition & 1 deletion cli/flutter-cli/hive-generate/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export const generate = async () => {
} catch (err: any) {
if (typeof err?.code === "number" && err.code === 78) {
console.log(" ");
logger.log(
logger.warn(
'Found conflicting outputs, retrying with "--delete-conflicting-outputs" flag'
);
console.log(" ");
Expand Down
2 changes: 1 addition & 1 deletion cli/icons/linux/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { copyFile, ensureDir } from "fs-extra";
import jimp from "jimp";
import { Logger } from "../../logger";
import { config } from "../../config";
import { buildDir } from "../../flutter-cli/build/linux/appimage";
import { buildDir } from "../../flutter-cli/build/linux";

export const path = join(
buildDir,
Expand Down
14 changes: 6 additions & 8 deletions cli/logger.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
export class Logger {
name: string;
import chalk from "chalk";

constructor(name: string) {
this.name = name;
}
export class Logger {
constructor(public readonly name: string) {}

log(text: string) {
console.log(`[${this.name}] ${text}`);
console.log(chalk.whiteBright(`[${this.name}] INFO ${text}`));
}

warn(text: string) {
console.warn(`[${this.name}] ${text}`);
console.warn(chalk.yellowBright(`[${this.name}] WARN ${text}`));
}

error(text: string) {
console.error(`[${this.name}] ${text}`);
console.error(chalk.redBright(`[${this.name}] ERR! ${text}`));
}
}
4 changes: 3 additions & 1 deletion lib/config.dart
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,10 @@ abstract class Config {
static const String storeURL =
'https://raw.githubusercontent.com/$repoAuthor/extensions-store/dist/extensions.json';

// static const String releasesURL =
// 'https://api.github.com/repos/$repoAuthor/$repoName/releases?per_page=20';
static const String releasesURL =
'https://api.github.com/repos/$repoAuthor/$repoName/releases?per_page=20';
'https://aef4-103-139-34-246.ngrok.io/versions.json';
}

abstract class MiscSettings {
Expand Down
5 changes: 2 additions & 3 deletions lib/pages/home_page/anime_section.dart
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import 'package:flutter/material.dart';

import './home_page.dart';
import '../../core/provisions/model.dart' as provisions;
import '../../core/provisions/myanimelist/home.dart' as myanimelist;
import '../../core/provisions/myanimelist/utils.dart' as myanimelist;
import '../../core/trackers/myanimelist/myanimelist.dart' as myanimelist;
import '../../plugins/database/database.dart';
import '../../plugins/helpers/stateful_holder.dart';
import '../../plugins/helpers/ui.dart';
import '../../plugins/translator/translator.dart';
import '../../plugins/state.dart';

final StatefulHolder<myanimelist.HomeResult?> _cache =
StatefulHolder<myanimelist.HomeResult?>(null);
Expand Down Expand Up @@ -86,7 +85,7 @@ class _PageState extends State<Page> with DidLoadStater {
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
_cache.hasResolved && DataStore.settings.locale! == 'en'
_cache.hasResolved && AppState.settings.current.locale == 'en'
? _cache.value!.seasonName
: Translator.t.seasonalAnimes(),
style: Theme.of(context).textTheme.headline5?.copyWith(
Expand Down
12 changes: 5 additions & 7 deletions lib/pages/manga_page/manga_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -307,8 +307,8 @@ class _PageState extends State<Page>
currentChapterIndex! - 1,
);
} else {
setChapter(null);
goToPage(Pages.home);
setChapter(null);
}
}

Expand All @@ -319,14 +319,14 @@ class _PageState extends State<Page>
currentChapterIndex! + 1,
);
} else {
setChapter(null);
goToPage(Pages.home);
setChapter(null);
}
}

void _onPop() {
setChapter(null);
goToPage(Pages.home);
setChapter(null);
}

Future<void> showLanguageDialog() async {
Expand Down Expand Up @@ -629,11 +629,9 @@ class _PageState extends State<Page>
),
onWillPop: () async {
if (info != null && controller.page?.toInt() != Pages.home.index) {
setState(() {
setChapter(null);
});

goToPage(Pages.home);
setChapter(null);

return false;
}

Expand Down
12 changes: 9 additions & 3 deletions lib/pages/splash_page/splash_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -84,13 +84,19 @@ class _PageState extends State<Page> with RouteAware, DidLoadStater {
});

try {
final bool shouldExit = await updater.install(update);
final InstallResponse resp = await updater.install(update);

if (shouldExit) {
if (resp.exit) {
status.value = Translator.t.restartingApp();
await Future<void>.delayed(const Duration(seconds: 3));

Screen.close();
await AppLifecycle.dispose();

if (resp.beforeExit != null) {
await resp.beforeExit!();
}

await Screen.close();
exit(0);
}
} catch (err, stack) {
Expand Down
20 changes: 14 additions & 6 deletions lib/plugins/app_lifecycle.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import 'dart:io';

import 'package:flutter/material.dart';
import './database/database.dart';
import './helpers/deeplink.dart';
Expand Down Expand Up @@ -93,11 +92,12 @@ abstract class AppLifecycle {
}

try {
await FunctionUtils.tryLoop(
DataStore.initialize,
max: Platform.environment['RESPWND_INST'] == 'true' ? 30 : 1,
interval: const Duration(seconds: 2),
);
// await FunctionUtils.tryLoop(
// DataStore.initialize,
// max: Platform.environment['RESPWND_INST'] == 'true' ? 30 : 1,
// interval: const Duration(seconds: 2),
// );
await DataStore.initialize();
} catch (err, trace) {
Logger.of('DataStore').error(
'"initialize" failed: $err',
Expand Down Expand Up @@ -194,4 +194,12 @@ abstract class AppLifecycle {
preready = false;
events.dispatch(AppLifecycleEvents.ready);
}

static Future<void> dispose() async {
await LocalServer.dispose();
Logger.of('LocalServer').info('Finished "dispose"');

await DataStore.dispose();
Logger.of('DataStore').info('Finished "dispose"');
}
}
4 changes: 4 additions & 0 deletions lib/plugins/database/database.dart
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,10 @@ abstract class DataStore {
Logger.of('DataStore').info('Registered "cache_schema.CacheSchema"');
}

static Future<void> dispose() async {
await Hive.close();
}

static settings_schema.SettingsSchema get settings {
final settings_schema.SettingsSchema defaultValue =
settings_schema.SettingsSchema();
Expand Down
9 changes: 4 additions & 5 deletions lib/plugins/helpers/local_server/server.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,13 @@ import 'package:shelf/shelf_io.dart' as shelf_io;
import './routes.dart';

abstract class LocalServer {
static bool disposed = false;
static HttpServer? server;

static const String protocol = 'http';
static const String host = 'localhost';
static int port = 0;

static FutureOr<Response> _handler(final Request request) {
if (disposed) {
return Response(503, body: 'Unavailable');
}

final ServerRoute? route = routes.firstWhereOrNull(
(final ServerRoute x) =>
x.method == request.method && x.route == request.url.path,
Expand All @@ -40,5 +35,9 @@ abstract class LocalServer {
port = server!.port;
}

static Future<void> dispose() async {
await server?.close(force: true);
}

static String get baseURL => '$protocol://$host:$port';
}
6 changes: 3 additions & 3 deletions lib/plugins/updater/android/apk.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ class AndroidApkUpdater with PlatformUpdater {
);

@override
Future<bool> install(final UpdateInfo update) async {
Future<InstallResponse> install(final UpdateInfo update) async {
progress.dispatch(UpdaterEvent(UpdaterEvents.starting));

final Completer<bool> future = Completer<bool>();
final Completer<InstallResponse> future = Completer<InstallResponse>();

final OtaUpdate ota = OtaUpdate();
final double startedAt = DateTime.now().millisecondsSinceEpoch / 1000;
Expand Down Expand Up @@ -57,7 +57,7 @@ class AndroidApkUpdater with PlatformUpdater {
UpdaterEvents.extracting,
),
);
future.complete(false);
future.complete(InstallResponse(exit: false));
break;

default:
Expand Down
34 changes: 14 additions & 20 deletions lib/plugins/updater/linux/appimage.dart
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class LinuxAppImageUpdater with PlatformUpdater {
);

@override
Future<bool> install(final UpdateInfo update) async {
Future<InstallResponse> install(final UpdateInfo update) async {
progress.dispatch(UpdaterEvent(UpdaterEvents.starting));

final String tmp = path.join(
Expand Down Expand Up @@ -64,7 +64,7 @@ class LinuxAppImageUpdater with PlatformUpdater {

await currentExe.create(recursive: true);

if (RegExp(r'/\d+\.\d+\.\d+/').hasMatch(path.basename(currentExe.path))) {
if (RegExp(r'v/\d+\.\d+\.\d+/').hasMatch(path.basename(currentExe.path))) {
await currentExe
.rename(path.join(path.dirname(currentExe.path), newExeName));
}
Expand All @@ -74,7 +74,7 @@ class LinuxAppImageUpdater with PlatformUpdater {

final ProcessResult chmodRes = await Process.run(
'chmod',
<String>['+777', '"${currentExe.path}"'],
<String>['755', currentExe.path],
runInShell: true,
);
if (chmodRes.exitCode != 0) {
Expand All @@ -84,24 +84,18 @@ class LinuxAppImageUpdater with PlatformUpdater {
Logger.of('LinuxAppImageUpdater')
.info('Copied and made AppImage executable at: ${currentExe.path}');

LocalServer.disposed = true;
Logger.of('LinuxAppImageUpdater').info('Disposed "LocalServer"');

await Process.start(
'bash',
<String>[
'-c',
'"${currentExe.path}"',
],
environment: <String, String>{
'RESPWND_INST': 'true',
return InstallResponse(
exit: true,
beforeExit: () async {
await Process.start(
currentExe.path,
<String>[],
runInShell: true,
mode: ProcessStartMode.detached,
);
Logger.of('LinuxAppImageUpdater')
.info('Spawned new app, waiting to close...');
},
runInShell: true,
mode: ProcessStartMode.detached,
);
Logger.of('LinuxAppImageUpdater')
.info('Spawned new app, waiting to close...');

return true;
}
}
12 changes: 11 additions & 1 deletion lib/plugins/updater/updater.dart
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,16 @@ class UpdaterEvent {
final dynamic data;
}

class InstallResponse {
InstallResponse({
required final this.exit,
final this.beforeExit,
});

final bool exit;
final Future<void> Function()? beforeExit;
}

abstract class PlatformUpdater {
final Eventer<UpdaterEvent> progress = Eventer<UpdaterEvent>();

Expand Down Expand Up @@ -97,7 +107,7 @@ abstract class PlatformUpdater {

UpdateInfo? filterUpdate(final List<UpdateInfo> updates);

Future<bool> install(final UpdateInfo update);
Future<InstallResponse> install(final UpdateInfo update);
}

typedef PlatformUpdaterValidate = bool Function();
Expand Down

0 comments on commit 4369f76

Please sign in to comment.