add apibuilder widget to make api callsmore straightforward and data updateable from everywhere through providers

This commit is contained in:
lukas-heiligenbrunner 2023-12-30 22:23:42 +01:00
parent 6ca462e2d2
commit fca5df4c70
28 changed files with 812 additions and 341 deletions

View File

@ -1,14 +1,15 @@
use crate::api::add::okapi_add_operation_for_package_add_; use crate::api::add::okapi_add_operation_for_package_add_;
use crate::api::add::package_add; use crate::api::add::package_add;
use crate::api::list::{get_build, okapi_add_operation_for_list_builds_}; use crate::api::list::okapi_add_operation_for_get_build_;
use crate::api::list::okapi_add_operation_for_get_package_;
use crate::api::list::okapi_add_operation_for_stats_; use crate::api::list::okapi_add_operation_for_stats_;
use crate::api::list::{build_output, okapi_add_operation_for_package_list_}; use crate::api::list::{build_output, okapi_add_operation_for_package_list_};
use crate::api::list::{get_build, get_package, okapi_add_operation_for_list_builds_};
use crate::api::list::{list_builds, okapi_add_operation_for_search_}; use crate::api::list::{list_builds, okapi_add_operation_for_search_};
use crate::api::list::{okapi_add_operation_for_build_output_, stats}; use crate::api::list::{okapi_add_operation_for_build_output_, stats};
use crate::api::list::{package_list, search}; use crate::api::list::{package_list, search};
use crate::api::remove::okapi_add_operation_for_package_del_; use crate::api::remove::okapi_add_operation_for_package_del_;
use crate::api::remove::okapi_add_operation_for_version_del_; use crate::api::remove::okapi_add_operation_for_version_del_;
use crate::api::list::okapi_add_operation_for_get_build_;
use crate::api::remove::{package_del, version_del}; use crate::api::remove::{package_del, version_del};
use rocket::Route; use rocket::Route;
use rocket_okapi::openapi_get_routes; use rocket_okapi::openapi_get_routes;
@ -23,6 +24,7 @@ pub fn build_api() -> Vec<Route> {
build_output, build_output,
list_builds, list_builds,
stats, stats,
get_build get_build,
get_package
] ]
} }

View File

