Skip to content

Commit

Permalink
feat: device list
Browse files Browse the repository at this point in the history
  • Loading branch information
diyews committed Nov 20, 2021
1 parent 21b97ca commit 0e77b14
Show file tree
Hide file tree
Showing 4 changed files with 269 additions and 57 deletions.
35 changes: 35 additions & 0 deletions lib/cbc_cipher.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import 'dart:typed_data';

import 'package:pointycastle/export.dart' hide State;
import 'package:shared_preferences/shared_preferences.dart';

class CBCCipher {
static Uint8List aesKey = Uint8List(0);

static Future<void> initKey() async {
final prefs = await SharedPreferences.getInstance();
final key = prefs.getString('encrypt_key') ?? '';
if (key.isNotEmpty) {
aesKey = Uint8List.fromList(key.codeUnits);
}
}

static Uint8List processBodyBytes(Uint8List bodyBytes) {
final iv = Uint8List.sublistView(bodyBytes, 0, aesKey.length);
final cipherText = Uint8List.sublistView(bodyBytes, aesKey.length);

final cbc = CBCBlockCipher(AESFastEngine())
..init(false, ParametersWithIV(KeyParameter(aesKey), iv));

final paddedPlainText = Uint8List(cipherText.length);

/* decrypt take 100ms(cold), 50ms(medium), 15-30ms(hot) */
var offset = 0;
while (offset < cipherText.length) {
offset += cbc.processBlock(cipherText, offset, paddedPlainText, offset);
}

return Uint8List.sublistView(
paddedPlainText, 0, paddedPlainText.length - paddedPlainText.last);
}
}
142 changes: 142 additions & 0 deletions lib/device_list.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:scrcpy_flutter/cbc_cipher.dart';
import 'package:scrcpy_flutter/scrcpy.dart';
import 'package:shared_preferences/shared_preferences.dart';

class DeviceList extends StatefulWidget {
const DeviceList({Key? key, required this.refreshNotifier}) : super(key: key);
final ChangeNotifier refreshNotifier;

@override
_DeviceListState createState() => _DeviceListState();
}

class _DeviceListState extends State<DeviceList> {
List<_DeviceWidget> _deviceWidgetList = [];
SharedPreferences? prefs;

@override
void initState() {
super.initState();

SharedPreferences.getInstance().then((prefs) {
this.prefs = prefs;
final devicesStr = prefs.getString('queried_devices') ?? '';
if (devicesStr.isEmpty) {
batchQueryWrapped();
} else if (CBCCipher.aesKey.isNotEmpty) {
_deviceWidgetList.addAll(_DeviceWidget.jsonStringToList(devicesStr));
}

/* clear and refresh */
widget.refreshNotifier.addListener(() async {
_deviceWidgetList = [];
prefs.remove('queried_devices');
batchQueryWrapped();
});
});
}

batchQueryWrapped() {
if (CBCCipher.aesKey.isNotEmpty) {
batchQuery();
}
}

batchQuery() {
final List<String> prefixList = ['192.168.0', '192.168.1'];

for (var element in prefixList) {
for (var i = 1; i < 255; ++i) {
query('$element.$i');
}
}
}

query(String ip) async {
try {
final res = await http.get(Uri.parse('http://$ip:7008/huinyegrbizgn'));
final bytes = CBCCipher.processBodyBytes(res.bodyBytes);
final name = String.fromCharCodes(bytes);
setState(() {
_deviceWidgetList.add(_DeviceWidget(ip: ip, name: name));
});
prefs!.setString(
'queried_devices', _DeviceWidget.listToJsonString(_deviceWidgetList));
} catch (e) {
/* ignore */
}
}

@override
Widget build(BuildContext context) {
return CBCCipher.aesKey.isNotEmpty
? GridView.count(
crossAxisCount: 2,
padding: const EdgeInsets.all(10),
mainAxisSpacing: 10,
crossAxisSpacing: 10,
children: _deviceWidgetList,
)
: const Center(
child: Text('Please set key'),
);
}
}

