XNCameraManager.m 9.03 KB
//
//  XNCameraManager.m
//  IM_ios_client
//
//  Created by 赵世强 on 2018/3/9.
//  Copyright © 2018年 xiniu. All rights reserved.
//

#import "XNCameraManager.h"
#import "ZLPhotoManager.h"
#import "ZLCustomCamera.h"
#import "ToastUtils.h"
#import <AliyunOSSiOS/OSSService.h>
#import "xn_base_Client_AF.h"

#import "FileUploadAuthInfoGetRequest.h"
#import "FileUploadAuthInfoGetResponse.h"


@implementation XNCameraManager

{
  UIViewController *sender;
  OSSClient *client;
  
}

#pragma mark 创建单例
/**
 *  @author qianjun
 *
 *  @brief  创建单例
 *
 *  @return self
 */
+ (instancetype)sharedInstance {
  static id sharedInstance = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    sharedInstance = [[self alloc] init];
  });
  return sharedInstance;
}

-(instancetype)init{
  self = [super init];
  self.passportId = @"";
  return self;
}

- (void)showCameraWithController:(UIViewController *)sender passportId:(NSString *)passportId{
  sender = sender;
  if (passportId) {
    self.passportId = passportId;
  }
  
  if (![ZLPhotoManager haveMicrophoneAuthority]) {
    NSString *message = [NSString stringWithFormat:GetLocalLanguageTextValue(ZLPhotoBrowserNoMicrophoneAuthorityText), kAPPName];
    ShowAlert(message, sender);
    return;
  }
  ZLCustomCamera *camera = [[ZLCustomCamera alloc] init];
  camera.allowTakePhoto = YES;
  camera.allowRecordVideo = NO;
  camera.sessionPreset = ZLCaptureSessionPreset640x480;
  camera.videoType = ZLExportVideoTypeMp4;
  camera.modalPresentationStyle = UIModalPresentationFullScreen;
  camera.circleProgressColor = [UIColor colorWithRed:((float)((0x3399ff & 0xFF0000) >> 16))/255.0 green:((float)((0x3399ff & 0xFF00) >> 8))/255.0 blue:((float)(0x3399ff & 0xFF))/255.0 alpha:1.0];
  camera.maxRecordDuration = 10;
  zl_weakify(self);
  camera.doneBlock = ^(UIImage *image, NSURL *videoUrl) {
    zl_strongify(weakSelf);
    [strongSelf saveImage:image videoUrl:videoUrl];
  };
  [sender showDetailViewController:camera sender:nil];
}

- (void)saveImage:(UIImage *)image videoUrl:(NSURL *)videoUrl
{
  zl_weakify(self);
  if (image) {
    [ZLPhotoManager saveImageToAblum:image completion:^(BOOL suc, PHAsset *asset) {
      zl_strongify(weakSelf);
      dispatch_async(dispatch_get_main_queue(), ^{
        if (suc) {
          //                    ZLPhotoModel *model = [ZLPhotoModel modelWithAsset:asset type:ZLAssetMediaTypeImage duration:nil];
          NSData* data= UIImageJPEGRepresentation(image, 0.1);
          [strongSelf uploadFileWithData:data fileType:ZLAssetMediaTypeImage asset:asset];
          
          
        } else {
          ShowToastLong(@"%@", GetLocalLanguageTextValue(ZLPhotoBrowserSaveImageErrorText));
        }
        
      });
    }];
  } else if (videoUrl) {
    [ZLPhotoManager saveVideoToAblum:videoUrl completion:^(BOOL suc, PHAsset *asset) {
      zl_strongify(weakSelf);
      dispatch_async(dispatch_get_main_queue(), ^{
        if (suc) {
          ZLPhotoModel *model = [ZLPhotoModel modelWithAsset:asset type:ZLAssetMediaTypeVideo duration:nil];
          
          model.duration = [ZLPhotoManager getDuration:asset];
          
          NSData* data = [NSData dataWithContentsOfURL:videoUrl];
          
          [strongSelf uploadFileWithData:data fileType:ZLAssetMediaTypeVideo asset:asset];
        } else {
          ShowToastLong(@"%@", GetLocalLanguageTextValue(ZLPhotoBrowserSaveVideoFailed));
        }
        
      });
    }];
  }
}