@ -9,7 +9,7 @@ use rocket::serde::{Deserialize, Serialize};
use rocket::{get, State}; use rocket::{get, State};
use rocket_okapi::okapi::schemars; use rocket_okapi::okapi::schemars;
use rocket_okapi::{openapi, JsonSchema}; use rocket_okapi::{openapi, JsonSchema};
use sea_orm::{PaginatorTrait}; use sea_orm::PaginatorTrait;
use sea_orm::{ColumnTrait, QueryFilter}; use sea_orm::{ColumnTrait, QueryFilter};
use sea_orm::{DatabaseConnection, EntityTrait, FromQueryResult, QuerySelect, RelationTrait}; use sea_orm::{DatabaseConnection, EntityTrait, FromQueryResult, QuerySelect, RelationTrait};
@ -70,6 +70,32 @@ pub async fn package_list(
Ok(Json(all)) Ok(Json(all))
} }
#[openapi(tag = "test")]
#[get("/package/<id>")]
pub async fn get_package(
db: &State<DatabaseConnection>,
id: u64,
) -> Result<Json<ListPackageModel>, NotFound<String>> {
let db = db as &DatabaseConnection;
let all: ListPackageModel = Packages::find()
.join_rev(JoinType::InnerJoin, versions::Relation::Packages.def())
.filter(packages::Column::Id.eq(id))
.select_only()
.column_as(versions::Column::Id.count(), "count")
.column(packages::Column::Name)
.column(packages::Column::Id)
.column(packages::Column::Status)
.group_by(packages::Column::Name)
.into_model::<ListPackageModel>()
.one(db)
.await
.map_err(|e| NotFound(e.to_string()))?
.ok_or(NotFound("id not found".to_string()))?;
Ok(Json(all))
}
#[openapi(tag = "test")] #[openapi(tag = "test")]
#[get("/builds/output?<buildid>&<startline>")] #[get("/builds/output?<buildid>&<startline>")]
pub async fn build_output( pub async fn build_output(
@ -172,7 +198,10 @@ pub async fn get_build(
.column_as(packages::Column::Name, "pkg_name") .column_as(packages::Column::Name, "pkg_name")
.column(versions::Column::Version) .column(versions::Column::Version)
.into_model::<ListBuildsModel>() .into_model::<ListBuildsModel>()
.one(db).await.map_err(|e| NotFound(e.to_string()))?.ok_or(NotFound("no item with id found".to_string()))?; .one(db)
.await
.map_err(|e| NotFound(e.to_string()))?
.ok_or(NotFound("no item with id found".to_string()))?;
Ok(Json(result)) Ok(Json(result))
} }

View File

@ -6,22 +6,12 @@ use rocket_okapi::okapi::schemars;
use rocket_okapi::{openapi, JsonSchema}; use rocket_okapi::{openapi, JsonSchema};
use sea_orm::DatabaseConnection; use sea_orm::DatabaseConnection;
#[derive(Deserialize, JsonSchema)]
#[serde(crate = "rocket::serde")]
pub struct DelBody {
id: i32,
}
#[openapi(tag = "test")] #[openapi(tag = "test")]
#[post("/packages/delete", data = "<input>")] #[post("/package/delete/<id>")]
pub async fn package_del( pub async fn package_del(db: &State<DatabaseConnection>, id: i32) -> Result<(), String> {
db: &State<DatabaseConnection>,
input: Json<DelBody>,
) -> Result<(), String> {
let db = db as &DatabaseConnection; let db = db as &DatabaseConnection;
let pkg_id = input.id.clone();
remove_pkg(db, pkg_id).await.map_err(|e| e.to_string())?; remove_pkg(db, id).await.map_err(|e| e.to_string())?;
Ok(()) Ok(())
} }

View File

@ -2,7 +2,8 @@ import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
class ApiClient { class ApiClient {
static const String _apiBase = !kDebugMode ? "http://localhost:8081/api" : "api"; static const String _apiBase =
kDebugMode ? "http://localhost:8081/api" : "api";
final Dio _dio = Dio(BaseOptions(baseUrl: _apiBase)); final Dio _dio = Dio(BaseOptions(baseUrl: _apiBase));
String? token; String? token;

View File

@ -2,8 +2,17 @@ import '../models/build.dart';
import 'api_client.dart'; import 'api_client.dart';
extension BuildsAPI on ApiClient { extension BuildsAPI on ApiClient {
Future<List<Build>> listAllBuilds() async { Future<List<Build>> listAllBuilds({int? pkgID, int? limit}) async {
final resp = await getRawClient().get("/builds"); String uri = "/builds?";
if (pkgID != null) {
uri += "pkgid=$pkgID";
}
if (limit != null) {
uri += "limit=$limit";
}
final resp = await getRawClient().get(uri);
final responseObject = resp.data as List; final responseObject = resp.data as List;
final List<Build> packages = final List<Build> packages =

View File

@ -11,9 +11,21 @@ extension PackagesAPI on ApiClient {
return packages; return packages;
} }
Future<Package> getPackage(int id) async {
final resp = await getRawClient().get("/package/$id");
final package = Package.fromJson(resp.data);
return package;
}
Future<void> addPackage({bool force = false, required String name}) async { Future<void> addPackage({bool force = false, required String name}) async {
final resp = await getRawClient() final resp = await getRawClient()
.post("/packages/add", data: {'force_build': force, 'name': name}); .post("/packages/add", data: {'force_build': force, 'name': name});
print(resp.data); print(resp.data);
} }
Future<bool> deletePackage(int id) async {
final resp = await getRawClient().post("/package/delete/$id");
return resp.statusCode == 200;
}
} }

View File

@ -0,0 +1,95 @@
import 'dart:async';
import 'package:aurcache/api/builds.dart';
import 'package:flutter/material.dart';
import '../api/API.dart';
import '../models/build.dart';
class BuildOutput extends StatefulWidget {
const BuildOutput({super.key, required this.build});
final Build build;
@override
State<BuildOutput> createState() => _BuildOutputState();
}
class _BuildOutputState extends State<BuildOutput> {
late Future<String> initialOutput;
String output = "";
Timer? outputTimer;
final scrollController = ScrollController();
@override
Widget build(BuildContext context) {
return Expanded(
flex: 1,
child: SingleChildScrollView(
controller: scrollController,
scrollDirection: Axis.vertical, //.horizontal
child: Padding(
padding: const EdgeInsets.only(left: 30, right: 15),
child: Text(
output,
style: const TextStyle(
fontSize: 16.0,
color: Colors.white,
),
),
),
),
);
}
@override
void initState() {
super.initState();
initOutputLoader();
}
void initOutputLoader() {
initialOutput = API.getOutput(buildID: widget.build.id);
initialOutput.then((value) {
setState(() {
output = value;
});
_scrollToBottom();
});
// poll new output only if not finished
if (widget.build.status == 0) {
outputTimer = Timer.periodic(const Duration(seconds: 3), (Timer t) async {
print("refreshing output");
final value = await API.getOutput(
buildID: widget.build.id, line: output.split("\n").length);
setState(() {
output += value;
});
_scrollToBottom();
});
}
}
void _scrollToBottom() {
WidgetsBinding.instance.addPostFrameCallback((_) {
// scroll to bottom
final scrollPosition = scrollController.position;
if (scrollPosition.viewportDimension < scrollPosition.maxScrollExtent) {
scrollController.animateTo(
scrollPosition.maxScrollExtent,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOut,
);
}
});
}
@override
void dispose() {
super.dispose();
outputTimer?.cancel();
}
}

View File

@ -0,0 +1,53 @@
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import '../constants/color_constants.dart';
import '../models/build.dart';
import 'dashboard/your_packages.dart';
class BuildsTable extends StatelessWidget {
const BuildsTable({super.key, required this.data});
final List<Build> data;
@override
Widget build(BuildContext context) {
return DataTable(
horizontalMargin: 0,
columnSpacing: defaultPadding,
columns: const [
DataColumn(
label: Text("Build ID"),
),
DataColumn(
label: Text("Package Name"),
),
DataColumn(
label: Text("Version"),
),
DataColumn(
label: Text("Status"),
),
],
rows: data.map((e) => buildDataRow(context, e)).toList(),
);
}
DataRow buildDataRow(BuildContext context, Build build) {
return DataRow(
cells: [
DataCell(Text(build.id.toString())),
DataCell(Text(build.pkg_name)),
DataCell(Text(build.version)),
DataCell(IconButton(
icon: Icon(
switchSuccessIcon(build.status),
color: switchSuccessColor(build.status),
),
onPressed: () {
context.push("/build/${build.id}");
},
)),
],
);
}
}

View File

@ -0,0 +1,41 @@
import 'package:flutter/material.dart';
Future<bool> showDeleteConfirmationDialog(BuildContext context) async {
return (await showDialog<bool>(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return Stack(
children: <Widget>[
GestureDetector(
onTap: () {
Navigator.of(context).pop(false); // Dismiss dialog on outside tap
},
child: Container(
color: Colors.black.withOpacity(0.5), // Adjust opacity for blur
),
),
// Delete confirmation dialog
AlertDialog(
title: Text('Confirm Delete'),
content: Text('Are you sure you want to delete this item?'),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pop(true);
},
child: Text('Yes, Delete'),
),
TextButton(
onPressed: () {
Navigator.of(context).pop(false); // Dismiss dialog
},
child: Text('Cancel'),
),
],
),
],
);
},
))!;
}

