generated from dellevin/template
服务端接口优化
todo:待添加影评海报,书评书摘的接口与标签接口
This commit is contained in:
@@ -19,6 +19,20 @@ class BookDao {
|
||||
return List.generate(maps.length, (i) => Book.fromJson(maps[i]));
|
||||
}
|
||||
|
||||
// 分页查询书籍记录
|
||||
Future<List<Book>> getBooksPaged({String? status, int limit = 20, int offset = 0}) async {
|
||||
final db = await _dbHelper.database;
|
||||
String where = 'is_deleted = 0';
|
||||
List<dynamic> whereArgs = [];
|
||||
if (status != null && status.isNotEmpty) {
|
||||
where += ' AND status = ?';
|
||||
whereArgs.add(status);
|
||||
}
|
||||
final maps = await db.query('books', where: where, whereArgs: whereArgs,
|
||||
orderBy: 'created_at DESC', limit: limit, offset: offset);
|
||||
return List.generate(maps.length, (i) => Book.fromJson(maps[i]));
|
||||
}
|
||||
|
||||
// 根据状态筛选书籍记录
|
||||
Future<List<Book>> getBooksByStatus(String status) async {
|
||||
final db = await _dbHelper.database;
|
||||
|
||||
@@ -19,6 +19,20 @@ class MovieDao {
|
||||
return List.generate(maps.length, (i) => Movie.fromJson(maps[i]));
|
||||
}
|
||||
|
||||
// 分页查询影视记录
|
||||
Future<List<Movie>> getMoviesPaged({String? status, int limit = 20, int offset = 0}) async {
|
||||
final db = await _dbHelper.database;
|
||||
String where = 'is_deleted = 0';
|
||||
List<dynamic> whereArgs = [];
|
||||
if (status != null && status.isNotEmpty) {
|
||||
where += ' AND status = ?';
|
||||
whereArgs.add(status);
|
||||
}
|
||||
final maps = await db.query('movies', where: where, whereArgs: whereArgs,
|
||||
orderBy: 'created_at DESC', limit: limit, offset: offset);
|
||||
return List.generate(maps.length, (i) => Movie.fromJson(maps[i]));
|
||||
}
|
||||
|
||||
// 根据状态筛选影视记录
|
||||
Future<List<Movie>> getMoviesByStatus(String status) async {
|
||||
final db = await _dbHelper.database;
|
||||
|
||||
@@ -19,6 +19,14 @@ class NoteDao {
|
||||
return List.generate(maps.length, (i) => Note.fromJson(maps[i]));
|
||||
}
|
||||
|
||||
// 分页查询笔记
|
||||
Future<List<Note>> getNotesPaged({int limit = 20, int offset = 0}) async {
|
||||
final db = await _dbHelper.database;
|
||||
final maps = await db.query('notes', where: 'is_deleted = 0',
|
||||
orderBy: 'created_at DESC', limit: limit, offset: offset);
|
||||
return List.generate(maps.length, (i) => Note.fromJson(maps[i]));
|
||||
}
|
||||
|
||||
// 根据ID获取笔记
|
||||
Future<Note?> getNoteById(String id) async {
|
||||
final db = await _dbHelper.database;
|
||||
|
||||
@@ -26,19 +26,31 @@ class ServerDataService {
|
||||
bool get isAvailable => _baseUrl.isNotEmpty && _code.isNotEmpty;
|
||||
|
||||
Future<dynamic> _post(String path, [Map<String, dynamic>? extra]) async {
|
||||
final resp = await http.post(
|
||||
Uri.parse('$_baseUrl$path'),
|
||||
headers: _headers,
|
||||
body: jsonEncode(_body(extra)),
|
||||
).timeout(const Duration(seconds: 30));
|
||||
if (resp.statusCode != 200) return null;
|
||||
return jsonDecode(resp.body);
|
||||
try {
|
||||
final url = '$_baseUrl$path';
|
||||
debugPrint('[ServerData] POST $url');
|
||||
final resp = await http.post(
|
||||
Uri.parse(url),
|
||||
headers: _headers,
|
||||
body: jsonEncode(_body(extra)),
|
||||
).timeout(const Duration(seconds: 30));
|
||||
debugPrint('[ServerData] ${resp.statusCode} $path');
|
||||
if (resp.statusCode != 200) return null;
|
||||
return jsonDecode(resp.body);
|
||||
} catch (e) {
|
||||
debugPrint('[ServerData] ERROR $path: $e');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 影视 ────────────────────────────────────────────────────
|
||||
|
||||
Future<List<Movie>> getMovies() async {
|
||||
final data = await _post('/api/data/movies');
|
||||
Future<List<Movie>> getMovies({String? status, int? limit, int? offset}) async {
|
||||
final body = <String, dynamic>{};
|
||||
if (status != null && status.isNotEmpty) body['status'] = status;
|
||||
if (limit != null) body['limit'] = limit;
|
||||
if (offset != null) body['offset'] = offset;
|
||||
final data = await _post('/api/data/movies', body.isEmpty ? null : body);
|
||||
if (data == null || data['movies'] == null) return [];
|
||||
return (data['movies'] as List).map((m) => Movie.fromJson(m as Map<String, dynamic>)).toList();
|
||||
}
|
||||
@@ -55,8 +67,12 @@ class ServerDataService {
|
||||
|
||||
// ─── 书籍 ────────────────────────────────────────────────────
|
||||
|
||||
Future<List<Book>> getBooks() async {
|
||||
final data = await _post('/api/data/books');
|
||||
Future<List<Book>> getBooks({String? status, int? limit, int? offset}) async {
|
||||
final body = <String, dynamic>{};
|
||||
if (status != null && status.isNotEmpty) body['status'] = status;
|
||||
if (limit != null) body['limit'] = limit;
|
||||
if (offset != null) body['offset'] = offset;
|
||||
final data = await _post('/api/data/books', body.isEmpty ? null : body);
|
||||
if (data == null || data['books'] == null) return [];
|
||||
return (data['books'] as List).map((b) => Book.fromJson(b as Map<String, dynamic>)).toList();
|
||||
}
|
||||
@@ -73,8 +89,11 @@ class ServerDataService {
|
||||
|
||||
// ─── 笔记 ────────────────────────────────────────────────────
|
||||
|
||||
Future<List<Note>> getNotes() async {
|
||||
final data = await _post('/api/data/notes');
|
||||
Future<List<Note>> getNotes({int? limit, int? offset}) async {
|
||||
final body = <String, dynamic>{};
|
||||
if (limit != null) body['limit'] = limit;
|
||||
if (offset != null) body['offset'] = offset;
|
||||
final data = await _post('/api/data/notes', body.isEmpty ? null : body);
|
||||
if (data == null || data['notes'] == null) return [];
|
||||
return (data['notes'] as List).map((n) => Note.fromJson(n as Map<String, dynamic>)).toList();
|
||||
}
|
||||
@@ -89,6 +108,29 @@ class ServerDataService {
|
||||
return data != null;
|
||||
}
|
||||
|
||||
// ─── 批量同步 ────────────────────────────────────────────────
|
||||
|
||||
Future<Map<String, int>> batchSync({
|
||||
List<Movie>? movies,
|
||||
List<Book>? books,
|
||||
List<Note>? notes,
|
||||
List<Map<String, dynamic>>? tags,
|
||||
}) async {
|
||||
final data = await _post('/api/data/batch_sync', {
|
||||
if (movies != null) 'movies': movies.map((m) => m.toJson()).toList(),
|
||||
if (books != null) 'books': books.map((b) => b.toJson()).toList(),
|
||||
if (notes != null) 'notes': notes.map((n) => n.toJson()).toList(),
|
||||
if (tags != null) 'tags': tags,
|
||||
});
|
||||
if (data == null) return {};
|
||||
return {
|
||||
'movies': (data['movies'] as int?) ?? 0,
|
||||
'books': (data['books'] as int?) ?? 0,
|
||||
'notes': (data['notes'] as int?) ?? 0,
|
||||
'tags': (data['tags'] as int?) ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ─── 标签 ────────────────────────────────────────────────────
|
||||
|
||||
Future<List<Map<String, dynamic>>> getTags(String? type) async {
|
||||
|
||||
@@ -2,16 +2,21 @@ import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
import '../user_prefs.dart';
|
||||
import '../database_helper.dart';
|
||||
import '../../models/data_models.dart';
|
||||
import '../movie/movie_dao.dart';
|
||||
import '../book/book_dao.dart';
|
||||
import '../note/note_dao.dart';
|
||||
import 'server_data_service.dart';
|
||||
|
||||
/// 服务端实时同步服务
|
||||
/// - 开启时:上传一次本地数据到服务器,后续 CRUD 走 API
|
||||
/// - 关闭时:从服务器下载数据到本地,切换本地数据库
|
||||
/// - 开启时:智能合并本地与服务端数据
|
||||
/// - 关闭时:从服务器下载数据到本地
|
||||
class ServerSyncService {
|
||||
static final ServerSyncService instance = ServerSyncService._();
|
||||
ServerSyncService._();
|
||||
@@ -46,59 +51,131 @@ class ServerSyncService {
|
||||
try { final d = jsonDecode(s); return d is Map<String, dynamic> ? d : null; } catch (_) { return null; }
|
||||
}
|
||||
|
||||
/// 开启同步:上传本地数据到服务器
|
||||
Future<bool> uploadToServer() async {
|
||||
/// 开启同步:智能合并本地与服务端数据
|
||||
Future<bool> syncWithServer() async {
|
||||
if (!isConfigured || _isSyncing) return false;
|
||||
_isSyncing = true;
|
||||
try {
|
||||
final url = _prefs.syncServerUrl;
|
||||
final code = _prefs.syncActivationCode;
|
||||
final deviceId = _prefs.deviceId;
|
||||
final server = ServerDataService.instance;
|
||||
|
||||
final dbPath = await DatabaseHelper.instance.databasePath;
|
||||
if (dbPath == null || !File(dbPath).existsSync()) {
|
||||
debugPrint('[Sync] 数据库文件不存在');
|
||||
return false;
|
||||
}
|
||||
// 读取本地数据
|
||||
final localMovies = await MovieDao().getAllMovies();
|
||||
final localBooks = await BookDao().getAllBooks();
|
||||
final localNotes = await NoteDao().getAllNotes();
|
||||
|
||||
final request = http.MultipartRequest('POST', Uri.parse('$url/api/sync/upload'));
|
||||
request.fields['code'] = code;
|
||||
request.fields['device_id'] = deviceId;
|
||||
request.files.add(await http.MultipartFile.fromPath('database', dbPath));
|
||||
// 读取服务端数据
|
||||
final remoteMovies = await server.getMovies();
|
||||
final remoteBooks = await server.getBooks();
|
||||
final remoteNotes = await server.getNotes();
|
||||
|
||||
final appDir = await getApplicationDocumentsDirectory();
|
||||
final imgDir = Directory(p.join(appDir.path, 'images'));
|
||||
if (await imgDir.exists()) {
|
||||
await for (final entity in imgDir.list(recursive: true)) {
|
||||
if (entity is File) {
|
||||
final relPath = p.relative(entity.path, from: appDir.path).replaceAll('\\', '/');
|
||||
request.files.add(await http.MultipartFile('images', entity.readAsBytes().asStream(), await entity.length(), filename: relPath));
|
||||
// 需要 push 到服务端的数据
|
||||
final pushMovies = <Movie>[];
|
||||
final pushBooks = <Book>[];
|
||||
final pushNotes = <Note>[];
|
||||
final imagePaths = <String>[];
|
||||
|
||||
// 服务端无数据 → 全量 push
|
||||
if (remoteMovies.isEmpty && remoteBooks.isEmpty && remoteNotes.isEmpty) {
|
||||
pushMovies.addAll(localMovies);
|
||||
pushBooks.addAll(localBooks);
|
||||
pushNotes.addAll(localNotes);
|
||||
} else {
|
||||
// 按 updated_at 合并
|
||||
final remoteMovieMap = {for (final m in remoteMovies) m.id: m};
|
||||
for (final m in localMovies) {
|
||||
final r = remoteMovieMap.remove(m.id);
|
||||
if (r == null || m.updatedAt.isAfter(r.updatedAt)) {
|
||||
pushMovies.add(m);
|
||||
} else {
|
||||
await _upsertLocalMovie(m: r);
|
||||
}
|
||||
}
|
||||
for (final r in remoteMovieMap.values) {
|
||||
await _upsertLocalMovie(m: r);
|
||||
}
|
||||
|
||||
final remoteBookMap = {for (final b in remoteBooks) b.id: b};
|
||||
for (final b in localBooks) {
|
||||
final r = remoteBookMap.remove(b.id);
|
||||
if (r == null || b.updatedAt.isAfter(r.updatedAt)) {
|
||||
pushBooks.add(b);
|
||||
} else {
|
||||
await _upsertLocalBook(b: r);
|
||||
}
|
||||
}
|
||||
for (final r in remoteBookMap.values) {
|
||||
await _upsertLocalBook(b: r);
|
||||
}
|
||||
|
||||
final remoteNoteMap = {for (final n in remoteNotes) n.id: n};
|
||||
for (final n in localNotes) {
|
||||
final r = remoteNoteMap.remove(n.id);
|
||||
if (r == null || n.updatedAt.isAfter(r.updatedAt)) {
|
||||
pushNotes.add(n);
|
||||
} else {
|
||||
await _upsertLocalNote(n: r);
|
||||
}
|
||||
}
|
||||
for (final r in remoteNoteMap.values) {
|
||||
await _upsertLocalNote(n: r);
|
||||
}
|
||||
}
|
||||
|
||||
final avatarsDir = Directory(p.join(appDir.path, 'avatars'));
|
||||
if (await avatarsDir.exists()) {
|
||||
await for (final entity in avatarsDir.list()) {
|
||||
if (entity is File) {
|
||||
final relPath = p.relative(entity.path, from: appDir.path).replaceAll('\\', '/');
|
||||
request.files.add(await http.MultipartFile('images', entity.readAsBytes().asStream(), await entity.length(), filename: relPath));
|
||||
}
|
||||
// 批量 push 到服务端
|
||||
if (pushMovies.isNotEmpty || pushBooks.isNotEmpty || pushNotes.isNotEmpty) {
|
||||
final db = await DatabaseHelper.instance.database;
|
||||
final localTags = await db.query('tags');
|
||||
final result = await server.batchSync(
|
||||
movies: pushMovies.isEmpty ? null : pushMovies,
|
||||
books: pushBooks.isEmpty ? null : pushBooks,
|
||||
notes: pushNotes.isEmpty ? null : pushNotes,
|
||||
tags: localTags.isEmpty ? null : localTags.cast<Map<String, dynamic>>(),
|
||||
);
|
||||
debugPrint('[Sync] 批量推送: $result');
|
||||
|
||||
// 收集需要上传的图片
|
||||
for (final m in pushMovies) {
|
||||
if (m.posterPath != null && m.posterPath!.isNotEmpty) imagePaths.add(m.posterPath!);
|
||||
}
|
||||
for (final b in pushBooks) {
|
||||
if (b.coverPath != null && b.coverPath!.isNotEmpty) imagePaths.add(b.coverPath!);
|
||||
}
|
||||
for (final n in pushNotes) {
|
||||
imagePaths.addAll(n.images.where((i) => i.isNotEmpty));
|
||||
}
|
||||
}
|
||||
|
||||
final resp = await request.send().timeout(const Duration(seconds: 300));
|
||||
if (resp.statusCode == 200) {
|
||||
debugPrint('[Sync] 上传成功');
|
||||
return true;
|
||||
// 上传图片
|
||||
if (imagePaths.isNotEmpty) {
|
||||
debugPrint('[Sync] 上传 ${imagePaths.length} 张图片');
|
||||
await ServerDataService.uploadLocalImages(imagePaths);
|
||||
}
|
||||
debugPrint('[Sync] 上传失败 HTTP ${resp.statusCode}');
|
||||
|
||||
debugPrint('[Sync] 合并完成');
|
||||
return true;
|
||||
} catch (e) {
|
||||
debugPrint('[Sync] 上传异常: $e');
|
||||
debugPrint('[Sync] 合并异常: $e');
|
||||
return false;
|
||||
} finally {
|
||||
_isSyncing = false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ─── 合并辅助方法 ────────────────────────────────────────────
|
||||
|
||||
Future<void> _upsertLocalMovie({required Movie m}) async {
|
||||
final db = await DatabaseHelper.instance.database;
|
||||
await db.insert('movies', m.toJson(), conflictAlgorithm: ConflictAlgorithm.replace);
|
||||
}
|
||||
|
||||
Future<void> _upsertLocalBook({required Book b}) async {
|
||||
final db = await DatabaseHelper.instance.database;
|
||||
await db.insert('books', b.toJson(), conflictAlgorithm: ConflictAlgorithm.replace);
|
||||
}
|
||||
|
||||
Future<void> _upsertLocalNote({required Note n}) async {
|
||||
final db = await DatabaseHelper.instance.database;
|
||||
await db.insert('notes', n.toJson(), conflictAlgorithm: ConflictAlgorithm.replace);
|
||||
}
|
||||
|
||||
/// 关闭同步:从服务器下载数据到本地
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'dart:convert';
|
||||
import 'dart:io' show Platform;
|
||||
import 'dart:math';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'user_prefs.dart';
|
||||
|
||||
@@ -16,9 +17,10 @@ class UsageStatsService with WidgetsBindingObserver {
|
||||
|
||||
final UserPrefs _prefs = UserPrefs();
|
||||
|
||||
/// 统计服务器地址,发布前替换为实际地址,置空则禁用
|
||||
static String serverUrl = 'http://api.mooknote.iletter.top/';
|
||||
// static String serverUrl = 'http://192.168.31.48:27050/';
|
||||
/// 统计服务器地址,debug 走局域网,release 走线上
|
||||
static String serverUrl = kDebugMode
|
||||
? 'http://192.168.31.48:27047/'
|
||||
: 'http://api.mooknote.iletter.top/';
|
||||
Timer? _heartbeatTimer;
|
||||
bool _started = false;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user