class _DeviceWidget extends StatefulWidget {
final String name;
final String ip;

const _DeviceWidget({Key? key, required this.ip, this.name = ''})
: super(key: key);

static String listToJsonString(List<_DeviceWidget> list) {
return jsonEncode(list.map((e) => {"ip": e.ip, "name": e.name}).toList());
}

static List<_DeviceWidget> jsonStringToList(String str) {
return (jsonDecode(str) as List<dynamic>)
.map((e) => _DeviceWidget(
ip: e['ip']!,
name: e['name']!,
))
.toList();
}

@override
_DeviceWidgetState createState() => _DeviceWidgetState();
}

class _DeviceWidgetState extends State<_DeviceWidget> {
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => Scrcpy(
ip: widget.ip,
)));
},
child: Container(
alignment: Alignment.center,
decoration: const BoxDecoration(color: Colors.black26),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(widget.name),
const SizedBox(
height: 2,
),
Text(
widget.ip,
style: const TextStyle(color: Colors.black26, fontSize: 12),
),
],
)),
);
}
}
96 changes: 71 additions & 25 deletions lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
import 'dart:async';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:scrcpy_flutter/cbc_cipher.dart';
import 'package:scrcpy_flutter/device_list.dart';
import 'package:scrcpy_flutter/scrcpy.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await CBCCipher.initKey();
runApp(const MyApp());
}

Expand All @@ -27,14 +34,16 @@ class MyApp extends StatelessWidget {
// is not restarted.
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
home: MyHomePage(),
debugShowCheckedModeBanner: false,
);
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
MyHomePage({Key? key}) : super(key: key) {
CBCCipher.initKey();
}

// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
Expand All @@ -46,6 +55,7 @@ class MyHomePage extends StatefulWidget {

class _MyHomePageState extends State<MyHomePage> {
SharedPreferences? prefs;
final refreshDeviceNotifier = ChangeNotifier();

_MyHomePageState() {
SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
Expand Down Expand Up @@ -99,33 +109,35 @@ class _MyHomePageState extends State<MyHomePage> {
return Scaffold(
appBar: AppBar(
title: Text('X'),
actions: [
IconButton(
onPressed: () {
refreshDeviceNotifier.notifyListeners();
},
icon: const Icon(Icons.refresh)),
PopupMenuButton(itemBuilder: (_context) {
return [
PopupMenuItem(
child: const Text('Key'),
onTap: () {
Timer.run(() async {
final result = await _openEditEncryptKeyDialog(context);
if (result.isNotEmpty) {
refreshDeviceNotifier.notifyListeners();
}
});
},
)
];
}),
],
),
resizeToAvoidBottomInset: false,
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'xxx',
style: Theme.of(context).textTheme.headline4,
),
],
child: DeviceList(
refreshNotifier: refreshDeviceNotifier,
),
),
floatingActionButton: FloatingActionButton(
Expand All @@ -136,3 +148,37 @@ class _MyHomePageState extends State<MyHomePage> {
);
}
}

Future<String> _openEditEncryptKeyDialog(BuildContext context) async {
final prefs = await SharedPreferences.getInstance();
final String key = prefs.getString('encrypt_key') ?? '';

TextEditingController _controller = TextEditingController()..text = key;

return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text('Key(16 length)'),
titlePadding: const EdgeInsets.symmetric(vertical: 2, horizontal: 8),
contentPadding: const EdgeInsets.symmetric(vertical: 2, horizontal: 8),
content: TextField(
controller: _controller,
autofocus: true,
),
actions: [
ElevatedButton(
onPressed: () {
final text = _controller.text;
prefs.setString('encrypt_key', text);
CBCCipher.aesKey = Uint8List.fromList(text.codeUnits);
Navigator.of(context).pop(_controller.text);
},
child: const Text('OK')),
],
);
},
).then((value) {
return value ?? '';
});
}
Loading

0 comments on commit 0e77b14

Please sign in to comment.