View File

@ -1,10 +1,14 @@
import 'dart:async'; import 'dart:async';
import 'package:aurcache/api/builds.dart'; import 'package:aurcache/api/builds.dart';
import 'package:aurcache/components/builds_table.dart';
import 'package:aurcache/models/build.dart'; import 'package:aurcache/models/build.dart';
import 'package:aurcache/components/dashboard/your_packages.dart'; import 'package:aurcache/components/dashboard/your_packages.dart';
import 'package:aurcache/providers/APIBuilder.dart';
import 'package:aurcache/providers/builds_provider.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart'; import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import '../../api/API.dart'; import '../../api/API.dart';
import '../../constants/color_constants.dart'; import '../../constants/color_constants.dart';
@ -19,27 +23,6 @@ class RecentBuilds extends StatefulWidget {
} }
class _RecentBuildsState extends State<RecentBuilds> { class _RecentBuildsState extends State<RecentBuilds> {
late Future<List<Build>> dataFuture;
Timer? timer;
@override
void initState() {
super.initState();
dataFuture = API.listAllBuilds();
timer = Timer.periodic(
const Duration(seconds: 10),
(Timer t) => setState(() {
dataFuture = API.listAllBuilds();
}));
}
@override
void dispose() {
super.dispose();
timer?.cancel();
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Container( return Container(
@ -57,57 +40,26 @@ class _RecentBuildsState extends State<RecentBuilds> {
), ),
SizedBox( SizedBox(
width: double.infinity, width: double.infinity,
child: FutureBuilder( child: APIBuilder<BuildsProvider, List<Build>, BuildsDTO>(
future: dataFuture, dto: BuildsDTO(limit: 10),
builder: (context, snapshot) { interval: const Duration(seconds: 10),
if (snapshot.hasData) { onLoad: () => const Text("no data"),
return DataTable( onData: (t) {
horizontalMargin: 0, return BuildsTable(data: t);
columnSpacing: defaultPadding, },
columns: const [ ),
DataColumn(
label: Text("Build ID"),
),
DataColumn(
label: Text("Package Name"),
),
DataColumn(
label: Text("Version"),
),
DataColumn(
label: Text("Status"),
),
],
rows: snapshot.data!
.map((e) => recentUserDataRow(e))
.toList(),
);
} else {
return const Text("no data");
}
}),
), ),
ElevatedButton(
onPressed: () {
context.push("/builds");
},
child: Text(
"List all Builds",
style: TextStyle(color: Colors.white.withOpacity(0.8)),
),
)
], ],
), ),
); );
} }
DataRow recentUserDataRow(Build build) {
return DataRow(
cells: [
DataCell(Text(build.id.toString())),
DataCell(Text(build.pkg_name)),
DataCell(Text(build.version)),
DataCell(IconButton(
icon: Icon(
switchSuccessIcon(build.status),
color: switchSuccessColor(build.status),
),
onPressed: () {
context.push("/build/${build.id}");
},
)),
],
);
}
} }

View File