- (void)uploadFileWithData:(NSData *)data fileType:(ZLAssetMediaType)type asset:(PHAsset *)asset{
  
  ZLProgressHUD *hud = [[ZLProgressHUD alloc] init];
  [hud show];
  
  FileUploadAuthInfoGetRequest *req_FileUploadAuthInfoGet = [[FileUploadAuthInfoGetRequest alloc]init];
  [req_FileUploadAuthInfoGet.baseRequest setSession:self.passportId];
  [req_FileUploadAuthInfoGet.baseRequest setMethod:req_FileUploadAuthInfoGet.apimethodName];
  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
  NSString *str_date = [self getDateTimeString:dateFormatter];
  NSString *str_fileName = [NSString stringWithFormat:@"%@%@%@",str_date,self.passportId,[asset valueForKey:@"filename"]];

  [req_FileUploadAuthInfoGet setName:str_fileName];
  
  [[xn_base_Client_AF sharedInstance] f_sendRequest:req_FileUploadAuthInfoGet.baseRequest isPost:YES completion:^(NSDictionary *_dict) {
    
    BaseResponse *_res_base = (BaseResponse *)[_dict objectForKey:kResponseNotiKey_baseResponse];
    NSString *_str_error = [_dict objectForKey:kResponseNotiKey_error];
    if (![_str_error isEqualToString:kNoError]) {
      // 出错
      [hud hide];
      
    }else{
      FileUploadAuthInfoGetResponse *res_FileUploadAuthInfoGet = [[FileUploadAuthInfoGetResponse alloc]init];
      res_FileUploadAuthInfoGet.baseResponse = _res_base;
      
      id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:res_FileUploadAuthInfoGet.accessKeyId secretKeyId:res_FileUploadAuthInfoGet.accessKeySecret securityToken:res_FileUploadAuthInfoGet.securityToken];
      client = [[OSSClient alloc] initWithEndpoint:res_FileUploadAuthInfoGet.info.endpoint credentialProvider:credential];
      
      OSSPutObjectRequest * put = [OSSPutObjectRequest new];
      // 必填字段
      put.bucketName = res_FileUploadAuthInfoGet.info.bucket;
      
      NSString *string = res_FileUploadAuthInfoGet.info.fileUrl;
      
      if ([[string substringWithRange:NSMakeRange(0, 1)] isEqualToString:@"/"]) {
        string =  [res_FileUploadAuthInfoGet.info.fileUrl substringWithRange:NSMakeRange(1, res_FileUploadAuthInfoGet.info.fileUrl.length-1)];
        
      }
      
      put.objectKey = string;
      put.uploadingData = data;
      
      OSSTask * putTask = [client putObject:put];
      [putTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
          NSLog(@"upload object success! 上传文件成功");
          NSString * constrainURL = nil;
          OSSTask *result = [client presignPublicURLWithBucketName:res_FileUploadAuthInfoGet.info.bucket
                                                     withObjectKey:string];
          if (!result.error) {
            constrainURL = result.result;
            if (self.finshBlock) {
              if (type == ZLAssetMediaTypeImage) {
                self.finshBlock(@{@"url":constrainURL,@"type":@"IMAGE"});
              }else if (type == ZLAssetMediaTypeVideo){
                self.finshBlock(@{@"url":constrainURL,@"type":@"VIDEO"});
              }
              [hud hide];
              self.finshBlock = nil;
            }else{
              [hud hide];
            }
            NSLog(@"error: %@", constrainURL);
          } else {
            [hud hide];
            NSLog(@"error: %@", result.error);
          }
          
        } else {
          [hud hide];
          NSLog(@"upload object failed, error: %@" , task.error);
        }
        return nil;
      }];
    }
    
    NSLog(@"%@",_dict);
  }];
  
  
  //    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  //
  //    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"multipart/form-data", nil];
  //
  //    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
  //
  //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
  //
  //    [manager POST:[NSString stringWithFormat:@"https://my.xiniunet.com/api/fileUpload.do?passportId=%@",self.passportId] parameters:body constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
  //
  //        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  //        // 设置时间格式
  //        formatter.dateFormat = @"yyyyMMddHHmmss";
  //        NSString *str = [formatter stringFromDate:[NSDate date]];
  //        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
  //
  //        if (type == ZLAssetMediaTypeVideo) {
  //
  //            [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"file/mov"];
  //        }else{
  //
  //            [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/jpg"];
  //        }
  //
  //        NSLog(@"1111");
  //
  //    } progress:^(NSProgress * _Nonnull uploadProgress) {
  //
  //        NSLog(@"上传中");
  //
  //    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
  //
  //          //请求成功的block回调
  //        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
  //
  //        NSLog(@"上传成功%@",dic);
  //        [hud hide];
  //
  //
  //    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  //
  //        NSLog(@"上传失败%@",error);
  //        [hud hide];
  //    }];
}

- (NSString *)getDateTimeString:(NSDateFormatter *)dateFormatter
{
  if (dateFormatter == nil) {
    dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
  }
  NSDate *dateNow = [NSDate date];
  return [dateFormatter stringFromDate:dateNow];
}

@end