backupsFileManager.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. //
  2. // backupsFileManager.m
  3. // 隐私保护
  4. //
  5. // Created by xd h on 2024/1/3.
  6. //
  7. #import "backupsFileManager.h"
  8. #import "cachesFileManager.h"
  9. #import "connectDeviceManager.h"
  10. #import "AFNetworkReachabilityManager.h"
  11. @interface backupsFileManager ()
  12. /**检测任务10s后 无反馈重新开始 */
  13. @property (nonatomic, assign) NSInteger taskRenewTime; //
  14. @property (nonatomic,strong)photosBackupsTaskModel *lastModel;//最后一次备份的数据
  15. @end
  16. @implementation backupsFileManager
  17. static backupsFileManager * cur_backupsFileShareInstance = nil;
  18. +(backupsFileManager *)shareInstance;
  19. {
  20. static dispatch_once_t onceToken;
  21. dispatch_once(&onceToken, ^{
  22. cur_backupsFileShareInstance = [[backupsFileManager alloc] init];
  23. });
  24. return cur_backupsFileShareInstance;
  25. }
  26. - (id)init
  27. {
  28. self = [super init];
  29. if (self) {
  30. //[self initManager];
  31. }
  32. return self;
  33. }
  34. - (void)AutohandlePhotosBackupsFun
  35. {
  36. NSString *curSdnId = [connectDeviceManager shareInstance].DeviceThirdIdMod.data.sdnId;
  37. if(!_sdnId || ![curSdnId isEqualToString:_sdnId])
  38. {//没有备份过 或者更换设备了
  39. [self handlePhotosBackupsFun];
  40. }
  41. else{
  42. [self checkReBackupsFileFun];
  43. }
  44. }
  45. - (void)handlePhotosBackupsFun
  46. {
  47. BOOL haveOpenBackups = [HWDataManager getBoolWithKey:stringKeyAddSn(Const_photo_backups_state)];
  48. if(!haveOpenBackups){
  49. return;
  50. }
  51. if(ksharedAppDelegate.DisabledFileTransferType){
  52. return;
  53. }
  54. //相册权限
  55. if (![[TZImageManager manager] authorizationStatusAuthorized]){
  56. [HWDataManager setBoolWithKey:Const_photo_backups_state value:NO];
  57. return;
  58. }
  59. NSString *curSdnId = [connectDeviceManager shareInstance].DeviceThirdIdMod.data.sdnId;
  60. _sdnId = curSdnId;
  61. [photosBackupsTaskModel bg_findAsync:backups_photos_tableName limit:0 orderBy:nil desc:YES complete:^(NSArray * _Nullable array) {
  62. if(!array || array.count == 0){
  63. [self getAllAlbumsFun];
  64. return;
  65. }
  66. if(array.count >1){
  67. [self keepDatabaseOneDataFun];
  68. }
  69. self->_lastModel = array.firstObject;
  70. HLog(@"1 bg_id:%@",self->_lastModel.bg_id);
  71. if(self->_lastModel.isBackupsSuspendType == backupsSuspendByUser){
  72. return;
  73. }
  74. if(self->_lastModel.curBackupsState == backupsStateFail
  75. ||self->_lastModel.curBackupsState == backupsStateDone){//上次备份完成
  76. [self getAllAlbumsFun];
  77. }
  78. else{//继续上次的备份任务
  79. [self handelBackupsModelFun:self->_lastModel];
  80. }
  81. }];
  82. }
  83. - (void)keepDatabaseOneDataFun
  84. {
  85. [photosBackupsTaskModel bg_deleteFirstObject:backups_photos_tableName];
  86. //[photosBackupsTaskModel bg_findAsync:backups_photos_tableName
  87. }
  88. //备份开始查询相册
  89. - (void)getAllAlbumsFun
  90. {
  91. //
  92. KWeakSelf
  93. [[TZImageManager manager] getAllAlbums:YES allowPickingImage:YES needFetchAssets:NO completion:^(NSArray<TZAlbumModel *> *models) {
  94. if(models.count >= 1){
  95. TZAlbumModel *curAlbumModel= models.firstObject;
  96. photosBackupsTaskModel * taskModel = [photosBackupsTaskModel new];
  97. //taskModel.count = curAlbumModel.count;
  98. //taskModel.result = curAlbumModel.result;
  99. taskModel.failCount = 0;
  100. taskModel.didBackupsCount = 0;
  101. taskModel.bg_tableName = backups_photos_tableName;
  102. NSMutableString *allLocalIdentifier= [NSMutableString new];
  103. for (PHAsset *asset in curAlbumModel.result) {
  104. if (asset.localIdentifier) {
  105. if(allLocalIdentifier.length >0){
  106. [allLocalIdentifier appendString:@"&"];
  107. }
  108. [allLocalIdentifier appendString:asset.localIdentifier];
  109. }
  110. }
  111. taskModel.totalLocalIdentifier = allLocalIdentifier;
  112. if(self->_lastModel && self->_lastModel.totalLocalIdentifier){//相册备份排重
  113. taskModel.curTaskLocalIdentifier = [weakSelf AlbumBackupsHandleNew:taskModel];
  114. }
  115. else{
  116. taskModel.curTaskLocalIdentifier = allLocalIdentifier;
  117. }
  118. taskModel.count = [taskModel.curTaskLocalIdentifier componentsSeparatedByString:@"&"].count;
  119. HLog(@"2 bg_id:%@",taskModel.bg_id);
  120. [taskModel bg_saveAsync:^(BOOL isSuccess) {
  121. if(!isSuccess){
  122. HLog(@"\n\nError!!!\n\n");
  123. }
  124. else{
  125. //[self handelBackupsModelFun:taskModel];
  126. [self handlePhotosBackupsFun];
  127. }
  128. }];
  129. }
  130. }];
  131. }
  132. - (NSString*)AlbumBackupsHandleNew:(photosBackupsTaskModel * )taskModel
  133. {
  134. NSArray* curLocalIdentifierArr = [taskModel.totalLocalIdentifier componentsSeparatedByString:@"&"];
  135. NSArray* preLocalIdentifierArr = [_lastModel.totalLocalIdentifier componentsSeparatedByString:@"&"];
  136. NSMutableArray *allArr = [NSMutableArray arrayWithArray:curLocalIdentifierArr];
  137. for (NSString*localIdentifier in preLocalIdentifierArr) {
  138. for (NSString* newlocalIdentifier in allArr) {
  139. if([localIdentifier isEqualToString:newlocalIdentifier]){
  140. [allArr removeObject:newlocalIdentifier];
  141. break;
  142. }
  143. }
  144. }
  145. NSMutableString *allLocalIdentifier= [NSMutableString new];
  146. for (NSString* newlocalIdentifier in allArr) {
  147. if(allLocalIdentifier.length >0){
  148. [allLocalIdentifier appendString:@"&"];
  149. }
  150. [allLocalIdentifier appendString:newlocalIdentifier];
  151. }
  152. return allLocalIdentifier;
  153. }
  154. - (void)handelBackupsModelFun:(photosBackupsTaskModel*)backupsTaskModel
  155. {
  156. _curPhotosBackupsTaskMod = backupsTaskModel;
  157. _curPhotosBackupsTaskMod.isBackupsSuspendType = backupsSuspendNone;
  158. _curPhotosBackupsTaskMod.curBackupsState = backupsStateUploading;
  159. _curPhotosBackupsTaskMod.LocalIdentifierArr = [backupsTaskModel.curTaskLocalIdentifier componentsSeparatedByString:@"&"];
  160. if(_curPhotosBackupsTaskMod.LocalIdentifierArr.count == 0){
  161. _curPhotosBackupsTaskMod.didBackupsCount = 0;
  162. _curPhotosBackupsTaskMod.curBackupsState = backupsStateDone;
  163. [self RefreshDatabaseFun];
  164. [self changeBackupsFileStateFun];
  165. return;
  166. }
  167. if(_curPhotosBackupsTaskMod.LocalIdentifierArr.count
  168. <= (_curPhotosBackupsTaskMod.didBackupsCount + _curPhotosBackupsTaskMod.failCount))
  169. {
  170. _curPhotosBackupsTaskMod.curBackupsState = backupsStateDone;
  171. [self RefreshDatabaseFun];
  172. [self changeBackupsFileStateFun];
  173. return;
  174. }
  175. [self beginBackupsFileFun];
  176. }
  177. - (void)beginBackupsFileFun
  178. {
  179. BOOL isCanUseCellular = [HWDataManager getBoolWithKey:stringKeyAddSn(Const_file_Transfe_canUse_Cellular_all)];
  180. if(!isCanUseCellular){//不允许流量上传
  181. //
  182. if([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN){
  183. return;
  184. }
  185. }
  186. self.taskRenewTime = [iTools getNowTimeStamp];
  187. NSInteger index = _curPhotosBackupsTaskMod.didBackupsCount + _curPhotosBackupsTaskMod.failCount;
  188. if(!_curPhotosBackupsTaskMod.LocalIdentifierArr){
  189. _curPhotosBackupsTaskMod.LocalIdentifierArr = [_curPhotosBackupsTaskMod.curTaskLocalIdentifier componentsSeparatedByString:@"&"];
  190. }
  191. if(index >= _curPhotosBackupsTaskMod.LocalIdentifierArr.count){
  192. _curPhotosBackupsTaskMod.curBackupsState = backupsStateDone;
  193. [self RefreshDatabaseFun];
  194. [self changeBackupsFileStateFun];
  195. _curPhotosBackupsTaskMod = nil;
  196. return;
  197. }
  198. NSString *curLocalIdentifier = _curPhotosBackupsTaskMod.LocalIdentifierArr[index];
  199. if(!curLocalIdentifier || curLocalIdentifier.length == 0)
  200. {
  201. [self getDataWrongToChangeFailFun];
  202. return;
  203. }
  204. PHFetchResult *fetchResult = [PHAsset fetchAssetsWithLocalIdentifiers:@[curLocalIdentifier] options:nil];
  205. PHAsset *curAsset = fetchResult.firstObject;
  206. NSString *fileName = [curAsset valueForKey:@"filename"];;
  207. if(!fileName){
  208. [self getDataWrongToChangeFailFun];
  209. return;
  210. }
  211. _curPhotosBackupsTaskMod.filename = fileName;
  212. KWeakSelf
  213. if(curAsset.mediaType == PHAssetMediaTypeImage){
  214. _curPhotosBackupsTaskMod.curUploadFileType = uploadFileTypeImage;
  215. [[PHImageManager defaultManager] requestImageDataForAsset:curAsset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
  216. // 直接得到最终的 NSData 数据
  217. if (imageData) {
  218. [weakSelf afterGetImageDataFun:imageData];
  219. }
  220. else{
  221. [weakSelf getDataWrongToChangeFailFun];
  222. }
  223. }];
  224. }
  225. else{
  226. _curPhotosBackupsTaskMod.curUploadFileType = uploadFileTypeVideo;
  227. //判断文件是否在app内
  228. BOOL didSaveFile = [cachesFileManager checkFileIsSaveState:_curPhotosBackupsTaskMod.filename withType:uploadFileTypeVideo];
  229. if(didSaveFile){
  230. [self afterGetVideoDataFun];
  231. return;
  232. }
  233. //真正的视频数据
  234. PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
  235. options.version = PHVideoRequestOptionsVersionOriginal;
  236. [[PHImageManager defaultManager] requestAVAssetForVideo:curAsset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
  237. if ([asset isKindOfClass:[AVURLAsset class]]) {
  238. AVURLAsset* urlAsset = (AVURLAsset*)asset;
  239. BOOL isSuc = [cachesFileManager copyVideoItemAtPath:[urlAsset.URL path] fileName:self->_curPhotosBackupsTaskMod.filename error:nil];
  240. if (isSuc) {
  241. [weakSelf afterGetVideoDataFun];
  242. }
  243. else{
  244. [weakSelf getDataWrongToChangeFailFun];
  245. }
  246. }
  247. else{
  248. [weakSelf getDataWrongToChangeFailFun];
  249. }
  250. }];
  251. }
  252. }
  253. - (void)getDataWrongToChangeFailFun
  254. {
  255. [self deleteVideoFun];
  256. _curPhotosBackupsTaskMod.failCount += 1;
  257. [self RefreshDatabaseFun];
  258. if(_curPhotosBackupsTaskMod.curBackupsState == backupsStateSuspend){
  259. return;
  260. }
  261. [self beginBackupsFileFun];
  262. }
  263. - (void)changeBackupsFileStateToFailWith:(NSString*)errorStr
  264. {
  265. [self deleteVideoFun];
  266. _curPhotosBackupsTaskMod.curBackupsState = backupsStateFail;
  267. _curPhotosBackupsTaskMod.backupsTipMsg = errorStr;
  268. [self RefreshDatabaseFun];
  269. [self changeBackupsFileStateFun];
  270. }
  271. - (void)RefreshDatabaseFun
  272. {
  273. HLog(@"3 bg_id:%@",_curPhotosBackupsTaskMod.bg_id);
  274. [_curPhotosBackupsTaskMod bg_saveOrUpdateAsync:^(BOOL isSuccess) {
  275. if(isSuccess){
  276. }
  277. }];
  278. }
  279. - (void)afterGetImageDataFun:(NSData*)imageData
  280. {
  281. _curPhotosBackupsTaskMod.imageData = imageData;
  282. _curPhotosBackupsTaskMod.didUploadBytes = 0;
  283. _curPhotosBackupsTaskMod.totalBytes = [imageData length];
  284. [[NSNotificationCenter defaultCenter] postNotificationName:backupsFileBeginNotification object:_curPhotosBackupsTaskMod];
  285. }
  286. - (void)deleteVideoFun
  287. {
  288. if(_curPhotosBackupsTaskMod.curUploadFileType == uploadFileTypeVideo){
  289. [cachesFileManager removeItemAtPath:_curPhotosBackupsTaskMod.filename type:uploadFileTypeVideo error:nil];
  290. }
  291. }
  292. - (void)afterGetVideoDataFun
  293. {
  294. NSString *filePath = [cachesFileManager getFilePathWithName:_curPhotosBackupsTaskMod.filename type:uploadFileTypeVideo]; // 文件路径
  295. NSFileManager *manager0 = [NSFileManager defaultManager];
  296. if([manager0 fileExistsAtPath:filePath]) {
  297. NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath]; // 创建文件句柄
  298. if (fileHandle) {
  299. long long endOfFile = [fileHandle seekToEndOfFile];
  300. _curPhotosBackupsTaskMod.didUploadBytes = 0;
  301. _curPhotosBackupsTaskMod.totalBytes = endOfFile;
  302. [fileHandle closeFile];
  303. }
  304. }
  305. [[NSNotificationCenter defaultCenter] postNotificationName:backupsFileBeginNotification object:_curPhotosBackupsTaskMod];
  306. }
  307. - (void)backupsFileDoneFun
  308. {
  309. [self deleteVideoFun];
  310. _curPhotosBackupsTaskMod.didBackupsCount += 1;
  311. // if(!_curPhotosBackupsTaskMod.didBackupsOneFileType)
  312. // {
  313. // _curPhotosBackupsTaskMod.curTaskBackupsCount += 1;
  314. // }
  315. [self RefreshDatabaseFun];
  316. [self changeBackupsFileStateFun];
  317. if(_curPhotosBackupsTaskMod.curBackupsState == backupsStateSuspend){
  318. return;
  319. }
  320. [self beginBackupsFileFun];
  321. }
  322. //修改文件上传的状态
  323. - (void)changeBackupsFileStateFun
  324. {
  325. self.taskRenewTime = [iTools getNowTimeStamp];
  326. [[NSNotificationCenter defaultCenter] postNotificationName:backupsFileRefreshNotification object:_curPhotosBackupsTaskMod];
  327. }
  328. - (void)suspendBackupsFileFun
  329. {
  330. if(!_curPhotosBackupsTaskMod){
  331. return;
  332. }
  333. _curPhotosBackupsTaskMod.curBackupsState = backupsStateSuspend;
  334. _curPhotosBackupsTaskMod.backupsTipMsg = NSLocalizedString(@"File_backups_Record_tip_Suspend",nil);
  335. [_curPhotosBackupsTaskMod bg_saveOrUpdateAsync:^(BOOL isSuccess) {
  336. if(isSuccess){
  337. [self changeBackupsFileStateFun];
  338. }
  339. }];
  340. }
  341. //文件重新备份
  342. - (void)reBackupsFileFunBy:(photosBackupsTaskModel*)model
  343. {
  344. model.isBackupsSuspendType = backupsSuspendNone;
  345. model.curBackupsState = backupsStateUploading;
  346. _curPhotosBackupsTaskMod = model;
  347. [self RefreshDatabaseFun];
  348. [self changeBackupsFileStateFun];
  349. [self beginBackupsFileFun];
  350. // [_curPhotosBackupsTaskMod bg_saveOrUpdateAsync:^(BOOL isSuccess) {
  351. // if(isSuccess){
  352. // [self beginBackupsFileFun];
  353. // }
  354. // }];
  355. }
  356. //检查是否需要重新备份
  357. - (void)checkReBackupsFileFun
  358. {
  359. if(!_curPhotosBackupsTaskMod){
  360. return;
  361. }
  362. if(_curPhotosBackupsTaskMod.curBackupsState != backupsStateUploading){
  363. return;
  364. }
  365. NSInteger curTime = [iTools getNowTimeStamp];
  366. if(self.taskRenewTime == 0){
  367. return;
  368. }
  369. if(curTime - self.taskRenewTime < 10){
  370. return;
  371. }
  372. [self beginBackupsFileFun];
  373. }
  374. //检查是否在备份中
  375. - (BOOL)checkBackupsingFun{
  376. if(!_curPhotosBackupsTaskMod){
  377. return NO;
  378. }
  379. if(_curPhotosBackupsTaskMod.curBackupsState == backupsStateSuspend){
  380. return NO;
  381. }
  382. return YES;
  383. }
  384. @end