privacy_controller.dart 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. import 'dart:ffi';
  2. import 'dart:math';
  3. import 'package:clean/base/base_controller.dart';
  4. import 'package:clean/model/asset_info.dart';
  5. import 'package:clean/module/privacy/privacy_state.dart';
  6. import 'package:clean/utils/expand.dart';
  7. import 'package:clean/utils/file_utils.dart';
  8. import 'package:clean/utils/image_util.dart';
  9. import 'package:clean/utils/mmkv_util.dart';
  10. import 'package:flutter/Material.dart';
  11. import 'package:flutter/cupertino.dart';
  12. import 'package:flutter_screenutil/flutter_screenutil.dart';
  13. import 'package:get/get.dart';
  14. import 'package:permission_handler/permission_handler.dart';
  15. import 'package:wechat_assets_picker/wechat_assets_picker.dart';
  16. import 'package:wechat_camera_picker/wechat_camera_picker.dart';
  17. import '../../dialog/photo_uploading_dialog.dart';
  18. import '../../utils/toast_util.dart';
  19. import '../image_picker/image_picker_assets.dart';
  20. import 'package:intl/intl.dart';
  21. import 'dart:typed_data';
  22. import 'dart:io';
  23. class PrivacyController extends BaseController {
  24. final String isExistPasswd = "PRIVACY_EXIST_PASSWD";
  25. final String isPublic = "PRIVACY_PUBLIC";
  26. final String privacyPasswd = "PRIVACY_PASSWD";
  27. // 是否存在密码
  28. RxBool isPrivacyExistPasswd = false.obs;
  29. // 是否公开
  30. RxBool isPrivacyPublic = false.obs;
  31. RxBool isConfirm = false.obs;
  32. // 是否为编辑状态
  33. RxBool isEdit = false.obs;
  34. // 是否在重置密码
  35. bool isReset = false;
  36. // 设置密码标题
  37. RxString passwordTitle = "Input password".obs;
  38. // 密码
  39. late var passwordStr = "".obs;
  40. late var newPasswordStr = "";
  41. // 是否为解锁状态
  42. late var isUnlock = false.obs;
  43. // 使用共享状态
  44. RxList<AssetInfo>imageList = PrivacyState.imageList;
  45. RxMap<String, List<AssetInfo>> assetsByMonth = PrivacyState.assetsByMonth;
  46. // 获取月份数量
  47. int get monthCount => assetsByMonth.length;
  48. // 获取总图片数量
  49. int get totalAssetCount =>
  50. assetsByMonth.values.fold(0, (sum, list) => sum + list.length);
  51. // 存储选中的图片ID
  52. final RxSet<String> selectedAssets = <String>{}.obs;
  53. // 是否全选
  54. RxBool isAllSelected = false.obs;
  55. // 选中图片的总容量(字节)
  56. final RxInt selectedTotalSize = 0.obs;
  57. @override
  58. void onInit() {
  59. // TODO: implement onInit
  60. super.onInit();
  61. isPrivacyExistPasswd.value = KVUtil.getBool(isExistPasswd, false);
  62. isPrivacyPublic.value = KVUtil.getBool(isPublic, false);
  63. isUnlock.value = isPrivacyPublic.value;
  64. if (isPrivacyExistPasswd.value) {
  65. passwordTitle.value = "Input password";
  66. } else {
  67. passwordTitle.value = "Create New Password";
  68. }
  69. loadAssets();
  70. }
  71. // 加载并分组图片
  72. Future<void> loadAssets() async {
  73. var newImageList = <AssetInfo>[];
  74. newImageList = await FileUtils.getAllAssets(FileType.privacy);
  75. PrivacyState.imageList.value = newImageList;
  76. PrivacyState.updateMonthlyAssets();
  77. if (newImageList.isEmpty) {
  78. isEdit.value = false;
  79. return;
  80. }
  81. // 清空现有数据
  82. assetsByMonth.clear();
  83. // 按月份分组
  84. for (var asset in newImageList) {
  85. final monthKey = ImageUtil.getMonthKey(asset.createDateTime);
  86. if (!assetsByMonth.containsKey(monthKey)) {
  87. assetsByMonth[monthKey] = [];
  88. }
  89. assetsByMonth[monthKey]!.add(asset);
  90. asset.dateTitle = ImageUtil.formatMonthKey(monthKey);
  91. }
  92. newImageList.sort((a, b) => b.createDateTime.compareTo(a.createDateTime));
  93. PrivacyState.imageList.value = newImageList;
  94. PrivacyState.updateMonthlyAssets();
  95. // 对每个月份内的图片按时间排序(新的在前)
  96. assetsByMonth.forEach((key, list) {
  97. list.sort((a, b) => b.createDateTime.compareTo(a.createDateTime));
  98. });
  99. // 打印分组结果
  100. assetsByMonth.forEach((key, assets) {
  101. print('${ImageUtil.formatMonthKey(key)}: ${assets.length} photos');
  102. });
  103. }
  104. // 处理输入密码逻辑
  105. void inputPassword(String num) {
  106. passwordStr.value = passwordStr.value + num;
  107. if (passwordStr.value.length == 4) {
  108. if (isReset) {
  109. // 二次输入密码的情况
  110. if (isConfirm.value) {
  111. // 输入错误
  112. if (passwordStr.value != newPasswordStr) {
  113. ToastUtil.show("Input Error");
  114. Future.delayed(const Duration(milliseconds: 100), () {
  115. passwordStr.value = "";
  116. });
  117. } else {
  118. isUnlock.value = true;
  119. KVUtil.putString(privacyPasswd, passwordStr.value);
  120. KVUtil.putBool(isExistPasswd, true);
  121. KVUtil.putBool(isPublic, false);
  122. isPrivacyExistPasswd.value = KVUtil.getBool(isExistPasswd, false);
  123. isPrivacyPublic.value = KVUtil.getBool(isPublic, false);
  124. isReset = false;
  125. passwordStr.value = "";
  126. }
  127. } else {
  128. // 第一次输入密码
  129. isConfirm.value = true;
  130. newPasswordStr = passwordStr.value;
  131. passwordTitle.value = "Confirm Password";
  132. Future.delayed(const Duration(milliseconds: 100), () {
  133. passwordStr.value = "";
  134. });
  135. }
  136. return;
  137. }
  138. }
  139. if (passwordStr.value.length == 4) {
  140. // 存在密码的情况
  141. if (isPrivacyExistPasswd.value) {
  142. String? password = KVUtil.getString(privacyPasswd, "");
  143. if (passwordStr.value == password) {
  144. isUnlock.value = true;
  145. passwordStr.value = "";
  146. } else {
  147. ToastUtil.show("Input Error");
  148. Future.delayed(const Duration(milliseconds: 100), () {
  149. passwordStr.value = "";
  150. });
  151. }
  152. } else {
  153. // 二次输入密码的情况
  154. if (isConfirm.value) {
  155. // 输入错误
  156. if (passwordStr.value != newPasswordStr) {
  157. ToastUtil.show("Input Error");
  158. Future.delayed(const Duration(milliseconds: 100), () {
  159. passwordStr.value = "";
  160. });
  161. } else {
  162. isUnlock.value = true;
  163. KVUtil.putString(privacyPasswd, passwordStr.value);
  164. KVUtil.putBool(isExistPasswd, true);
  165. KVUtil.putBool(isPublic, false);
  166. isPrivacyExistPasswd.value = KVUtil.getBool(isExistPasswd, false);
  167. isPrivacyPublic.value = KVUtil.getBool(isPublic, false);
  168. isReset = false;
  169. passwordStr.value = "";
  170. }
  171. } else {
  172. // 第一次输入密码
  173. isConfirm.value = true;
  174. newPasswordStr = passwordStr.value;
  175. passwordTitle.value = "Confirm Password";
  176. Future.delayed(const Duration(milliseconds: 100), () {
  177. passwordStr.value = "";
  178. });
  179. }
  180. return;
  181. }
  182. }
  183. }
  184. void dialogSetPassword() {
  185. // // 存在密码情况下
  186. // if (isPrivacyExistPasswd.value) {
  187. // isConfirm.value = false;
  188. // isUnlock.value = false;
  189. // passwordTitle.value = "Input password";
  190. // isReset = true;
  191. // } else {
  192. isConfirm.value = false;
  193. isUnlock.value = false;
  194. passwordTitle.value = "Create New Password";
  195. isReset = true;
  196. // }
  197. }
  198. // 设置公开状态
  199. void setPublic() {
  200. KVUtil.putString("", passwordStr.value);
  201. KVUtil.putBool(isExistPasswd, false);
  202. KVUtil.putBool(isPublic, true);
  203. isPrivacyExistPasswd.value = KVUtil.getBool(isExistPasswd, false);
  204. isPrivacyPublic.value = KVUtil.getBool(isPublic, false);
  205. }
  206. // 上传按钮点击
  207. void uploadBtnClick() {
  208. showCupertinoModalPopup(
  209. context: Get.context!,
  210. builder: (context) {
  211. return CupertinoActionSheet(
  212. actions: <Widget>[
  213. //操作按钮集合
  214. CupertinoActionSheetAction(
  215. onPressed: () {
  216. Navigator.pop(context);
  217. openGallery();
  218. },
  219. child: Text(
  220. 'Upload from Gallery',
  221. style: TextStyle(
  222. color: "#007AFF".color,
  223. fontWeight: FontWeight.w500,
  224. fontSize: 16.sp,
  225. ),
  226. ),
  227. ),
  228. CupertinoActionSheetAction(
  229. onPressed: () {
  230. Navigator.pop(context);
  231. openCamera();
  232. },
  233. child: Text(
  234. 'Take and Upload',
  235. style: TextStyle(
  236. color: "#007AFF".color,
  237. fontWeight: FontWeight.w500,
  238. fontSize: 16.sp,
  239. ),
  240. ),
  241. ),
  242. ],
  243. cancelButton: CupertinoActionSheetAction(
  244. //取消按钮
  245. onPressed: () {
  246. Navigator.pop(context);
  247. },
  248. child: Text(
  249. 'Cancel',
  250. style: TextStyle(
  251. color: "#007AFF".color,
  252. fontWeight: FontWeight.w500,
  253. fontSize: 16.sp,
  254. ),
  255. ),
  256. ),
  257. );
  258. },
  259. );
  260. }
  261. // 保存并刷新图片列表
  262. Future<void> saveAndRefreshAssets(List<AssetEntity> assets) async {
  263. for (var asset in assets) {
  264. await FileUtils.saveAsset(FileType.privacy, asset);
  265. }
  266. showDialog(
  267. context: Get.context!,
  268. barrierDismissible: false, // 防止点击外部关闭
  269. builder: (context) => UploadingDialog(
  270. duration: const Duration(seconds: 3),
  271. onComplete: () {
  272. loadAssets();
  273. ToastUtil.show("Successful");
  274. // 这里可以添加完成后的操作
  275. },
  276. ),
  277. );
  278. // 重新加载图片列表
  279. // loadAssets();
  280. }
  281. // 选择/取消选择图片
  282. void toggleSelectAsset(String assetId) {
  283. final asset = imageList.firstWhere((asset) => asset.id == assetId);
  284. if (selectedAssets.contains(assetId)) {
  285. selectedAssets.remove(assetId);
  286. if (asset.size != null) {
  287. selectedTotalSize.value -= asset.size!;
  288. }
  289. } else {
  290. selectedAssets.add(assetId);
  291. if (asset.size != null) {
  292. selectedTotalSize.value += asset.size!;
  293. }
  294. }
  295. // 更新全选状态
  296. isAllSelected.value = selectedAssets.length == imageList.length;
  297. }
  298. // 全选/取消全选
  299. void toggleSelectAll() {
  300. if (isAllSelected.value) {
  301. selectedAssets.clear();
  302. selectedTotalSize.value = 0;
  303. } else {
  304. selectedAssets.addAll(imageList.map((asset) => asset.id));
  305. selectedTotalSize.value = imageList.fold(
  306. 0, (sum, asset) => sum + (asset.size != null ? asset.size! : 0));
  307. }
  308. isAllSelected.value = !isAllSelected.value;
  309. }
  310. // 退出编辑模式时清空选择
  311. void exitEditMode() {
  312. isEdit.value = false;
  313. selectedAssets.clear();
  314. isAllSelected.value = false;
  315. selectedTotalSize.value = 0;
  316. }
  317. // 删除文件
  318. void deleteBtnClick() {
  319. // 获取要删除的资产
  320. final assetsToDelete = imageList.where(
  321. (asset) => selectedAssets.contains(asset.id)
  322. ).toList();
  323. for (var asset in assetsToDelete) {
  324. FileUtils.deleteAsset(FileType.privacy, asset.id.substring(0, 36));
  325. }
  326. selectedTotalSize.value = 0;
  327. loadAssets();
  328. }
  329. // 格式化文件大小显示
  330. String formatFileSize(int bytes) {
  331. if (bytes <= 0) return "Delete";
  332. final units = ['B', 'KB', 'MB', 'GB'];
  333. int digitGroups = (log(bytes) / log(1024)).floor();
  334. if (bytes == 0) {
  335. return "Delete";
  336. } else {
  337. return "Delete(${(bytes / pow(1024, digitGroups)).toStringAsFixed(
  338. 1)} ${units[digitGroups]})";
  339. }
  340. }
  341. // 开启图库
  342. Future<void> openGallery() async {
  343. var status = await Permission.photos.status;
  344. if (status == PermissionStatus.granted) {
  345. List<AssetEntity> assets = <AssetEntity>[];
  346. for (var asset in imageList) {
  347. var newAsset = await asset.toAssetEntity();
  348. if (newAsset != null) {
  349. assets.add(newAsset);
  350. }
  351. }
  352. List<AssetEntity>? pickList = await ImagePickAssets.pick();
  353. if (pickList != null && pickList.isNotEmpty) {
  354. await saveAndRefreshAssets(pickList);
  355. }
  356. } else {
  357. ToastUtil.show("请先开启权限");
  358. }
  359. }
  360. // 开启相机
  361. Future<void> openCamera() async {
  362. final entity = await CameraPicker.pickFromCamera(
  363. Get.context!,
  364. pickerConfig: const CameraPickerConfig(),
  365. );
  366. if (entity != null) {
  367. await saveAndRefreshAssets([entity]);
  368. }
  369. }
  370. }