backupsFileManager.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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. HLog(@"2 bg_id:%@",taskModel.bg_id);
  119. [taskModel bg_saveAsync:^(BOOL isSuccess) {
  120. if(!isSuccess){
  121. HLog(@"\n\nError!!!\n\n");
  122. }
  123. else{
  124. //[self handelBackupsModelFun:taskModel];
  125. [self handlePhotosBackupsFun];
  126. }
  127. }];
  128. }
  129. }];
  130. }
  131. - (NSString*)AlbumBackupsHandleNew:(photosBackupsTaskModel * )taskModel
  132. {
  133. NSArray* curLocalIdentifierArr = [taskModel.totalLocalIdentifier componentsSeparatedByString:@"&"];
  134. NSArray* preLocalIdentifierArr = [_lastModel.totalLocalIdentifier componentsSeparatedByString:@"&"];
  135. NSMutableArray *allArr = [NSMutableArray arrayWithArray:curLocalIdentifierArr];
  136. for (NSString*localIdentifier in preLocalIdentifierArr) {
  137. for (NSString* newlocalIdentifier in allArr) {
  138. if([localIdentifier isEqualToString:newlocalIdentifier]){
  139. [allArr removeObject:newlocalIdentifier];
  140. break;
  141. }
  142. }
  143. }
  144. NSMutableString *allLocalIdentifier= [NSMutableString new];
  145. for (NSString* newlocalIdentifier in allArr) {
  146. if(allLocalIdentifier.length >0){
  147. [allLocalIdentifier appendString:@"&"];
  148. }
  149. [allLocalIdentifier appendString:newlocalIdentifier];
  150. }
  151. return allLocalIdentifier;
  152. }
  153. - (void)handelBackupsModelFun:(photosBackupsTaskModel*)backupsTaskModel
  154. {
  155. _curPhotosBackupsTaskMod = backupsTaskModel;
  156. _curPhotosBackupsTaskMod.isBackupsSuspendType = backupsSuspendNone;
  157. _curPhotosBackupsTaskMod.curBackupsState = backupsStateUploading;
  158. _curPhotosBackupsTaskMod.LocalIdentifierArr = [backupsTaskModel.curTaskLocalIdentifier componentsSeparatedByString:@"&"];
  159. if(_curPhotosBackupsTaskMod.LocalIdentifierArr.count == 0){
  160. _curPhotosBackupsTaskMod.didBackupsCount = 0;
  161. _curPhotosBackupsTaskMod.curBackupsState = backupsStateDone;
  162. [self RefreshDatabaseFun];
  163. [self changeBackupsFileStateFun];
  164. return;
  165. }
  166. if(_curPhotosBackupsTaskMod.LocalIdentifierArr.count
  167. <= (_curPhotosBackupsTaskMod.didBackupsCount + _curPhotosBackupsTaskMod.failCount))
  168. {
  169. _curPhotosBackupsTaskMod.curBackupsState = backupsStateDone;
  170. [self RefreshDatabaseFun];
  171. [self changeBackupsFileStateFun];
  172. return;
  173. }
  174. [self beginBackupsFileFun];
  175. }
  176. - (void)beginBackupsFileFun
  177. {
  178. BOOL isCanUseCellular = [HWDataManager getBoolWithKey:stringKeyAddSn(Const_file_Transfe_canUse_Cellular_all)];
  179. if(!isCanUseCellular){//不允许流量上传
  180. //
  181. if([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN){
  182. return;
  183. }
  184. }
  185. self.taskRenewTime = [iTools getNowTimeStamp];
  186. NSInteger index = _curPhotosBackupsTaskMod.didBackupsCount + _curPhotosBackupsTaskMod.failCount;
  187. if(!_curPhotosBackupsTaskMod.LocalIdentifierArr){
  188. _curPhotosBackupsTaskMod.LocalIdentifierArr = [_curPhotosBackupsTaskMod.curTaskLocalIdentifier componentsSeparatedByString:@"&"];
  189. }
  190. if(index >= _curPhotosBackupsTaskMod.LocalIdentifierArr.count){
  191. _curPhotosBackupsTaskMod.curBackupsState = backupsStateDone;
  192. [self RefreshDatabaseFun];
  193. [self changeBackupsFileStateFun];
  194. _curPhotosBackupsTaskMod = nil;
  195. return;
  196. }
  197. NSString *curLocalIdentifier = _curPhotosBackupsTaskMod.LocalIdentifierArr[index];
  198. if(!curLocalIdentifier || curLocalIdentifier.length == 0)
  199. {
  200. [self getDataWrongToChangeFailFun];
  201. return;
  202. }
  203. PHFetchResult *fetchResult = [PHAsset fetchAssetsWithLocalIdentifiers:@[curLocalIdentifier] options:nil];
  204. PHAsset *curAsset = fetchResult.firstObject;
  205. NSString *fileName = [curAsset valueForKey:@"filename"];;
  206. if(!fileName){
  207. [self getDataWrongToChangeFailFun];
  208. return;
  209. }
  210. _curPhotosBackupsTaskMod.filename = fileName;
  211. KWeakSelf
  212. if(curAsset.mediaType == PHAssetMediaTypeImage){
  213. _curPhotosBackupsTaskMod.curUploadFileType = uploadFileTypeImage;
  214. [[PHImageManager defaultManager] requestImageDataForAsset:curAsset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
  215. // 直接得到最终的 NSData 数据
  216. if (imageData) {
  217. [weakSelf afterGetImageDataFun:imageData];
  218. }
  219. else{
  220. [weakSelf getDataWrongToChangeFailFun];
  221. }
  222. }];
  223. }
  224. else{
  225. _curPhotosBackupsTaskMod.curUploadFileType = uploadFileTypeVideo;
  226. //判断文件是否在app内
  227. BOOL didSaveFile = [cachesFileManager checkFileIsSaveState:_curPhotosBackupsTaskMod.filename withType:uploadFileTypeVideo];
  228. if(didSaveFile){
  229. [self afterGetVideoDataFun];
  230. return;
  231. }
  232. //真正的视频数据
  233. PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
  234. options.version = PHVideoRequestOptionsVersionOriginal;
  235. [[PHImageManager defaultManager] requestAVAssetForVideo:curAsset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
  236. if ([asset isKindOfClass:[AVURLAsset class]]) {
  237. AVURLAsset* urlAsset = (AVURLAsset*)asset;
  238. BOOL isSuc = [cachesFileManager copyVideoItemAtPath:[urlAsset.URL path] fileName:self->_curPhotosBackupsTaskMod.filename error:nil];
  239. if (isSuc) {
  240. [weakSelf afterGetVideoDataFun];
  241. }
  242. else{
  243. [weakSelf getDataWrongToChangeFailFun];
  244. }
  245. }
  246. else{
  247. [weakSelf getDataWrongToChangeFailFun];
  248. }
  249. }];
  250. }
  251. }
  252. - (void)getDataWrongToChangeFailFun
  253. {
  254. [self deleteVideoFun];
  255. _curPhotosBackupsTaskMod.failCount += 1;
  256. [self RefreshDatabaseFun];
  257. if(_curPhotosBackupsTaskMod.curBackupsState == backupsStateSuspend){
  258. return;
  259. }
  260. [self beginBackupsFileFun];
  261. }
  262. - (void)changeBackupsFileStateToFailWith:(NSString*)errorStr
  263. {
  264. [self deleteVideoFun];
  265. _curPhotosBackupsTaskMod.curBackupsState = backupsStateFail;
  266. _curPhotosBackupsTaskMod.backupsTipMsg = errorStr;
  267. [self RefreshDatabaseFun];
  268. [self changeBackupsFileStateFun];
  269. }
  270. - (void)RefreshDatabaseFun
  271. {
  272. HLog(@"3 bg_id:%@",_curPhotosBackupsTaskMod.bg_id);
  273. [_curPhotosBackupsTaskMod bg_saveOrUpdateAsync:^(BOOL isSuccess) {
  274. if(isSuccess){
  275. }
  276. }];
  277. }
  278. - (void)afterGetImageDataFun:(NSData*)imageData
  279. {
  280. _curPhotosBackupsTaskMod.imageData = imageData;
  281. _curPhotosBackupsTaskMod.didUploadBytes = 0;
  282. _curPhotosBackupsTaskMod.totalBytes = [imageData length];
  283. [[NSNotificationCenter defaultCenter] postNotificationName:backupsFileBeginNotification object:_curPhotosBackupsTaskMod];
  284. }
  285. - (void)deleteVideoFun
  286. {
  287. if(_curPhotosBackupsTaskMod.curUploadFileType == uploadFileTypeVideo){
  288. [cachesFileManager removeItemAtPath:_curPhotosBackupsTaskMod.filename type:uploadFileTypeVideo error:nil];
  289. }
  290. }
  291. - (void)afterGetVideoDataFun
  292. {
  293. NSString *filePath = [cachesFileManager getFilePathWithName:_curPhotosBackupsTaskMod.filename type:uploadFileTypeVideo]; // 文件路径
  294. NSFileManager *manager0 = [NSFileManager defaultManager];
  295. if([manager0 fileExistsAtPath:filePath]) {
  296. NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath]; // 创建文件句柄
  297. if (fileHandle) {
  298. long long endOfFile = [fileHandle seekToEndOfFile];
  299. _curPhotosBackupsTaskMod.didUploadBytes = 0;
  300. _curPhotosBackupsTaskMod.totalBytes = endOfFile;
  301. [fileHandle closeFile];
  302. }
  303. }
  304. [[NSNotificationCenter defaultCenter] postNotificationName:backupsFileBeginNotification object:_curPhotosBackupsTaskMod];
  305. }
  306. - (void)backupsFileDoneFun
  307. {
  308. [self deleteVideoFun];
  309. _curPhotosBackupsTaskMod.didBackupsCount += 1;
  310. // if(!_curPhotosBackupsTaskMod.didBackupsOneFileType)
  311. // {
  312. // _curPhotosBackupsTaskMod.curTaskBackupsCount += 1;
  313. // }
  314. [self RefreshDatabaseFun];
  315. [self changeBackupsFileStateFun];
  316. if(_curPhotosBackupsTaskMod.curBackupsState == backupsStateSuspend){
  317. return;
  318. }
  319. [self beginBackupsFileFun];
  320. }
  321. //修改文件上传的状态
  322. - (void)changeBackupsFileStateFun
  323. {
  324. self.taskRenewTime = [iTools getNowTimeStamp];
  325. [[NSNotificationCenter defaultCenter] postNotificationName:backupsFileRefreshNotification object:_curPhotosBackupsTaskMod];
  326. }
  327. - (void)suspendBackupsFileFun
  328. {
  329. if(!_curPhotosBackupsTaskMod){
  330. return;
  331. }
  332. _curPhotosBackupsTaskMod.curBackupsState = backupsStateSuspend;
  333. _curPhotosBackupsTaskMod.backupsTipMsg = NSLocalizedString(@"File_backups_Record_tip_Suspend",nil);
  334. [_curPhotosBackupsTaskMod bg_saveOrUpdateAsync:^(BOOL isSuccess) {
  335. if(isSuccess){
  336. [self changeBackupsFileStateFun];
  337. }
  338. }];
  339. }
  340. //文件重新备份
  341. - (void)reBackupsFileFunBy:(photosBackupsTaskModel*)model
  342. {
  343. model.isBackupsSuspendType = backupsSuspendNone;
  344. model.curBackupsState = backupsStateUploading;
  345. _curPhotosBackupsTaskMod = model;
  346. [_curPhotosBackupsTaskMod bg_saveOrUpdateAsync:^(BOOL isSuccess) {
  347. if(isSuccess){
  348. [self beginBackupsFileFun];
  349. }
  350. }];
  351. }
  352. //检查是否需要重新备份
  353. - (void)checkReBackupsFileFun
  354. {
  355. if(!_curPhotosBackupsTaskMod){
  356. return;
  357. }
  358. if(_curPhotosBackupsTaskMod.curBackupsState != backupsStateUploading){
  359. return;
  360. }
  361. NSInteger curTime = [iTools getNowTimeStamp];
  362. if(self.taskRenewTime == 0){
  363. return;
  364. }
  365. if(curTime - self.taskRenewTime < 10){
  366. return;
  367. }
  368. [self beginBackupsFileFun];
  369. }
  370. //检查是否在备份中
  371. - (BOOL)checkBackupsingFun{
  372. if(!_curPhotosBackupsTaskMod){
  373. return NO;
  374. }
  375. if(_curPhotosBackupsTaskMod.curBackupsState != backupsStateUploading){
  376. return NO;
  377. }
  378. return YES;
  379. }
  380. @end