@ -1,9 +1,13 @@
import 'package:aurcache/api/packages.dart'; import 'package:aurcache/api/packages.dart';
import 'package:aurcache/providers/builds_provider.dart';
import 'package:aurcache/providers/stats_provider.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart'; import 'package:flutter_svg/svg.dart';
import 'package:provider/provider.dart';
import '../../api/API.dart'; import '../../api/API.dart';
import '../../constants/color_constants.dart'; import '../../constants/color_constants.dart';
import '../../providers/packages_provider.dart';
class SearchField extends StatelessWidget { class SearchField extends StatelessWidget {
SearchField({ SearchField({
@ -25,9 +29,14 @@ class SearchField extends StatelessWidget {
borderRadius: BorderRadius.all(Radius.circular(10)), borderRadius: BorderRadius.all(Radius.circular(10)),
), ),
suffixIcon: InkWell( suffixIcon: InkWell(
onTap: () { onTap: () async {
// todo this is only temporary -> add this to a proper page // todo this is only temporary -> add this to a proper page
API.addPackage(name: controller.text); await API.addPackage(name: controller.text, force: true);
Provider.of<PackagesProvider>(context, listen: false)
.refresh(context);
Provider.of<BuildsProvider>(context, listen: false)
.refresh(context);
Provider.of<StatsProvider>(context, listen: false).refresh(context);
}, },
child: Container( child: Container(
padding: EdgeInsets.all(defaultPadding * 0.75), padding: EdgeInsets.all(defaultPadding * 0.75),

View File

@ -1,11 +1,18 @@
import 'dart:async'; import 'dart:async';
import 'package:aurcache/api/packages.dart'; import 'package:aurcache/api/packages.dart';
import 'package:aurcache/providers/APIBuilder.dart';
import 'package:aurcache/providers/packages_provider.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import '../../api/API.dart'; import '../../api/API.dart';
import '../../constants/color_constants.dart'; import '../../constants/color_constants.dart';
import '../../models/package.dart'; import '../../models/package.dart';
import '../../providers/builds_provider.dart';
import '../../providers/stats_provider.dart';
import '../confirm_popup.dart';
class YourPackages extends StatefulWidget { class YourPackages extends StatefulWidget {
const YourPackages({ const YourPackages({
@ -17,27 +24,6 @@ class YourPackages extends StatefulWidget {
} }
class _YourPackagesState extends State<YourPackages> { class _YourPackagesState extends State<YourPackages> {
late Future<List<Package>> dataFuture;
Timer? timer;
@override
void initState() {
super.initState();
dataFuture = API.listPackages();
timer = Timer.periodic(
const Duration(seconds: 10),
(Timer t) => setState(() {
dataFuture = API.listPackages();
}));
}
@override
void dispose() {
super.dispose();
timer?.cancel();
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Container( return Container(
@ -57,10 +43,11 @@ class _YourPackagesState extends State<YourPackages> {
//scrollDirection: Axis.horizontal, //scrollDirection: Axis.horizontal,
child: SizedBox( child: SizedBox(
width: double.infinity, width: double.infinity,
child: FutureBuilder( child: APIBuilder<PackagesProvider, List<Package>, Object>(
builder: (context, snapshot) { key: GlobalKey(),
if (snapshot.hasData) { interval: const Duration(seconds: 10),
return DataTable( onData: (data) {
return DataTable(
horizontalMargin: 0, horizontalMargin: 0,
columnSpacing: defaultPadding, columnSpacing: defaultPadding,
columns: const [ columns: const [
@ -80,15 +67,11 @@ class _YourPackagesState extends State<YourPackages> {
label: Text("Action"), label: Text("Action"),
), ),
], ],
rows: snapshot.data! rows: data
.map((e) => buildDataRow(e)) .map((e) => buildDataRow(e))
.toList(growable: false), .toList(growable: false));
);
} else {
return const Text("No data");
}
}, },
future: dataFuture, onLoad: () => const Text("No data"),
), ),
), ),
), ),
@ -117,7 +100,9 @@ class _YourPackagesState extends State<YourPackages> {
children: [ children: [
TextButton( TextButton(
child: const Text('View', style: TextStyle(color: greenColor)), child: const Text('View', style: TextStyle(color: greenColor)),
onPressed: () {}, onPressed: () {
context.push("/package/${package.id}");
},
), ),
const SizedBox( const SizedBox(
width: 6, width: 6,
@ -125,7 +110,21 @@ class _YourPackagesState extends State<YourPackages> {
TextButton( TextButton(
child: const Text("Delete", child: const Text("Delete",
style: TextStyle(color: Colors.redAccent)), style: TextStyle(color: Colors.redAccent)),
onPressed: () {}, onPressed: () async {
final confirmResult =
await showDeleteConfirmationDialog(context);
if (!confirmResult) return;
final succ = await API.deletePackage(package.id);
if (succ) {
Provider.of<PackagesProvider>(context, listen: false)
.refresh(context);
Provider.of<BuildsProvider>(context, listen: false)
.refresh(context);
Provider.of<StatsProvider>(context, listen: false)
.refresh(context);
}
},
), ),
], ],
), ),

View File

@ -1,6 +1,8 @@
import 'package:aurcache/screens/build_screen.dart'; import 'package:aurcache/screens/build_screen.dart';
import 'package:aurcache/screens/builds_screen.dart';
import 'package:aurcache/screens/dashboard_screen.dart'; import 'package:aurcache/screens/dashboard_screen.dart';
import 'package:aurcache/components/menu_shell.dart'; import 'package:aurcache/components/menu_shell.dart';
import 'package:aurcache/screens/package_screen.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart'; import 'package:go_router/go_router.dart';
@ -21,15 +23,24 @@ final appRouter = GoRouter(
GoRoute( GoRoute(
path: '/', path: '/',
builder: (context, state) => DashboardScreen(), builder: (context, state) => DashboardScreen(),
routes: [ ),
GoRoute( GoRoute(
path: 'build/:id', path: '/build/:id',
builder: (context, state) { builder: (context, state) {
final id = int.parse(state.pathParameters['id']!); final id = int.parse(state.pathParameters['id']!);
return BuildScreen(buildID: id); return BuildScreen(buildID: id);
}, },
), ),
] GoRoute(
path: '/builds',
builder: (context, state) => const BuildsScreen(),
),
GoRoute(
path: '/package/:id',
builder: (context, state) {
final id = int.parse(state.pathParameters['id']!);
return PackageScreen(pkgID: id);
},
), ),
], ],
), ),

View File

@ -1,7 +1,13 @@
import 'package:aurcache/components/router.dart'; import 'package:aurcache/components/router.dart';
import 'package:aurcache/providers/build_provider.dart';
import 'package:aurcache/providers/builds_provider.dart';
import 'package:aurcache/providers/package_provider.dart';
import 'package:aurcache/providers/packages_provider.dart';
import 'package:aurcache/providers/stats_provider.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart'; import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart'; import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart';
import 'constants/color_constants.dart'; import 'constants/color_constants.dart';
void main() { void main() {
@ -14,22 +20,31 @@ class MyApp extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return MaterialApp.router( return MultiProvider(
routerConfig: appRouter, providers: [
debugShowCheckedModeBanner: false, ChangeNotifierProvider<StatsProvider>(create: (_) => StatsProvider()),
title: 'Smart Dashboard - Admin Panel v0.1 ', ChangeNotifierProvider<PackagesProvider>(
theme: ThemeData.dark().copyWith( create: (_) => PackagesProvider()),
appBarTheme: const AppBarTheme(backgroundColor: bgColor, elevation: 0), ChangeNotifierProvider<BuildsProvider>(create: (_) => BuildsProvider()),
scaffoldBackgroundColor: bgColor, ChangeNotifierProvider<PackageProvider>(
primaryColor: greenColor, create: (_) => PackageProvider()),
dialogBackgroundColor: secondaryColor, ChangeNotifierProvider<BuildProvider>(create: (_) => BuildProvider()),
textTheme: GoogleFonts.openSansTextTheme(Theme.of(context).textTheme) ],
.apply(bodyColor: Colors.white), child: MaterialApp.router(
canvasColor: secondaryColor, routerConfig: appRouter,
debugShowCheckedModeBanner: false,
title: 'AURCache',
theme: ThemeData.dark().copyWith(
appBarTheme:
const AppBarTheme(backgroundColor: bgColor, elevation: 0),
scaffoldBackgroundColor: bgColor,
primaryColor: greenColor,
dialogBackgroundColor: secondaryColor,
textTheme: GoogleFonts.openSansTextTheme(Theme.of(context).textTheme)
.apply(bodyColor: Colors.white),
canvasColor: secondaryColor,
),
), ),
routeInformationParser: appRouter.routeInformationParser,
routeInformationProvider: appRouter.routeInformationProvider,
routerDelegate: appRouter.routerDelegate,
); );
} }
} }

View File

@ -0,0 +1,67 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'BaseProvider.dart';
class APIBuilder<T extends BaseProvider, K, DTO> extends StatefulWidget {
const APIBuilder(
{super.key,
required this.onLoad,
required this.onData,
this.interval,
this.dto});
final DTO? dto;
final Duration? interval;
final Widget Function() onLoad;
final Widget Function(K t) onData;
@override
State<APIBuilder<T, K, DTO>> createState() => _APIBuilderState<T, K, DTO>();
}
class _APIBuilderState<T extends BaseProvider, K, DTO>
extends State<APIBuilder<T, K, DTO>> {
Timer? timer;
@override
void initState() {
super.initState();
Provider.of<T>(context, listen: false).loadFuture(context, dto: widget.dto);
if (widget.interval != null) {
timer = Timer.periodic(widget.interval!, (Timer t) {
final RenderObject? box = context.findRenderObject();
print(box);
print(context.mounted);
Provider.of<T>(context, listen: false)
.refresh(context, dto: widget.dto);
});
}
}
@override
void dispose() {
super.dispose();
timer?.cancel();
}
@override
Widget build(BuildContext context) {
final Future<K> fut = Provider.of<T>(context).data as Future<K>;
return FutureBuilder<K>(
future: fut,
builder: (context, snapshot) {
if (snapshot.hasData) {
return widget.onData(snapshot.data!);
} else {
return widget.onLoad();
}
},
);
}
}

View File

@ -0,0 +1,12 @@
import 'package:flutter/material.dart';
abstract class BaseProvider<T, DTO> with ChangeNotifier {
late Future<T> data;
loadFuture(context, {DTO? dto});
refresh(context, {DTO? dto}) {
loadFuture(context, dto: dto);
notifyListeners();
}
}

View File

@ -0,0 +1,19 @@
import 'package:aurcache/api/builds.dart';
import '../api/API.dart';
import '../models/build.dart';
import 'BaseProvider.dart';
class BuildDTO {
final int buildID;
BuildDTO({required this.buildID});
}
class BuildProvider extends BaseProvider<Build, BuildDTO> {
@override
loadFuture(context, {dto}) {
// todo search solution to force an exising dto
data = API.getBuild(dto!.buildID);
}
}

View File

@ -0,0 +1,23 @@
import 'package:aurcache/api/builds.dart';
import '../api/API.dart';
import '../models/build.dart';
import 'BaseProvider.dart';
class BuildsDTO {
final int? pkgID;
final int? limit;
BuildsDTO({this.pkgID, this.limit});
}
class BuildsProvider extends BaseProvider<List<Build>, BuildsDTO> {
@override
loadFuture(context, {dto}) {
if (dto != null) {
data = API.listAllBuilds(pkgID: dto.pkgID, limit: dto.limit);
} else {
data = API.listAllBuilds();
}
}
}

View File

@ -1 +0,0 @@

View File

@ -0,0 +1,19 @@
import 'package:aurcache/api/packages.dart';
import '../api/API.dart';
import '../models/package.dart';
import 'BaseProvider.dart';
class PackageDTO {
final int pkgID;
PackageDTO({required this.pkgID});
}
class PackageProvider extends BaseProvider<Package, PackageDTO> {
@override
loadFuture(context, {dto}) {
// todo search solution to force an exising dto
data = API.getPackage(dto!.pkgID);
}
}

View File

@ -0,0 +1,11 @@
import 'package:aurcache/api/packages.dart';
import 'package:aurcache/providers/BaseProvider.dart';
import '../api/API.dart';
class PackagesProvider extends BaseProvider {
@override
loadFuture(context, {dto}) {
data = API.listPackages();
}
}

View File

@ -0,0 +1,11 @@
import 'package:aurcache/api/statistics.dart';
import '../api/API.dart';
import 'BaseProvider.dart';
class StatsProvider extends BaseProvider {
@override
loadFuture(context, {dto}) {
data = API.listStats();
}
}

View File

@ -1,7 +1,10 @@
import 'dart:async'; import 'dart:async';
import 'package:aurcache/api/builds.dart'; import 'package:aurcache/api/builds.dart';
import 'package:aurcache/components/build_output.dart';
import 'package:aurcache/models/build.dart'; import 'package:aurcache/models/build.dart';
import 'package:aurcache/providers/APIBuilder.dart';
import 'package:aurcache/providers/build_provider.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart'; import 'package:go_router/go_router.dart';
@ -18,146 +21,54 @@ class BuildScreen extends StatefulWidget {
} }
class _BuildScreenState extends State<BuildScreen> { class _BuildScreenState extends State<BuildScreen> {
late Future<Build> buildData;
late Future<String> initialOutput;
String output = "";
Timer? outputTimer, buildDataTimer;
final scrollController = ScrollController();
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
body: FutureBuilder( body: APIBuilder<BuildProvider, Build, BuildDTO>(
future: buildData, dto: BuildDTO(buildID: widget.buildID),
builder: (context, snapshot) { interval: const Duration(seconds: 10),
if (snapshot.hasData) { onLoad: () => const Text("no data"),
final buildData = snapshot.data!; onData: (buildData) {
return Column(
return Column( crossAxisAlignment: CrossAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start, children: [
children: [ Row(
Row( mainAxisAlignment: MainAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start, children: [
children: [ const SizedBox(
const SizedBox( width: 10,
width: 10,
),
IconButton(
icon: Icon(
switchSuccessIcon(buildData.status),
color: switchSuccessColor(buildData.status),
),
onPressed: () {
context.replace("/build/${buildData.id}");
},
),
const SizedBox(
width: 10,
),
Text(
buildData.pkg_name,
style: const TextStyle(fontWeight: FontWeight.bold),
),
const SizedBox(
width: 10,
),
const Text("triggered 2 months ago")
],
),
const SizedBox(
height: 15,
),
Expanded(
flex: 1,
child: SingleChildScrollView(
controller: scrollController,
scrollDirection: Axis.vertical, //.horizontal
child: Padding(
padding: const EdgeInsets.only(left: 30, right: 15),
child: Text(
output,
style: const TextStyle(
fontSize: 16.0,
color: Colors.white,
),
),
),
), ),
), IconButton(
], icon: Icon(
); switchSuccessIcon(buildData.status),
} else { color: switchSuccessColor(buildData.status),
return const Text("loading build"); ),
} onPressed: () {
context.replace("/build/${buildData.id}");
},
),
const SizedBox(
width: 10,
),
Text(
buildData.pkg_name,
style: const TextStyle(fontWeight: FontWeight.bold),
),
const SizedBox(
width: 10,
),
const Text("triggered 2 months ago")
],
),
const SizedBox(
height: 15,
),
BuildOutput(build: buildData)
],
);
}), }),
appBar: AppBar(), appBar: AppBar(),
); );
} }
@override
void initState() {
super.initState();
initBuildDataLoader();
initOutputLoader();
}
void initBuildDataLoader() {
buildData = API.getBuild(widget.buildID);
buildDataTimer = Timer.periodic(const Duration(seconds: 10), (t) {
setState(() {
buildData = API.getBuild(widget.buildID);
});
});
}
void initOutputLoader() {
initialOutput = API.getOutput(buildID: widget.buildID);
initialOutput.then((value) {
setState(() {
output = value;
});
_scrollToBottom();
});
buildData.then((value) {
// poll new output only if not finished
if (value.status == 0) {
outputTimer =
Timer.periodic(const Duration(seconds: 3), (Timer t) async {
print("refreshing output");
final value = await API.getOutput(
buildID: widget.buildID, line: output.split("\n").length);
setState(() {
output += value;
});
_scrollToBottom();
});
}
});
}
void _scrollToBottom() {
WidgetsBinding.instance.addPostFrameCallback((_) {
// scroll to bottom
final scrollPosition = scrollController.position;
if (scrollPosition.viewportDimension < scrollPosition.maxScrollExtent) {
scrollController.animateTo(
scrollPosition.maxScrollExtent,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOut,
);
}
});
}
@override
void dispose() {
super.dispose();
outputTimer?.cancel();
buildDataTimer?.cancel();
}
} }

View File

@ -0,0 +1,47 @@
import 'package:aurcache/components/builds_table.dart';
import 'package:aurcache/providers/APIBuilder.dart';
import 'package:aurcache/providers/builds_provider.dart';
import 'package:flutter/material.dart';
import '../constants/color_constants.dart';
import '../models/build.dart';
class BuildsScreen extends StatelessWidget {
const BuildsScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Padding(
padding: const EdgeInsets.all(defaultPadding),
child: Container(
padding: const EdgeInsets.all(defaultPadding),
decoration: const BoxDecoration(
color: secondaryColor,
borderRadius: BorderRadius.all(Radius.circular(10)),
),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"All Builds",
style: Theme.of(context).textTheme.subtitle1,
),
SizedBox(
width: double.infinity,
child: APIBuilder<BuildsProvider, List<Build>, Object>(
interval: const Duration(seconds: 10),
onLoad: () => const Text("no data"),
onData: (data) {
return BuildsTable(data: data);
}),
)
],
),
),
),
),
);
}
}

View File

@ -1,5 +1,8 @@
import 'package:aurcache/api/statistics.dart'; import 'package:aurcache/api/statistics.dart';
import 'package:aurcache/providers/APIBuilder.dart';
import 'package:aurcache/providers/stats_provider.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../api/API.dart'; import '../api/API.dart';
import '../components/dashboard/header.dart'; import '../components/dashboard/header.dart';
@ -11,70 +14,70 @@ import '../components/dashboard/recent_builds.dart';
import '../components/dashboard/your_packages.dart'; import '../components/dashboard/your_packages.dart';
import '../components/dashboard/side_panel.dart'; import '../components/dashboard/side_panel.dart';
class DashboardScreen extends StatelessWidget { class DashboardScreen extends StatefulWidget {
final stats = API.listStats(); @override
State<DashboardScreen> createState() => _DashboardScreenState();
}
class _DashboardScreenState extends State<DashboardScreen> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return FutureBuilder( return APIBuilder<StatsProvider, Stats, Object>(
future: stats, onData: (stats) {
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) { return SafeArea(
if (snapshot.hasData) { child: SingleChildScrollView(
final Stats stats = snapshot.data!; child: Container(
padding: const EdgeInsets.all(defaultPadding),
return SafeArea( child: Column(
child: SingleChildScrollView( children: [
child: Container( const Header(),
padding: const EdgeInsets.all(defaultPadding), const SizedBox(height: defaultPadding),
child: Column( QuickInfoBanner(
stats: stats,
),
const SizedBox(height: defaultPadding),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
const Header(), Expanded(
const SizedBox(height: defaultPadding), flex: 5,
QuickInfoBanner( child: Column(
stats: stats, children: [
), const YourPackages(),
const SizedBox(height: defaultPadding), const SizedBox(height: defaultPadding),
Row( const RecentBuilds(),
crossAxisAlignment: CrossAxisAlignment.start, if (Responsive.isMobile(context))
children: [ const SizedBox(height: defaultPadding),
Expanded( if (Responsive.isMobile(context))
flex: 5, SidePanel(
child: Column(
children: [
const YourPackages(),
const SizedBox(height: defaultPadding),
const RecentBuilds(),
if (Responsive.isMobile(context))
const SizedBox(height: defaultPadding),
if (Responsive.isMobile(context))
SidePanel(
nrbuilds: stats.total_builds,
nrfailedbuilds: stats.failed_builds,
nrActiveBuilds: stats.active_builds),
],
),
),
if (!Responsive.isMobile(context))
const SizedBox(width: defaultPadding),
// On Mobile means if the screen is less than 850 we dont want to show it
if (!Responsive.isMobile(context))
Expanded(
flex: 2,
child: SidePanel(
nrbuilds: stats.total_builds, nrbuilds: stats.total_builds,
nrfailedbuilds: stats.failed_builds, nrfailedbuilds: stats.failed_builds,
nrActiveBuilds: stats.active_builds), nrActiveBuilds: stats.active_builds),
), ],
], ),
) ),
if (!Responsive.isMobile(context))
const SizedBox(width: defaultPadding),
// On Mobile means if the screen is less than 850 we dont want to show it
if (!Responsive.isMobile(context))
Expanded(
flex: 2,
child: SidePanel(
nrbuilds: stats.total_builds,
nrfailedbuilds: stats.failed_builds,
nrActiveBuilds: stats.active_builds),
),
], ],
), )
), ],
), ),
); ),
} else { ),
return const Text("loading"); );
} },
}); onLoad: () {
return Text("loading");
},
);
} }
} }

View File

@ -0,0 +1,114 @@
import 'dart:async';
import 'package:aurcache/api/builds.dart';
import 'package:aurcache/api/packages.dart';
import 'package:aurcache/providers/APIBuilder.dart';
import 'package:aurcache/providers/builds_provider.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import '../api/API.dart';
import '../components/builds_table.dart';
import '../components/confirm_popup.dart';
import '../constants/color_constants.dart';
import '../models/build.dart';
import '../models/package.dart';
import '../providers/package_provider.dart';
import '../providers/packages_provider.dart';
class PackageScreen extends StatefulWidget {
const PackageScreen({super.key, required this.pkgID});
final int pkgID;
@override
State<PackageScreen> createState() => _PackageScreenState();
}
class _PackageScreenState extends State<PackageScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: APIBuilder<PackageProvider, Package, PackageDTO>(
dto: PackageDTO(pkgID: widget.pkgID),
onLoad: () => const Text("loading"),
onData: (pkg) {
return Padding(
padding: const EdgeInsets.all(defaultPadding),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
margin: const EdgeInsets.only(left: 15),
child: Text(
pkg.name,
style: const TextStyle(fontSize: 32),
),
),
Container(
margin: const EdgeInsets.only(right: 15),
child: ElevatedButton(
onPressed: () async {
final confirmResult =
await showDeleteConfirmationDialog(context);
if (!confirmResult) return;
final succ = await API.deletePackage(pkg.id);
if (succ) {
context.pop();
}
},
child: const Text(
"Delete",
style: TextStyle(color: Colors.redAccent),
),
),
)
],
),
const SizedBox(
height: 25,
),
Container(
padding: const EdgeInsets.all(defaultPadding),
decoration: const BoxDecoration(
color: secondaryColor,
borderRadius: BorderRadius.all(Radius.circular(10)),
),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Builds of ${pkg.name}",
style: Theme.of(context).textTheme.subtitle1,
),
SizedBox(
width: double.infinity,
child: APIBuilder<BuildsProvider, List<Build>,
BuildsDTO>(
key: GlobalKey(),
dto: BuildsDTO(pkgID: pkg.id),
interval: const Duration(seconds: 5),
onData: (data) {
return BuildsTable(data: data);
},
onLoad: () => const Text("no data"),
),
),
],
),
),
)
],
),
);
}),
);
}
}

View File

@ -208,6 +208,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.10.0" version: "1.10.0"
nested:
dependency: transitive
description:
name: nested
sha256: "03bac4c528c64c95c722ec99280375a6f2fc708eec17c7b3f07253b626cd2a20"
url: "https://pub.dev"
source: hosted
version: "1.0.0"
path: path:
dependency: transitive dependency: transitive
description: description:
@ -296,6 +304,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.1.7" version: "2.1.7"
provider:
dependency: "direct main"
description:
name: provider
sha256: "9a96a0a19b594dbc5bf0f1f27d2bc67d5f95957359b461cd9feb44ed6ae75096"
url: "https://pub.dev"
source: hosted
version: "6.1.1"
sky_engine: sky_engine:
dependency: transitive dependency: transitive
description: flutter description: flutter

View File

@ -40,6 +40,7 @@ dependencies:
google_fonts: ^6.1.0 google_fonts: ^6.1.0
dio: ^5.3.3 dio: ^5.3.3
go_router: ^13.0.0 go_router: ^13.0.0
provider: ^6.1.1
dev_dependencies: dev_dependencies:
flutter_test: flutter_test: