react-native-compressor 1.3.4 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +52 -1
  2. package/android/.gradle/6.1.1/fileHashes/fileHashes.lock +0 -0
  3. package/android/.gradle/buildOutputCleanup/buildOutputCleanup.lock +0 -0
  4. package/android/.gradle/buildOutputCleanup/cache.properties +2 -2
  5. package/android/.gradle/checksums/checksums.lock +0 -0
  6. package/android/.gradle/checksums/sha1-checksums.bin +0 -0
  7. package/android/build.gradle +1 -1
  8. package/android/src/main/java/com/.DS_Store +0 -0
  9. package/android/src/main/java/com/reactnativecompressor/.DS_Store +0 -0
  10. package/android/src/main/java/com/reactnativecompressor/CompressorModule.java +46 -1
  11. package/android/src/main/java/com/reactnativecompressor/Utils/RealPathUtil.java +210 -0
  12. package/android/src/main/java/com/reactnativecompressor/Utils/Utils.java +26 -1
  13. package/android/src/main/java/com/reactnativecompressor/Video/VideoModule.java +6 -0
  14. package/ios/.DS_Store +0 -0
  15. package/ios/Compressor-Bridging-Header.h +1 -1
  16. package/ios/Compressor.m +118 -12
  17. package/ios/Image/ImageCompressor.h +2 -0
  18. package/ios/Image/ImageCompressor.m +153 -1
  19. package/ios/Video/VideoCompressor.swift +34 -34
  20. package/lib/commonjs/Video/index.js +1 -1
  21. package/lib/commonjs/Video/index.js.map +1 -1
  22. package/lib/commonjs/index.js +22 -1
  23. package/lib/commonjs/index.js.map +1 -1
  24. package/lib/commonjs/utils/index.js +18 -4
  25. package/lib/commonjs/utils/index.js.map +1 -1
  26. package/lib/module/Video/index.js +1 -1
  27. package/lib/module/Video/index.js.map +1 -1
  28. package/lib/module/index.js +6 -3
  29. package/lib/module/index.js.map +1 -1
  30. package/lib/module/utils/index.js +9 -4
  31. package/lib/module/utils/index.js.map +1 -1
  32. package/lib/typescript/index.d.ts +5 -2
  33. package/lib/typescript/utils/index.d.ts +3 -0
  34. package/package.json +1 -1
  35. package/src/Video/index.tsx +1 -1
  36. package/src/index.tsx +13 -1
  37. package/src/utils/index.tsx +14 -3
@@ -1,7 +1,12 @@
1
1
  #import <Accelerate/Accelerate.h>
2
2
  #import <CoreGraphics/CoreGraphics.h>
3
-
3
+ #import <Photos/Photos.h>
4
+ #import <React/RCTUtils.h>
5
+ #import <React/RCTImageLoader.h>
4
6
  #import "ImageCompressor.h"
7
+ #import <React/RCTConvert.h>
8
+ #import <Foundation/Foundation.h>
9
+ #import <MobileCoreServices/MobileCoreServices.h>
5
10
 
6
11
  @implementation ImageCompressor
7
12
  + (CGSize) findTargetSize: (UIImage *) image maxWidth: (int) maxWidth maxHeight: (int) maxHeight {
@@ -288,4 +293,151 @@
288
293
  return returnablePath;
289
294
  }
290
295
 
296
+ +(void)getAbsoluteImagePath:(NSString *)imagePath completionHandler:(void (^)(NSString *absoluteImagePath))completionHandler
297
+ {
298
+ if (![imagePath containsString:@"ph://"]) {
299
+ completionHandler(imagePath);
300
+ return;
301
+ }
302
+ NSURL *imageURL = [NSURL URLWithString:[imagePath stringByReplacingOccurrencesOfString:@" " withString:@"%20"]];
303
+ CGSize size = CGSizeZero;
304
+ CGFloat scale = 1;
305
+ RCTResizeMode resizeMode = RCTResizeModeContain;
306
+ NSString *assetID = @"";
307
+ PHFetchResult *results;
308
+ if (!imageURL) {
309
+ NSString *errorText = @"Cannot load a photo library asset with no URL";
310
+ @throw([NSException exceptionWithName:errorText reason:errorText userInfo:nil]);
311
+ } else if ([imageURL.scheme caseInsensitiveCompare:@"assets-library"] == NSOrderedSame) {
312
+ assetID = [imageURL absoluteString];
313
+ results = [PHAsset fetchAssetsWithALAssetURLs:@[imageURL] options:nil];
314
+ } else {
315
+ assetID = [imageURL.absoluteString substringFromIndex:@"ph://".length];
316
+ results = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetID] options:nil];
317
+ }
318
+ if (results.count == 0) {
319
+ NSString *errorText = [NSString stringWithFormat:@"Failed to fetch PHAsset with local identifier %@ with no error message.", assetID];
320
+ @throw([NSException exceptionWithName:errorText reason:errorText userInfo:nil]);
321
+ }
322
+ PHAsset *asset = [results firstObject]; // <-- WE GOT THE ASSET
323
+ PHImageRequestOptions *imageOptions = [PHImageRequestOptions new];
324
+ imageOptions.networkAccessAllowed = YES;
325
+ imageOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
326
+
327
+ BOOL useMaximumSize = CGSizeEqualToSize(size, CGSizeZero);
328
+ CGSize targetSize;
329
+ if (useMaximumSize) {
330
+ targetSize = PHImageManagerMaximumSize;
331
+ imageOptions.resizeMode = PHImageRequestOptionsResizeModeNone;
332
+ } else {
333
+ targetSize = CGSizeApplyAffineTransform(size, CGAffineTransformMakeScale(scale, scale));
334
+ imageOptions.resizeMode = PHImageRequestOptionsResizeModeFast;
335
+ }
336
+
337
+ PHImageContentMode contentMode = PHImageContentModeAspectFill;
338
+ if (resizeMode == RCTResizeModeContain) {
339
+ contentMode = PHImageContentModeAspectFit;
340
+ }
341
+ [[PHImageManager defaultManager] requestImageForAsset:asset
342
+ targetSize:targetSize
343
+ contentMode:contentMode
344
+ options:imageOptions
345
+ resultHandler:^(UIImage *result, NSDictionary<NSString *, id> *info) {
346
+ // WE GOT THE IMAGE
347
+ if (result) {
348
+ UIImage *image = result;
349
+ NSString *imageName = [assetID stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
350
+ NSString *imagePath = [self saveImageIntoCache:image withName:imageName];
351
+ completionHandler(imagePath);
352
+ } else {
353
+ @throw([NSException exceptionWithName:@"image not found" reason:@"image not found" userInfo:nil]);
354
+ }
355
+ }];
356
+ }
357
+
358
+ +(NSString*) saveImageIntoCache:(UIImage *)image withName:(NSString *)name {
359
+ NSData *imageData = UIImageJPEGRepresentation(image, 1);
360
+ NSString *path =[self generateCacheFilePath:@"jpg"];
361
+ [[NSFileManager defaultManager] createFileAtPath:path contents:imageData attributes:NULL];
362
+ return path;
363
+ }
364
+
365
+ /// for video
366
+
367
+ +(void)getAbsoluteVideoPath:(NSString *)videoPath completionHandler:(void (^)(NSString *absoluteImagePath))completionHandler
368
+ {
369
+
370
+ if (![videoPath containsString:@"ph://"]) {
371
+ completionHandler(videoPath);
372
+ return;
373
+ }
374
+ NSString *assetId =[videoPath stringByReplacingOccurrencesOfString:@"ph://"
375
+ withString:@""];
376
+ AVFileType outputFileType = AVFileTypeMPEG4;
377
+ NSString *pressetType = AVAssetExportPresetPassthrough;
378
+
379
+ // Throwing some errors to the user if he is not careful enough
380
+ if ([assetId isEqualToString:@""]) {
381
+ NSError *error = [NSError errorWithDomain:@"RNGalleryManager" code: -91 userInfo:nil];
382
+ @throw([NSException exceptionWithName:error reason:error userInfo:nil]);
383
+ return;
384
+ }
385
+
386
+ // Getting Video Asset
387
+ NSArray* localIds = [NSArray arrayWithObjects: assetId, nil];
388
+ PHAsset * _Nullable videoAsset = [PHAsset fetchAssetsWithLocalIdentifiers:localIds options:nil].firstObject;
389
+
390
+ // Getting information from the asset
391
+ NSString *mimeType = (NSString *)CFBridgingRelease(UTTypeCopyPreferredTagWithClass((__bridge CFStringRef _Nonnull)(outputFileType), kUTTagClassMIMEType));
392
+ CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, (__bridge CFStringRef _Nonnull)(mimeType), NULL);
393
+ NSString *extension = (NSString *)CFBridgingRelease(UTTypeCopyPreferredTagWithClass(uti, kUTTagClassFilenameExtension));
394
+
395
+ // Creating output url and temp file name
396
+ NSString *path =[self generateCacheFilePath:extension];
397
+ NSURL *outputUrl = [NSURL URLWithString:[@"file://" stringByAppendingString:path]];
398
+
399
+ // Setting video export session options
400
+ PHVideoRequestOptions *videoRequestOptions = [[PHVideoRequestOptions alloc] init];
401
+ videoRequestOptions.networkAccessAllowed = YES;
402
+ videoRequestOptions.deliveryMode = PHVideoRequestOptionsDeliveryModeHighQualityFormat;
403
+
404
+ // Creating new export session
405
+ [[PHImageManager defaultManager] requestExportSessionForVideo:videoAsset options:videoRequestOptions exportPreset:pressetType resultHandler:^(AVAssetExportSession * _Nullable exportSession, NSDictionary * _Nullable info) {
406
+
407
+ exportSession.shouldOptimizeForNetworkUse = YES;
408
+ exportSession.outputFileType = outputFileType;
409
+ exportSession.outputURL = outputUrl;
410
+ // Converting the video and waiting to see whats going to happen
411
+ [exportSession exportAsynchronouslyWithCompletionHandler:^{
412
+ switch ([exportSession status])
413
+ {
414
+ case AVAssetExportSessionStatusFailed:
415
+ {
416
+ NSError* error = exportSession.error;
417
+ NSString *codeWithDomain = [NSString stringWithFormat:@"E%@%zd", error.domain.uppercaseString, error.code];
418
+ @throw([NSException exceptionWithName:error reason:error userInfo:nil]);
419
+ break;
420
+ }
421
+ case AVAssetExportSessionStatusCancelled:
422
+ {
423
+ NSError *error = [NSError errorWithDomain:@"RNGalleryManager" code: -91 userInfo:nil];
424
+ @throw([NSException exceptionWithName:error reason:error userInfo:nil]);
425
+ break;
426
+ }
427
+ case AVAssetExportSessionStatusCompleted:
428
+ {
429
+ completionHandler(outputUrl.absoluteString);
430
+ break;
431
+ }
432
+ default:
433
+ {
434
+ NSError *error = [NSError errorWithDomain:@"RNGalleryManager" code: -91 userInfo:nil];
435
+ @throw([NSException exceptionWithName:@"Unknown status" reason:@"Unknown status" userInfo:nil]);
436
+ break;
437
+ }
438
+ }
439
+ }];
440
+ }];
441
+ }
442
+
291
443
  @end
@@ -2,6 +2,7 @@ import Foundation
2
2
  import AssetsLibrary
3
3
  import AVFoundation
4
4
  import NextLevelSessionExporter
5
+ import Photos
5
6
 
6
7
  struct CompressionError: Error {
7
8
  private let message: String
@@ -205,45 +206,45 @@ func makeValidUri(filePath: String) -> String {
205
206
 
206
207
 
207
208
  func compressVideo(url: URL, options: [String: Any], onProgress: @escaping (Float) -> Void, onCompletion: @escaping (URL) -> Void, onFailure: @escaping (Error) -> Void){
208
- var minimumFileSizeForCompress:Double=16.0;
209
- let fileSize=self.getfileSize(forURL: url);
210
- if((options["minimumFileSizeForCompress"]) != nil)
211
- {
212
- minimumFileSizeForCompress=options["minimumFileSizeForCompress"] as! Double;
213
- }
214
- if(fileSize>minimumFileSizeForCompress)
215
- {
216
- if(options["compressionMethod"] as! String=="auto")
209
+ ImageCompressor.getAbsoluteVideoPath(url.absoluteString) { absoluteVideoPath in
210
+ var minimumFileSizeForCompress:Double=16.0;
211
+ let videoURL = URL(string: absoluteVideoPath!)
212
+ let fileSize=self.getfileSize(forURL: videoURL!);
213
+ if((options["minimumFileSizeForCompress"]) != nil)
217
214
  {
218
- autoCompressionHelper(url: url, options:options) { progress in
219
- onProgress(progress)
220
- } onCompletion: { outputURL in
221
- onCompletion(outputURL)
222
- } onFailure: { error in
223
- onFailure(error)
215
+ minimumFileSizeForCompress=options["minimumFileSizeForCompress"] as! Double;
216
+ }
217
+ if(fileSize>minimumFileSizeForCompress)
218
+ {
219
+ if(options["compressionMethod"] as! String=="auto")
220
+ {
221
+ self.autoCompressionHelper(url: videoURL!, options:options) { progress in
222
+ onProgress(progress)
223
+ } onCompletion: { outputURL in
224
+ onCompletion(outputURL)
225
+ } onFailure: { error in
226
+ onFailure(error)
227
+ }
224
228
  }
229
+ else
230
+ {
231
+ self.manualCompressionHelper(url: videoURL!, options:options) { progress in
232
+ onProgress(progress)
233
+ } onCompletion: { outputURL in
234
+ onCompletion(outputURL)
235
+ } onFailure: { error in
236
+ onFailure(error)
237
+ }
238
+ }
239
+
240
+
241
+
225
242
  }
226
243
  else
227
244
  {
228
- manualCompressionHelper(url: url, options:options) { progress in
229
- onProgress(progress)
230
- } onCompletion: { outputURL in
231
- onCompletion(outputURL)
232
- } onFailure: { error in
233
- onFailure(error)
234
- }
245
+ onCompletion(url)
235
246
  }
236
-
237
-
238
-
239
- }
240
- else
241
- {
242
- onCompletion(url)
243
- }
244
-
245
-
246
-
247
+ }
247
248
  }
248
249
 
249
250
 
@@ -412,5 +413,4 @@ func makeValidUri(filePath: String) -> String {
412
413
  return track;
413
414
  }
414
415
 
415
-
416
416
  }
@@ -82,7 +82,7 @@ const Video = {
82
82
  modifiedOptions.maxSize = 640;
83
83
  }
84
84
 
85
- if (options !== null && options !== void 0 && options.minimumFileSizeForCompress) {
85
+ if ((options === null || options === void 0 ? void 0 : options.minimumFileSizeForCompress) !== undefined) {
86
86
  modifiedOptions.minimumFileSizeForCompress = options === null || options === void 0 ? void 0 : options.minimumFileSizeForCompress;
87
87
  }
88
88
 
@@ -1 +1 @@
1
- {"version":3,"sources":["index.tsx"],"names":["VideoCompressEventEmitter","NativeEventEmitter","NativeModules","VideoCompressor","NativeVideoCompressor","backgroundUpload","url","fileUrl","options","onProgress","uuid","subscription","addListener","event","data","written","total","Platform","OS","includes","replace","result","upload","method","httpMethod","headers","remove","cancelCompression","cancellationId","Video","compress","progress","modifiedOptions","bitrate","compressionMethod","maxSize","minimumFileSizeForCompress","getCancellationId","activateBackgroundTask","onExpired","deactivateBackgroundTask","removeAllListeners"],"mappings":";;;;;;;AAAA;;AAMA;;AAgEA,MAAMA,yBAAyB,GAAG,IAAIC,+BAAJ,CAChCC,2BAAcC,eADkB,CAAlC;AAIA,MAAMC,qBAAqB,GAAGF,2BAAcC,eAA5C;;AAEO,MAAME,gBAAgB,GAAG,OAC9BC,GAD8B,EAE9BC,OAF8B,EAG9BC,OAH8B,EAI9BC,UAJ8B,KAKb;AACjB,QAAMC,IAAI,GAAG,oBAAb;AACA,MAAIC,YAAJ;;AACA,MAAI;AACF,QAAIF,UAAJ,EAAgB;AACdE,MAAAA,YAAY,GAAGX,yBAAyB,CAACY,WAA1B,CACb,yBADa,EAEZC,KAAD,IAAgB;AACd,YAAIA,KAAK,CAACH,IAAN,KAAeA,IAAnB,EAAyB;AACvBD,UAAAA,UAAU,CAACI,KAAK,CAACC,IAAN,CAAWC,OAAZ,EAAqBF,KAAK,CAACC,IAAN,CAAWE,KAAhC,CAAV;AACD;AACF,OANY,CAAf;AAQD;;AACD,QAAIC,sBAASC,EAAT,KAAgB,SAAhB,IAA6BX,OAAO,CAACY,QAAR,CAAiB,SAAjB,CAAjC,EAA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D,CAAT;;AACA,YAAIF,YAAJ,EAAkB;AAChBA,UAAAA,YAAY,CAACe,MAAb;AACD;AACF,OAPH,CADF;AAUD;;AACD,WAAOtB,qBAAqB,CAACkC,sBAAtB,CAA6C,EAA7C,CAAP;AACD,GAxEgC;;AAyEjCE,EAAAA,wBAAwB,GAAG;AACzBxC,IAAAA,yBAAyB,CAACyC,kBAA1B,CAA6C,uBAA7C;AACA,WAAOrC,qBAAqB,CAACoC,wBAAtB,CAA+C,EAA/C,CAAP;AACD;;AA5EgC,CAAnC;eA+EeX,K","sourcesContent":["import {\n NativeModules,\n NativeEventEmitter,\n Platform,\n NativeEventSubscription,\n} from 'react-native';\nimport { uuidv4 } from '../utils';\n\nexport declare enum FileSystemUploadType {\n BINARY_CONTENT = 0,\n MULTIPART = 1,\n}\n\nexport declare type FileSystemAcceptedUploadHttpMethod =\n | 'POST'\n | 'PUT'\n | 'PATCH';\nexport type compressionMethod = 'auto' | 'manual';\ntype videoCompresssionType = {\n bitrate?: number;\n maxSize?: number;\n compressionMethod?: compressionMethod;\n minimumFileSizeForCompress?: number;\n getCancellationId?: (cancellationId: string) => void;\n};\n\nexport declare enum FileSystemSessionType {\n BACKGROUND = 0,\n FOREGROUND = 1,\n}\n\nexport declare type HTTPResponse = {\n status: number;\n headers: Record<string, string>;\n body: string;\n};\n\nexport declare type FileSystemUploadOptions = (\n | {\n uploadType?: FileSystemUploadType.BINARY_CONTENT;\n }\n | {\n uploadType: FileSystemUploadType.MULTIPART;\n fieldName?: string;\n mimeType?: string;\n parameters?: Record<string, string>;\n }\n) & {\n headers?: Record<string, string>;\n httpMethod?: FileSystemAcceptedUploadHttpMethod;\n sessionType?: FileSystemSessionType;\n};\n\nexport type VideoCompressorType = {\n compress(\n fileUrl: string,\n options?: videoCompresssionType,\n onProgress?: (progress: number) => void\n ): Promise<string>;\n cancelCompression(cancellationId: string): void;\n backgroundUpload(\n url: string,\n fileUrl: string,\n options: FileSystemUploadOptions,\n onProgress?: (writtem: number, total: number) => void\n ): Promise<any>;\n activateBackgroundTask(onExpired?: (data: any) => void): Promise<any>;\n deactivateBackgroundTask(): Promise<any>;\n};\n\nconst VideoCompressEventEmitter = new NativeEventEmitter(\n NativeModules.VideoCompressor\n);\n\nconst NativeVideoCompressor = NativeModules.VideoCompressor;\n\nexport const backgroundUpload = async (\n url: string,\n fileUrl: string,\n options: FileSystemUploadOptions,\n onProgress?: (writtem: number, total: number) => void\n): Promise<any> => {\n const uuid = uuidv4();\n let subscription: NativeEventSubscription;\n try {\n if (onProgress) {\n subscription = VideoCompressEventEmitter.addListener(\n 'VideoCompressorProgress',\n (event: any) => {\n if (event.uuid === uuid) {\n onProgress(event.data.written, event.data.total);\n }\n }\n );\n }\n if (Platform.OS === 'android' && fileUrl.includes('file://')) {\n fileUrl = fileUrl.replace('file://', '');\n }\n const result = await NativeVideoCompressor.upload(fileUrl, {\n uuid,\n method: options.httpMethod,\n headers: options.headers,\n url,\n });\n return result;\n } finally {\n // @ts-ignore\n if (subscription) {\n subscription.remove();\n }\n }\n};\n\nexport const cancelCompression = (cancellationId: string) => {\n return NativeVideoCompressor.cancelCompression(cancellationId);\n};\n\nconst Video: VideoCompressorType = {\n compress: async (\n fileUrl: string,\n options?: videoCompresssionType,\n onProgress?: (progress: number) => void\n ) => {\n const uuid = uuidv4();\n let subscription: NativeEventSubscription;\n try {\n if (onProgress) {\n subscription = VideoCompressEventEmitter.addListener(\n 'videoCompressProgress',\n (event: any) => {\n if (event.uuid === uuid) {\n onProgress(event.data.progress);\n }\n }\n );\n }\n const modifiedOptions: {\n uuid: string;\n bitrate?: number;\n compressionMethod?: compressionMethod;\n maxSize?: number;\n minimumFileSizeForCompress?: number;\n } = { uuid };\n if (options?.bitrate) modifiedOptions.bitrate = options?.bitrate;\n if (options?.compressionMethod) {\n modifiedOptions.compressionMethod = options?.compressionMethod;\n } else {\n modifiedOptions.compressionMethod = 'manual';\n }\n if (options?.maxSize) {\n modifiedOptions.maxSize = options?.maxSize;\n } else {\n modifiedOptions.maxSize = 640;\n }\n if (options?.minimumFileSizeForCompress) {\n modifiedOptions.minimumFileSizeForCompress =\n options?.minimumFileSizeForCompress;\n }\n if (options?.getCancellationId) {\n options?.getCancellationId(uuid);\n }\n const result = await NativeVideoCompressor.compress(\n fileUrl,\n modifiedOptions\n );\n return result;\n } finally {\n // @ts-ignore\n if (subscription) {\n subscription.remove();\n }\n }\n },\n backgroundUpload,\n cancelCompression,\n activateBackgroundTask(onExpired?) {\n if (onExpired) {\n const subscription: NativeEventSubscription =\n VideoCompressEventEmitter.addListener(\n 'backgroundTaskExpired',\n (event: any) => {\n onExpired(event);\n if (subscription) {\n subscription.remove();\n }\n }\n );\n }\n return NativeVideoCompressor.activateBackgroundTask({});\n },\n deactivateBackgroundTask() {\n VideoCompressEventEmitter.removeAllListeners('backgroundTaskExpired');\n return NativeVideoCompressor.deactivateBackgroundTask({});\n },\n} as VideoCompressorType;\n\nexport default Video;\n"]}
1
+ {"version":3,"sources":["index.tsx"],"names":["VideoCompressEventEmitter","NativeEventEmitter","NativeModules","VideoCompressor","NativeVideoCompressor","backgroundUpload","url","fileUrl","options","onProgress","uuid","subscription","addListener","event","data","written","total","Platform","OS","includes","replace","result","upload","method","httpMethod","headers","remove","cancelCompression","cancellationId","Video","compress","progress","modifiedOptions","bitrate","compressionMethod","maxSize","minimumFileSizeForCompress","undefined","getCancellationId","activateBackgroundTask","onExpired","deactivateBackgroundTask","removeAllListeners"],"mappings":";;;;;;;AAAA;;AAMA;;AAgEA,MAAMA,yBAAyB,GAAG,IAAIC,+BAAJ,CAChCC,2BAAcC,eADkB,CAAlC;AAIA,MAAMC,qBAAqB,GAAGF,2BAAcC,eAA5C;;AAEO,MAAME,gBAAgB,GAAG,OAC9BC,GAD8B,EAE9BC,OAF8B,EAG9BC,OAH8B,EAI9BC,UAJ8B,KAKb;AACjB,QAAMC,IAAI,GAAG,oBAAb;AACA,MAAIC,YAAJ;;AACA,MAAI;AACF,QAAIF,UAAJ,EAAgB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,EAEnByB,eAFmB,CAArB;AAIA,aAAOX,MAAP;AACD,KAzCD,SAyCU;AACR;AACA,UAAIV,YAAJ,EAAkB;AAChBA,QAAAA,YAAY,CAACe,MAAb;AACD;AACF;AACF,GAvDgC;AAwDjCrB,EAAAA,gBAxDiC;AAyDjCsB,EAAAA,iBAzDiC;;AA0DjCY,EAAAA,sBAAsB,CAACC,SAAD,EAAa;AACjC,QAAIA,SAAJ,EAAe;AACb,YAAM7B,YAAqC,GACzCX,yBAAyB,CAACY,WAA1B,CACE,uBADF,EAEGC,KAAD,IAAgB;AACd2B,QAAAA,SAAS,CAAC3B,KAAD,CAAT;;AACA,YAAIF,YAAJ,EAAkB;AAChBA,UAAAA,YAAY,CAACe,MAAb;AACD;AACF,OAPH,CADF;AAUD;;AACD,WAAOtB,qBAAqB,CAACmC,sBAAtB,CAA6C,EAA7C,CAAP;AACD,GAxEgC;;AAyEjCE,EAAAA,wBAAwB,GAAG;AACzBzC,IAAAA,yBAAyB,CAAC0C,kBAA1B,CAA6C,uBAA7C;AACA,WAAOtC,qBAAqB,CAACqC,wBAAtB,CAA+C,EAA/C,CAAP;AACD;;AA5EgC,CAAnC;eA+EeZ,K","sourcesContent":["import {\n NativeModules,\n NativeEventEmitter,\n Platform,\n NativeEventSubscription,\n} from 'react-native';\nimport { uuidv4 } from '../utils';\n\nexport declare enum FileSystemUploadType {\n BINARY_CONTENT = 0,\n MULTIPART = 1,\n}\n\nexport declare type FileSystemAcceptedUploadHttpMethod =\n | 'POST'\n | 'PUT'\n | 'PATCH';\nexport type compressionMethod = 'auto' | 'manual';\ntype videoCompresssionType = {\n bitrate?: number;\n maxSize?: number;\n compressionMethod?: compressionMethod;\n minimumFileSizeForCompress?: number;\n getCancellationId?: (cancellationId: string) => void;\n};\n\nexport declare enum FileSystemSessionType {\n BACKGROUND = 0,\n FOREGROUND = 1,\n}\n\nexport declare type HTTPResponse = {\n status: number;\n headers: Record<string, string>;\n body: string;\n};\n\nexport declare type FileSystemUploadOptions = (\n | {\n uploadType?: FileSystemUploadType.BINARY_CONTENT;\n }\n | {\n uploadType: FileSystemUploadType.MULTIPART;\n fieldName?: string;\n mimeType?: string;\n parameters?: Record<string, string>;\n }\n) & {\n headers?: Record<string, string>;\n httpMethod?: FileSystemAcceptedUploadHttpMethod;\n sessionType?: FileSystemSessionType;\n};\n\nexport type VideoCompressorType = {\n compress(\n fileUrl: string,\n options?: videoCompresssionType,\n onProgress?: (progress: number) => void\n ): Promise<string>;\n cancelCompression(cancellationId: string): void;\n backgroundUpload(\n url: string,\n fileUrl: string,\n options: FileSystemUploadOptions,\n onProgress?: (writtem: number, total: number) => void\n ): Promise<any>;\n activateBackgroundTask(onExpired?: (data: any) => void): Promise<any>;\n deactivateBackgroundTask(): Promise<any>;\n};\n\nconst VideoCompressEventEmitter = new NativeEventEmitter(\n NativeModules.VideoCompressor\n);\n\nconst NativeVideoCompressor = NativeModules.VideoCompressor;\n\nexport const backgroundUpload = async (\n url: string,\n fileUrl: string,\n options: FileSystemUploadOptions,\n onProgress?: (writtem: number, total: number) => void\n): Promise<any> => {\n const uuid = uuidv4();\n let subscription: NativeEventSubscription;\n try {\n if (onProgress) {\n subscription = VideoCompressEventEmitter.addListener(\n 'VideoCompressorProgress',\n (event: any) => {\n if (event.uuid === uuid) {\n onProgress(event.data.written, event.data.total);\n }\n }\n );\n }\n if (Platform.OS === 'android' && fileUrl.includes('file://')) {\n fileUrl = fileUrl.replace('file://', '');\n }\n const result = await NativeVideoCompressor.upload(fileUrl, {\n uuid,\n method: options.httpMethod,\n headers: options.headers,\n url,\n });\n return result;\n } finally {\n // @ts-ignore\n if (subscription) {\n subscription.remove();\n }\n }\n};\n\nexport const cancelCompression = (cancellationId: string) => {\n return NativeVideoCompressor.cancelCompression(cancellationId);\n};\n\nconst Video: VideoCompressorType = {\n compress: async (\n fileUrl: string,\n options?: videoCompresssionType,\n onProgress?: (progress: number) => void\n ) => {\n const uuid = uuidv4();\n let subscription: NativeEventSubscription;\n try {\n if (onProgress) {\n subscription = VideoCompressEventEmitter.addListener(\n 'videoCompressProgress',\n (event: any) => {\n if (event.uuid === uuid) {\n onProgress(event.data.progress);\n }\n }\n );\n }\n const modifiedOptions: {\n uuid: string;\n bitrate?: number;\n compressionMethod?: compressionMethod;\n maxSize?: number;\n minimumFileSizeForCompress?: number;\n } = { uuid };\n if (options?.bitrate) modifiedOptions.bitrate = options?.bitrate;\n if (options?.compressionMethod) {\n modifiedOptions.compressionMethod = options?.compressionMethod;\n } else {\n modifiedOptions.compressionMethod = 'manual';\n }\n if (options?.maxSize) {\n modifiedOptions.maxSize = options?.maxSize;\n } else {\n modifiedOptions.maxSize = 640;\n }\n if (options?.minimumFileSizeForCompress !== undefined) {\n modifiedOptions.minimumFileSizeForCompress =\n options?.minimumFileSizeForCompress;\n }\n if (options?.getCancellationId) {\n options?.getCancellationId(uuid);\n }\n const result = await NativeVideoCompressor.compress(\n fileUrl,\n modifiedOptions\n );\n return result;\n } finally {\n // @ts-ignore\n if (subscription) {\n subscription.remove();\n }\n }\n },\n backgroundUpload,\n cancelCompression,\n activateBackgroundTask(onExpired?) {\n if (onExpired) {\n const subscription: NativeEventSubscription =\n VideoCompressEventEmitter.addListener(\n 'backgroundTaskExpired',\n (event: any) => {\n onExpired(event);\n if (subscription) {\n subscription.remove();\n }\n }\n );\n }\n return NativeVideoCompressor.activateBackgroundTask({});\n },\n deactivateBackgroundTask() {\n VideoCompressEventEmitter.removeAllListeners('backgroundTaskExpired');\n return NativeVideoCompressor.deactivateBackgroundTask({});\n },\n} as VideoCompressorType;\n\nexport default Video;\n"]}
@@ -45,6 +45,24 @@ Object.defineProperty(exports, "uuidv4", {
45
45
  return _utils.uuidv4;
46
46
  }
47
47
  });
48
+ Object.defineProperty(exports, "generateFilePath", {
49
+ enumerable: true,
50
+ get: function () {
51
+ return _utils.generateFilePath;
52
+ }
53
+ });
54
+ Object.defineProperty(exports, "getRealPath", {
55
+ enumerable: true,
56
+ get: function () {
57
+ return _utils.getRealPath;
58
+ }
59
+ });
60
+ Object.defineProperty(exports, "getVideoMetaData", {
61
+ enumerable: true,
62
+ get: function () {
63
+ return _utils.getVideoMetaData;
64
+ }
65
+ });
48
66
  exports.default = void 0;
49
67
 
50
68
  var _Video = _interopRequireWildcard(require("./Video"));
@@ -67,7 +85,10 @@ var _default = {
67
85
  Image: _Image.default,
68
86
  backgroundUpload: _Video.backgroundUpload,
69
87
  getDetails: _utils.getDetails,
70
- uuidv4: _utils.uuidv4
88
+ uuidv4: _utils.uuidv4,
89
+ generateFilePath: _utils.generateFilePath,
90
+ getRealPath: _utils.getRealPath,
91
+ getVideoMetaData: _utils.getVideoMetaData
71
92
  };
72
93
  exports.default = _default;
73
94
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["index.tsx"],"names":["Video","Audio","Image","backgroundUpload","getDetails","uuidv4"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;AACA;;AACA;;AACA;;;;;;;;eAYe;AACbA,EAAAA,KAAK,EAALA,cADa;AAEbC,EAAAA,KAAK,EAALA,cAFa;AAGbC,EAAAA,KAAK,EAALA,cAHa;AAIbC,EAAAA,gBAAgB,EAAhBA,uBAJa;AAKbC,EAAAA,UAAU,EAAVA,iBALa;AAMbC,EAAAA,MAAM,EAANA;AANa,C","sourcesContent":["import Video, { VideoCompressorType, backgroundUpload } from './Video';\nimport Audio from './Audio';\nimport Image from './Image';\nimport { getDetails, uuidv4 } from './utils';\n\nexport {\n Video,\n Audio,\n Image,\n backgroundUpload,\n //type\n VideoCompressorType,\n getDetails,\n uuidv4,\n};\nexport default {\n Video,\n Audio,\n Image,\n backgroundUpload,\n getDetails,\n uuidv4,\n};\n"]}
1
+ {"version":3,"sources":["index.tsx"],"names":["Video","Audio","Image","backgroundUpload","getDetails","uuidv4","generateFilePath","getRealPath","getVideoMetaData"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;AACA;;AACA;;AACA;;;;;;;;eAqBe;AACbA,EAAAA,KAAK,EAALA,cADa;AAEbC,EAAAA,KAAK,EAALA,cAFa;AAGbC,EAAAA,KAAK,EAALA,cAHa;AAIbC,EAAAA,gBAAgB,EAAhBA,uBAJa;AAKbC,EAAAA,UAAU,EAAVA,iBALa;AAMbC,EAAAA,MAAM,EAANA,aANa;AAObC,EAAAA,gBAAgB,EAAhBA,uBAPa;AAQbC,EAAAA,WAAW,EAAXA,kBARa;AASbC,EAAAA,gBAAgB,EAAhBA;AATa,C","sourcesContent":["import Video, { VideoCompressorType, backgroundUpload } from './Video';\nimport Audio from './Audio';\nimport Image from './Image';\nimport {\n getDetails,\n uuidv4,\n generateFilePath,\n getRealPath,\n getVideoMetaData,\n} from './utils';\n\nexport {\n Video,\n Audio,\n Image,\n backgroundUpload,\n //type\n VideoCompressorType,\n getDetails,\n uuidv4,\n generateFilePath,\n getRealPath,\n getVideoMetaData,\n};\nexport default {\n Video,\n Audio,\n Image,\n backgroundUpload,\n getDetails,\n uuidv4,\n generateFilePath,\n getRealPath,\n getVideoMetaData,\n};\n"]}
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.uuidv4 = exports.checkUrlAndOptions = exports.getDetails = exports.DEFAULT_COMPRESS_AUDIO_OPTIONS = exports.AUDIO_BITRATE = void 0;
6
+ exports.uuidv4 = exports.checkUrlAndOptions = exports.getDetails = exports.getVideoMetaData = exports.getRealPath = exports.generateFilePath = exports.DEFAULT_COMPRESS_AUDIO_OPTIONS = exports.AUDIO_BITRATE = void 0;
7
7
 
8
8
  var _reactNative = require("react-native");
9
9
 
@@ -23,12 +23,26 @@ const DEFAULT_COMPRESS_AUDIO_OPTIONS = {
23
23
  };
24
24
  exports.DEFAULT_COMPRESS_AUDIO_OPTIONS = DEFAULT_COMPRESS_AUDIO_OPTIONS;
25
25
 
26
- const generateFile = extension => {
26
+ const generateFilePath = extension => {
27
27
  return new Promise((resolve, reject) => {
28
- Compressor.generateFile(extension).then(result => resolve('file://' + result)).catch(error => reject(error));
28
+ Compressor.generateFilePath(extension).then(result => resolve('file://' + result)).catch(error => reject(error));
29
29
  });
30
30
  };
31
31
 
32
+ exports.generateFilePath = generateFilePath;
33
+
34
+ const getRealPath = (path, type = 'video') => {
35
+ return Compressor.getRealPath(path, type);
36
+ };
37
+
38
+ exports.getRealPath = getRealPath;
39
+
40
+ const getVideoMetaData = path => {
41
+ return Compressor.getVideoMetaData(path);
42
+ };
43
+
44
+ exports.getVideoMetaData = getVideoMetaData;
45
+
32
46
  const isValidUrl = url => /^(?:\w+:)?\/\/([^\s\.]+\.\S{2}|localhost[\:?\d]*)\S*$/.test(url);
33
47
 
34
48
  const getFullFilename = path => {
@@ -120,7 +134,7 @@ const checkUrlAndOptions = async (url, options) => {
120
134
  outputFilePath = options.outputFilePath;
121
135
  defaultResult.outputFilePath = outputFilePath;
122
136
  } else {
123
- outputFilePath = await generateFile('mp3');
137
+ outputFilePath = await generateFilePath('mp3');
124
138
  defaultResult.outputFilePath = outputFilePath;
125
139
  }
126
140
 
@@ -1 +1 @@
1
- {"version":3,"sources":["index.tsx"],"names":["Compressor","NativeModules","AUDIO_BITRATE","INCORRECT_INPUT_PATH","INCORRECT_OUTPUT_PATH","ERROR_OCCUR_WHILE_GENERATING_OUTPUT_FILE","DEFAULT_COMPRESS_AUDIO_OPTIONS","bitrate","quality","outputFilePath","generateFile","extension","Promise","resolve","reject","then","result","catch","error","isValidUrl","url","test","getFullFilename","path","_path","includes","length","substring","array","split","isFileNameError","filename","getFilename","fullFilename","slice","join","isRemoteMedia","getDetails","mediaFullPath","extesnion","Error","mediaInfo","JSON","parse","mediaInformation","getMediaProperties","bit_rate","size","Number","format","e","checkUrlAndOptions","options","defaultResult","isCorrect","message","undefined","uuidv4","replace","c","r","parseFloat","Math","random","toString","Date","getTime","v"],"mappings":";;;;;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D,MAGO;AACLA,MAAAA,cAAc,GAAG,MAAMC,YAAY,CAAC,KAAD,CAAnC;AACA2C,MAAAA,aAAa,CAAC5C,cAAd,GAA+BA,cAA/B;AACD;;AACD,QAAIA,cAAc,KAAK+C,SAAnB,IAAgC/C,cAAc,KAAK,IAAvD,EAA6D;AAC3D4C,MAAAA,aAAa,CAACC,SAAd,GAA0B,KAA1B;AACAD,MAAAA,aAAa,CAACE,OAAd,GAAwBH,OAAO,CAAC3C,cAAR,GACpBL,qBADoB,GAEpBC,wCAFJ;AAGD;AACF,GAhBD,CAgBE,OAAO6C,CAAP,EAAU;AACVG,IAAAA,aAAa,CAACC,SAAd,GAA0B,KAA1B;AACAD,IAAAA,aAAa,CAACE,OAAd,GAAwBH,OAAO,CAAC3C,cAAR,GACpBL,qBADoB,GAEpBC,wCAFJ;AAGD,GArBD,SAqBU;AACR,WAAOgD,aAAP;AACD;AACF,CAzCM;;;;AA2CA,MAAMI,MAAM,GAAG,MAAM;AAC1B,SAAO,uCAAuCC,OAAvC,CAA+C,OAA/C,EAAwD,UAAUC,CAAV,EAAa;AAC1E,UAAMC,CAAC,GACFC,UAAU,CACT,OACEC,IAAI,CAACC,MAAL,GAAcC,QAAd,GAAyBN,OAAzB,CAAiC,IAAjC,EAAuC,EAAvC,CADF,GAEE,IAAIO,IAAJ,GAAWC,OAAX,EAHO,CAAV,GAKC,EALF,GAMA,CAPJ;AAAA,UAQE;AACAC,IAAAA,CAAC,GAAGR,CAAC,IAAI,GAAL,GAAWC,CAAX,GAAgBA,CAAC,GAAG,GAAL,GAAY,GATjC;AAUA,WAAOO,CAAC,CAACH,QAAF,CAAW,EAAX,CAAP;AACD,GAZM,CAAP;AAaD,CAdM","sourcesContent":["/* eslint-disable no-bitwise */\nimport { NativeModules } from 'react-native';\nconst { Compressor } = NativeModules;\nexport const AUDIO_BITRATE = [256, 192, 160, 128, 96, 64, 32];\ntype qualityType = 'low' | 'medium' | 'high';\nconst INCORRECT_INPUT_PATH = 'Incorrect input path. Please provide a valid one';\nconst INCORRECT_OUTPUT_PATH =\n 'Incorrect output path. Please provide a valid one';\nconst ERROR_OCCUR_WHILE_GENERATING_OUTPUT_FILE =\n 'An error occur while generating output file';\ntype audioCompresssionType = {\n bitrate?: number;\n quality: qualityType;\n outputFilePath?: string | undefined | null;\n};\n\nexport type defaultResultType = {\n outputFilePath: string | undefined | null;\n isCorrect: boolean;\n message: string;\n};\n\nexport const DEFAULT_COMPRESS_AUDIO_OPTIONS: audioCompresssionType = {\n bitrate: 96,\n quality: 'medium',\n outputFilePath: '',\n};\n\nexport type AudioType = {\n compress(value: string, options?: audioCompresssionType): Promise<string>;\n};\n\nconst generateFile: any = (extension: string) => {\n return new Promise((resolve, reject) => {\n Compressor.generateFile(extension)\n .then((result: any) => resolve('file://' + result))\n .catch((error: any) => reject(error));\n });\n};\n\nconst isValidUrl = (url: string) =>\n /^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$/.test(url);\n\nconst getFullFilename = (path: string | null) => {\n if (typeof path === 'string') {\n let _path = path;\n\n // In case of remote media, check if the url would be valid one\n if (path.includes('http') && !isValidUrl(path)) {\n return INCORRECT_INPUT_PATH;\n }\n\n // In case of url, check if it ends with \"/\" and do not consider it furthermore\n if (_path[_path.length - 1] === '/')\n _path = _path.substring(0, path.length - 1);\n\n const array = _path.split('/');\n return array.length > 1 ? array[array.length - 1] : INCORRECT_INPUT_PATH;\n }\n return INCORRECT_INPUT_PATH;\n};\n\nconst isFileNameError = (filename: string) => {\n return filename === INCORRECT_INPUT_PATH;\n};\n\nconst getFilename = (path: string | null) => {\n const fullFilename = getFullFilename(path);\n if (!isFileNameError(fullFilename)) {\n const array = fullFilename.split('.');\n return array.length > 1 ? array.slice(0, -1).join('') : array.join('');\n }\n return fullFilename;\n};\n\nconst isRemoteMedia = (path: string | null) => {\n return typeof path === 'string' ? path.split(':/')[0].includes('http') : null;\n};\n\nexport const getDetails = (\n mediaFullPath: string,\n extesnion: 'mp3' | 'mp4' = 'mp3'\n): Promise<any | null> => {\n return new Promise(async (resolve, reject) => {\n try {\n // Since we used \"-v error\", a work around is to call first this command before the following\n const result: any = {};\n if (result !== 0) {\n throw new Error('Failed to execute command');\n }\n\n // get the output result of the command\n // example of output {\"programs\": [], \"streams\": [{\"width\": 640,\"height\": 360}], \"format\": {\"size\": \"15804433\"}}\n let mediaInfo: any = await {};\n mediaInfo = JSON.parse(mediaInfo);\n\n // execute second command\n const mediaInformation: any = await {};\n\n // treat both results\n mediaInformation.filename = getFilename(mediaFullPath);\n mediaInformation.bitrate = mediaInformation.getMediaProperties().bit_rate;\n mediaInformation.extension = extesnion;\n mediaInformation.isRemoteMedia = isRemoteMedia(mediaFullPath);\n mediaInformation.size = Number(mediaInfo.format.size);\n\n resolve(mediaInformation);\n } catch (e) {\n reject(e);\n }\n });\n};\n\nexport const checkUrlAndOptions = async (\n url: string,\n options: audioCompresssionType\n): Promise<defaultResultType> => {\n if (!url) {\n throw new Error(\n 'Compression url is empty, please provide a url for compression.'\n );\n }\n const defaultResult: defaultResultType = {\n outputFilePath: '',\n isCorrect: true,\n message: '',\n };\n\n // Check if output file is correct\n let outputFilePath: string | undefined | null;\n try {\n // use default output file\n // or use new file from cache folder\n if (options.outputFilePath) {\n outputFilePath = options.outputFilePath;\n defaultResult.outputFilePath = outputFilePath;\n } else {\n outputFilePath = await generateFile('mp3');\n defaultResult.outputFilePath = outputFilePath;\n }\n if (outputFilePath === undefined || outputFilePath === null) {\n defaultResult.isCorrect = false;\n defaultResult.message = options.outputFilePath\n ? INCORRECT_OUTPUT_PATH\n : ERROR_OCCUR_WHILE_GENERATING_OUTPUT_FILE;\n }\n } catch (e) {\n defaultResult.isCorrect = false;\n defaultResult.message = options.outputFilePath\n ? INCORRECT_OUTPUT_PATH\n : ERROR_OCCUR_WHILE_GENERATING_OUTPUT_FILE;\n } finally {\n return defaultResult;\n }\n};\n\nexport const uuidv4 = () => {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n const r =\n (parseFloat(\n '0.' +\n Math.random().toString().replace('0.', '') +\n new Date().getTime()\n ) *\n 16) |\n 0,\n // eslint-disable-next-line eqeqeq\n v = c == 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n};\n"]}
1
+ {"version":3,"sources":["index.tsx"],"names":["Compressor","NativeModules","AUDIO_BITRATE","INCORRECT_INPUT_PATH","INCORRECT_OUTPUT_PATH","ERROR_OCCUR_WHILE_GENERATING_OUTPUT_FILE","DEFAULT_COMPRESS_AUDIO_OPTIONS","bitrate","quality","outputFilePath","generateFilePath","extension","Promise","resolve","reject","then","result","catch","error","getRealPath","path","type","getVideoMetaData","isValidUrl","url","test","getFullFilename","_path","includes","length","substring","array","split","isFileNameError","filename","getFilename","fullFilename","slice","join","isRemoteMedia","getDetails","mediaFullPath","extesnion","Error","mediaInfo","JSON","parse","mediaInformation","getMediaProperties","bit_rate","size","Number","format","e","checkUrlAndOptions","options","defaultResult","isCorrect","message","undefined","uuidv4","replace","c","r","parseFloat","Math","random","toString","Date","getTime","v"],"mappings":";;;;;;;AACA;;AADA;AAEA,MAAM;AAAEA,EAAAA;AAAF,IAAiBC,0BAAvB;AACO,MAAMC,aAAa,GAAG,CAAC,GAAD,EAAM,GAAN,EAAW,GAAX,EAAgB,GAAhB,EAAqB,EAArB,EAAyB,EAAzB,EAA6B,EAA7B,CAAtB;;AAEP,MAAMC,oBAAoB,GAAG,kDAA7B;AACA,MAAMC,qBAAqB,GACzB,mDADF;AAEA,MAAMC,wCAAwC,GAC5C,6CADF;AAcO,MAAMC,8BAAqD,GAAG;AACnEC,EAAAA,OAAO,EAAE,EAD0D;AAEnEC,EAAAA,OAAO,EAAE,QAF0D;AAGnEC,EAAAA,cAAc,EAAE;AAHmD,CAA9D;;;AAUA,MAAMC,gBAAqB,GAAIC,SAAD,IAAuB;AAC1D,SAAO,IAAIC,OAAJ,CAAY,CAACC,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AA1B;AACAD,MAAAA,aAAa,CAACE,OAAd,GAAwBH,OAAO,CAAC9C,cAAR,GACpBL,qBADoB,GAEpBC,wCAFJ;AAGD;AACF,GAhBD,CAgBE,OAAOgD,CAAP,EAAU;AACVG,IAAAA,aAAa,CAACC,SAAd,GAA0B,KAA1B;AACAD,IAAAA,aAAa,CAACE,OAAd,GAAwBH,OAAO,CAAC9C,cAAR,GACpBL,qBADoB,GAEpBC,wCAFJ;AAGD,GArBD,SAqBU;AACR,WAAOmD,aAAP;AACD;AACF,CAzCM;;;;AA2CA,MAAMI,MAAM,GAAG,MAAM;AAC1B,SAAO,uCAAuCC,OAAvC,CAA+C,OAA/C,EAAwD,UAAUC,CAAV,EAAa;AAC1E,UAAMC,CAAC,GACFC,UAAU,CACT,OACEC,IAAI,CAACC,MAAL,GAAcC,QAAd,GAAyBN,OAAzB,CAAiC,IAAjC,EAAuC,EAAvC,CADF,GAEE,IAAIO,IAAJ,GAAWC,OAAX,EAHO,CAAV,GAKC,EALF,GAMA,CAPJ;AAAA,UAQE;AACAC,IAAAA,CAAC,GAAGR,CAAC,IAAI,GAAL,GAAWC,CAAX,GAAgBA,CAAC,GAAG,GAAL,GAAY,GATjC;AAUA,WAAOO,CAAC,CAACH,QAAF,CAAW,EAAX,CAAP;AACD,GAZM,CAAP;AAaD,CAdM","sourcesContent":["/* eslint-disable no-bitwise */\nimport { NativeModules } from 'react-native';\nconst { Compressor } = NativeModules;\nexport const AUDIO_BITRATE = [256, 192, 160, 128, 96, 64, 32];\ntype qualityType = 'low' | 'medium' | 'high';\nconst INCORRECT_INPUT_PATH = 'Incorrect input path. Please provide a valid one';\nconst INCORRECT_OUTPUT_PATH =\n 'Incorrect output path. Please provide a valid one';\nconst ERROR_OCCUR_WHILE_GENERATING_OUTPUT_FILE =\n 'An error occur while generating output file';\ntype audioCompresssionType = {\n bitrate?: number;\n quality: qualityType;\n outputFilePath?: string | undefined | null;\n};\n\nexport type defaultResultType = {\n outputFilePath: string | undefined | null;\n isCorrect: boolean;\n message: string;\n};\n\nexport const DEFAULT_COMPRESS_AUDIO_OPTIONS: audioCompresssionType = {\n bitrate: 96,\n quality: 'medium',\n outputFilePath: '',\n};\n\nexport type AudioType = {\n compress(value: string, options?: audioCompresssionType): Promise<string>;\n};\n\nexport const generateFilePath: any = (extension: string) => {\n return new Promise((resolve, reject) => {\n Compressor.generateFilePath(extension)\n .then((result: any) => resolve('file://' + result))\n .catch((error: any) => reject(error));\n });\n};\n\nexport const getRealPath: any = (\n path: string,\n type: 'video' | 'imaage' = 'video'\n) => {\n return Compressor.getRealPath(path, type);\n};\n\nexport const getVideoMetaData: any = (path: string) => {\n return Compressor.getVideoMetaData(path);\n};\n\nconst isValidUrl = (url: string) =>\n /^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$/.test(url);\n\nconst getFullFilename = (path: string | null) => {\n if (typeof path === 'string') {\n let _path = path;\n\n // In case of remote media, check if the url would be valid one\n if (path.includes('http') && !isValidUrl(path)) {\n return INCORRECT_INPUT_PATH;\n }\n\n // In case of url, check if it ends with \"/\" and do not consider it furthermore\n if (_path[_path.length - 1] === '/')\n _path = _path.substring(0, path.length - 1);\n\n const array = _path.split('/');\n return array.length > 1 ? array[array.length - 1] : INCORRECT_INPUT_PATH;\n }\n return INCORRECT_INPUT_PATH;\n};\n\nconst isFileNameError = (filename: string) => {\n return filename === INCORRECT_INPUT_PATH;\n};\n\nconst getFilename = (path: string | null) => {\n const fullFilename = getFullFilename(path);\n if (!isFileNameError(fullFilename)) {\n const array = fullFilename.split('.');\n return array.length > 1 ? array.slice(0, -1).join('') : array.join('');\n }\n return fullFilename;\n};\n\nconst isRemoteMedia = (path: string | null) => {\n return typeof path === 'string' ? path.split(':/')[0].includes('http') : null;\n};\n\nexport const getDetails = (\n mediaFullPath: string,\n extesnion: 'mp3' | 'mp4' = 'mp3'\n): Promise<any | null> => {\n return new Promise(async (resolve, reject) => {\n try {\n // Since we used \"-v error\", a work around is to call first this command before the following\n const result: any = {};\n if (result !== 0) {\n throw new Error('Failed to execute command');\n }\n\n // get the output result of the command\n // example of output {\"programs\": [], \"streams\": [{\"width\": 640,\"height\": 360}], \"format\": {\"size\": \"15804433\"}}\n let mediaInfo: any = await {};\n mediaInfo = JSON.parse(mediaInfo);\n\n // execute second command\n const mediaInformation: any = await {};\n\n // treat both results\n mediaInformation.filename = getFilename(mediaFullPath);\n mediaInformation.bitrate = mediaInformation.getMediaProperties().bit_rate;\n mediaInformation.extension = extesnion;\n mediaInformation.isRemoteMedia = isRemoteMedia(mediaFullPath);\n mediaInformation.size = Number(mediaInfo.format.size);\n\n resolve(mediaInformation);\n } catch (e) {\n reject(e);\n }\n });\n};\n\nexport const checkUrlAndOptions = async (\n url: string,\n options: audioCompresssionType\n): Promise<defaultResultType> => {\n if (!url) {\n throw new Error(\n 'Compression url is empty, please provide a url for compression.'\n );\n }\n const defaultResult: defaultResultType = {\n outputFilePath: '',\n isCorrect: true,\n message: '',\n };\n\n // Check if output file is correct\n let outputFilePath: string | undefined | null;\n try {\n // use default output file\n // or use new file from cache folder\n if (options.outputFilePath) {\n outputFilePath = options.outputFilePath;\n defaultResult.outputFilePath = outputFilePath;\n } else {\n outputFilePath = await generateFilePath('mp3');\n defaultResult.outputFilePath = outputFilePath;\n }\n if (outputFilePath === undefined || outputFilePath === null) {\n defaultResult.isCorrect = false;\n defaultResult.message = options.outputFilePath\n ? INCORRECT_OUTPUT_PATH\n : ERROR_OCCUR_WHILE_GENERATING_OUTPUT_FILE;\n }\n } catch (e) {\n defaultResult.isCorrect = false;\n defaultResult.message = options.outputFilePath\n ? INCORRECT_OUTPUT_PATH\n : ERROR_OCCUR_WHILE_GENERATING_OUTPUT_FILE;\n } finally {\n return defaultResult;\n }\n};\n\nexport const uuidv4 = () => {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n const r =\n (parseFloat(\n '0.' +\n Math.random().toString().replace('0.', '') +\n new Date().getTime()\n ) *\n 16) |\n 0,\n // eslint-disable-next-line eqeqeq\n v = c == 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n};\n"]}
@@ -67,7 +67,7 @@ const Video = {
67
67
  modifiedOptions.maxSize = 640;
68
68
  }
69
69
 
70
- if (options !== null && options !== void 0 && options.minimumFileSizeForCompress) {
70
+ if ((options === null || options === void 0 ? void 0 : options.minimumFileSizeForCompress) !== undefined) {
71
71
  modifiedOptions.minimumFileSizeForCompress = options === null || options === void 0 ? void 0 : options.minimumFileSizeForCompress;
72
72
  }
73
73
 
@@ -1 +1 @@
1
- {"version":3,"sources":["index.tsx"],"names":["NativeModules","NativeEventEmitter","Platform","uuidv4","VideoCompressEventEmitter","VideoCompressor","NativeVideoCompressor","backgroundUpload","url","fileUrl","options","onProgress","uuid","subscription","addListener","event","data","written","total","OS","includes","replace","result","upload","method","httpMethod","headers","remove","cancelCompression","cancellationId","Video","compress","progress","modifiedOptions","bitrate","compressionMethod","maxSize","minimumFileSizeForCompress","getCancellationId","activateBackgroundTask","onExpired","deactivateBackgroundTask","removeAllListeners"],"mappings":"AAAA,SACEA,aADF,EAEEC,kBAFF,EAGEC,QAHF,QAKO,cALP;AAMA,SAASC,MAAT,QAAuB,UAAvB;AAgEA,MAAMC,yBAAyB,GAAG,IAAIH,kBAAJ,CAChCD,aAAa,CAACK,eADkB,CAAlC;AAIA,MAAMC,qBAAqB,GAAGN,aAAa,CAACK,eAA5C;AAEA,OAAO,MAAME,gBAAgB,GAAG,OAC9BC,GAD8B,EAE9BC,OAF8B,EAG9BC,OAH8B,EAI9BC,UAJ8B,KAKb;AACjB,QAAMC,IAAI,GAAGT,MAAM,EAAnB;AACA,MAAIU,YAAJ;;AACA,MAAI;AACF,QAAIF,UAAJ,EAAgB;AACdE,MAAAA,YAAY,GAAGT,yBAAyB,CAACU,WAA1B,CACb,yBADa,EAEZC,KAAD,IAAgB;AACd,YAAIA,KAAK,CAACH,IAAN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D;AACF;AACF,GAvDgC;AAwDjCpB,EAAAA,gBAxDiC;AAyDjCqB,EAAAA,iBAzDiC;;AA0DjCW,EAAAA,sBAAsB,CAACC,SAAD,EAAa;AACjC,QAAIA,SAAJ,EAAe;AACb,YAAM3B,YAAqC,GACzCT,yBAAyB,CAACU,WAA1B,CACE,uBADF,EAEGC,KAAD,IAAgB;AACdyB,QAAAA,SAAS,CAACzB,KAAD,CAAT;;AACA,YAAIF,YAAJ,EAAkB;AAChBA,UAAAA,YAAY,CAACc,MAAb;AACD;AACF,OAPH,CADF;AAUD;;AACD,WAAOrB,qBAAqB,CAACiC,sBAAtB,CAA6C,EAA7C,CAAP;AACD,GAxEgC;;AAyEjCE,EAAAA,wBAAwB,GAAG;AACzBrC,IAAAA,yBAAyB,CAACsC,kBAA1B,CAA6C,uBAA7C;AACA,WAAOpC,qBAAqB,CAACmC,wBAAtB,CAA+C,EAA/C,CAAP;AACD;;AA5EgC,CAAnC;AA+EA,eAAeX,KAAf","sourcesContent":["import {\n NativeModules,\n NativeEventEmitter,\n Platform,\n NativeEventSubscription,\n} from 'react-native';\nimport { uuidv4 } from '../utils';\n\nexport declare enum FileSystemUploadType {\n BINARY_CONTENT = 0,\n MULTIPART = 1,\n}\n\nexport declare type FileSystemAcceptedUploadHttpMethod =\n | 'POST'\n | 'PUT'\n | 'PATCH';\nexport type compressionMethod = 'auto' | 'manual';\ntype videoCompresssionType = {\n bitrate?: number;\n maxSize?: number;\n compressionMethod?: compressionMethod;\n minimumFileSizeForCompress?: number;\n getCancellationId?: (cancellationId: string) => void;\n};\n\nexport declare enum FileSystemSessionType {\n BACKGROUND = 0,\n FOREGROUND = 1,\n}\n\nexport declare type HTTPResponse = {\n status: number;\n headers: Record<string, string>;\n body: string;\n};\n\nexport declare type FileSystemUploadOptions = (\n | {\n uploadType?: FileSystemUploadType.BINARY_CONTENT;\n }\n | {\n uploadType: FileSystemUploadType.MULTIPART;\n fieldName?: string;\n mimeType?: string;\n parameters?: Record<string, string>;\n }\n) & {\n headers?: Record<string, string>;\n httpMethod?: FileSystemAcceptedUploadHttpMethod;\n sessionType?: FileSystemSessionType;\n};\n\nexport type VideoCompressorType = {\n compress(\n fileUrl: string,\n options?: videoCompresssionType,\n onProgress?: (progress: number) => void\n ): Promise<string>;\n cancelCompression(cancellationId: string): void;\n backgroundUpload(\n url: string,\n fileUrl: string,\n options: FileSystemUploadOptions,\n onProgress?: (writtem: number, total: number) => void\n ): Promise<any>;\n activateBackgroundTask(onExpired?: (data: any) => void): Promise<any>;\n deactivateBackgroundTask(): Promise<any>;\n};\n\nconst VideoCompressEventEmitter = new NativeEventEmitter(\n NativeModules.VideoCompressor\n);\n\nconst NativeVideoCompressor = NativeModules.VideoCompressor;\n\nexport const backgroundUpload = async (\n url: string,\n fileUrl: string,\n options: FileSystemUploadOptions,\n onProgress?: (writtem: number, total: number) => void\n): Promise<any> => {\n const uuid = uuidv4();\n let subscription: NativeEventSubscription;\n try {\n if (onProgress) {\n subscription = VideoCompressEventEmitter.addListener(\n 'VideoCompressorProgress',\n (event: any) => {\n if (event.uuid === uuid) {\n onProgress(event.data.written, event.data.total);\n }\n }\n );\n }\n if (Platform.OS === 'android' && fileUrl.includes('file://')) {\n fileUrl = fileUrl.replace('file://', '');\n }\n const result = await NativeVideoCompressor.upload(fileUrl, {\n uuid,\n method: options.httpMethod,\n headers: options.headers,\n url,\n });\n return result;\n } finally {\n // @ts-ignore\n if (subscription) {\n subscription.remove();\n }\n }\n};\n\nexport const cancelCompression = (cancellationId: string) => {\n return NativeVideoCompressor.cancelCompression(cancellationId);\n};\n\nconst Video: VideoCompressorType = {\n compress: async (\n fileUrl: string,\n options?: videoCompresssionType,\n onProgress?: (progress: number) => void\n ) => {\n const uuid = uuidv4();\n let subscription: NativeEventSubscription;\n try {\n if (onProgress) {\n subscription = VideoCompressEventEmitter.addListener(\n 'videoCompressProgress',\n (event: any) => {\n if (event.uuid === uuid) {\n onProgress(event.data.progress);\n }\n }\n );\n }\n const modifiedOptions: {\n uuid: string;\n bitrate?: number;\n compressionMethod?: compressionMethod;\n maxSize?: number;\n minimumFileSizeForCompress?: number;\n } = { uuid };\n if (options?.bitrate) modifiedOptions.bitrate = options?.bitrate;\n if (options?.compressionMethod) {\n modifiedOptions.compressionMethod = options?.compressionMethod;\n } else {\n modifiedOptions.compressionMethod = 'manual';\n }\n if (options?.maxSize) {\n modifiedOptions.maxSize = options?.maxSize;\n } else {\n modifiedOptions.maxSize = 640;\n }\n if (options?.minimumFileSizeForCompress) {\n modifiedOptions.minimumFileSizeForCompress =\n options?.minimumFileSizeForCompress;\n }\n if (options?.getCancellationId) {\n options?.getCancellationId(uuid);\n }\n const result = await NativeVideoCompressor.compress(\n fileUrl,\n modifiedOptions\n );\n return result;\n } finally {\n // @ts-ignore\n if (subscription) {\n subscription.remove();\n }\n }\n },\n backgroundUpload,\n cancelCompression,\n activateBackgroundTask(onExpired?) {\n if (onExpired) {\n const subscription: NativeEventSubscription =\n VideoCompressEventEmitter.addListener(\n 'backgroundTaskExpired',\n (event: any) => {\n onExpired(event);\n if (subscription) {\n subscription.remove();\n }\n }\n );\n }\n return NativeVideoCompressor.activateBackgroundTask({});\n },\n deactivateBackgroundTask() {\n VideoCompressEventEmitter.removeAllListeners('backgroundTaskExpired');\n return NativeVideoCompressor.deactivateBackgroundTask({});\n },\n} as VideoCompressorType;\n\nexport default Video;\n"]}
1
+ {"version":3,"sources":["index.tsx"],"names":["NativeModules","NativeEventEmitter","Platform","uuidv4","VideoCompressEventEmitter","VideoCompressor","NativeVideoCompressor","backgroundUpload","url","fileUrl","options","onProgress","uuid","subscription","addListener","event","data","written","total","OS","includes","replace","result","upload","method","httpMethod","headers","remove","cancelCompression","cancellationId","Video","compress","progress","modifiedOptions","bitrate","compressionMethod","maxSize","minimumFileSizeForCompress","undefined","getCancellationId","activateBackgroundTask","onExpired","deactivateBackgroundTask","removeAllListeners"],"mappings":"AAAA,SACEA,aADF,EAEEC,kBAFF,EAGEC,QAHF,QAKO,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O,CAAE2B,0BAAT,MAAwCC,SAA5C,EAAuD;AACrDL,QAAAA,eAAe,CAACI,0BAAhB,GACE3B,OADF,aACEA,OADF,uBACEA,OAAO,CAAE2B,0BADX;AAED;;AACD,UAAI3B,OAAJ,aAAIA,OAAJ,eAAIA,OAAO,CAAE6B,iBAAb,EAAgC;AAC9B7B,QAAAA,OAAO,SAAP,IAAAA,OAAO,WAAP,YAAAA,OAAO,CAAE6B,iBAAT,CAA2B3B,IAA3B;AACD;;AACD,YAAMU,MAAM,GAAG,MAAMhB,qBAAqB,CAACyB,QAAtB,CACnBtB,OADmB,EAEnBwB,eAFmB,CAArB;AAIA,aAAOX,MAAP;AACD,KAzCD,SAyCU;AACR;AACA,UAAIT,YAAJ,EAAkB;AAChBA,QAAAA,YAAY,CAACc,MAAb;AACD;AACF;AACF,GAvDgC;AAwDjCpB,EAAAA,gBAxDiC;AAyDjCqB,EAAAA,iBAzDiC;;AA0DjCY,EAAAA,sBAAsB,CAACC,SAAD,EAAa;AACjC,QAAIA,SAAJ,EAAe;AACb,YAAM5B,YAAqC,GACzCT,yBAAyB,CAACU,WAA1B,CACE,uBADF,EAEGC,KAAD,IAAgB;AACd0B,QAAAA,SAAS,CAAC1B,KAAD,CAAT;;AACA,YAAIF,YAAJ,EAAkB;AAChBA,UAAAA,YAAY,CAACc,MAAb;AACD;AACF,OAPH,CADF;AAUD;;AACD,WAAOrB,qBAAqB,CAACkC,sBAAtB,CAA6C,EAA7C,CAAP;AACD,GAxEgC;;AAyEjCE,EAAAA,wBAAwB,GAAG;AACzBtC,IAAAA,yBAAyB,CAACuC,kBAA1B,CAA6C,uBAA7C;AACA,WAAOrC,qBAAqB,CAACoC,wBAAtB,CAA+C,EAA/C,CAAP;AACD;;AA5EgC,CAAnC;AA+EA,eAAeZ,KAAf","sourcesContent":["import {\n NativeModules,\n NativeEventEmitter,\n Platform,\n NativeEventSubscription,\n} from 'react-native';\nimport { uuidv4 } from '../utils';\n\nexport declare enum FileSystemUploadType {\n BINARY_CONTENT = 0,\n MULTIPART = 1,\n}\n\nexport declare type FileSystemAcceptedUploadHttpMethod =\n | 'POST'\n | 'PUT'\n | 'PATCH';\nexport type compressionMethod = 'auto' | 'manual';\ntype videoCompresssionType = {\n bitrate?: number;\n maxSize?: number;\n compressionMethod?: compressionMethod;\n minimumFileSizeForCompress?: number;\n getCancellationId?: (cancellationId: string) => void;\n};\n\nexport declare enum FileSystemSessionType {\n BACKGROUND = 0,\n FOREGROUND = 1,\n}\n\nexport declare type HTTPResponse = {\n status: number;\n headers: Record<string, string>;\n body: string;\n};\n\nexport declare type FileSystemUploadOptions = (\n | {\n uploadType?: FileSystemUploadType.BINARY_CONTENT;\n }\n | {\n uploadType: FileSystemUploadType.MULTIPART;\n fieldName?: string;\n mimeType?: string;\n parameters?: Record<string, string>;\n }\n) & {\n headers?: Record<string, string>;\n httpMethod?: FileSystemAcceptedUploadHttpMethod;\n sessionType?: FileSystemSessionType;\n};\n\nexport type VideoCompressorType = {\n compress(\n fileUrl: string,\n options?: videoCompresssionType,\n onProgress?: (progress: number) => void\n ): Promise<string>;\n cancelCompression(cancellationId: string): void;\n backgroundUpload(\n url: string,\n fileUrl: string,\n options: FileSystemUploadOptions,\n onProgress?: (writtem: number, total: number) => void\n ): Promise<any>;\n activateBackgroundTask(onExpired?: (data: any) => void): Promise<any>;\n deactivateBackgroundTask(): Promise<any>;\n};\n\nconst VideoCompressEventEmitter = new NativeEventEmitter(\n NativeModules.VideoCompressor\n);\n\nconst NativeVideoCompressor = NativeModules.VideoCompressor;\n\nexport const backgroundUpload = async (\n url: string,\n fileUrl: string,\n options: FileSystemUploadOptions,\n onProgress?: (writtem: number, total: number) => void\n): Promise<any> => {\n const uuid = uuidv4();\n let subscription: NativeEventSubscription;\n try {\n if (onProgress) {\n subscription = VideoCompressEventEmitter.addListener(\n 'VideoCompressorProgress',\n (event: any) => {\n if (event.uuid === uuid) {\n onProgress(event.data.written, event.data.total);\n }\n }\n );\n }\n if (Platform.OS === 'android' && fileUrl.includes('file://')) {\n fileUrl = fileUrl.replace('file://', '');\n }\n const result = await NativeVideoCompressor.upload(fileUrl, {\n uuid,\n method: options.httpMethod,\n headers: options.headers,\n url,\n });\n return result;\n } finally {\n // @ts-ignore\n if (subscription) {\n subscription.remove();\n }\n }\n};\n\nexport const cancelCompression = (cancellationId: string) => {\n return NativeVideoCompressor.cancelCompression(cancellationId);\n};\n\nconst Video: VideoCompressorType = {\n compress: async (\n fileUrl: string,\n options?: videoCompresssionType,\n onProgress?: (progress: number) => void\n ) => {\n const uuid = uuidv4();\n let subscription: NativeEventSubscription;\n try {\n if (onProgress) {\n subscription = VideoCompressEventEmitter.addListener(\n 'videoCompressProgress',\n (event: any) => {\n if (event.uuid === uuid) {\n onProgress(event.data.progress);\n }\n }\n );\n }\n const modifiedOptions: {\n uuid: string;\n bitrate?: number;\n compressionMethod?: compressionMethod;\n maxSize?: number;\n minimumFileSizeForCompress?: number;\n } = { uuid };\n if (options?.bitrate) modifiedOptions.bitrate = options?.bitrate;\n if (options?.compressionMethod) {\n modifiedOptions.compressionMethod = options?.compressionMethod;\n } else {\n modifiedOptions.compressionMethod = 'manual';\n }\n if (options?.maxSize) {\n modifiedOptions.maxSize = options?.maxSize;\n } else {\n modifiedOptions.maxSize = 640;\n }\n if (options?.minimumFileSizeForCompress !== undefined) {\n modifiedOptions.minimumFileSizeForCompress =\n options?.minimumFileSizeForCompress;\n }\n if (options?.getCancellationId) {\n options?.getCancellationId(uuid);\n }\n const result = await NativeVideoCompressor.compress(\n fileUrl,\n modifiedOptions\n );\n return result;\n } finally {\n // @ts-ignore\n if (subscription) {\n subscription.remove();\n }\n }\n },\n backgroundUpload,\n cancelCompression,\n activateBackgroundTask(onExpired?) {\n if (onExpired) {\n const subscription: NativeEventSubscription =\n VideoCompressEventEmitter.addListener(\n 'backgroundTaskExpired',\n (event: any) => {\n onExpired(event);\n if (subscription) {\n subscription.remove();\n }\n }\n );\n }\n return NativeVideoCompressor.activateBackgroundTask({});\n },\n deactivateBackgroundTask() {\n VideoCompressEventEmitter.removeAllListeners('backgroundTaskExpired');\n return NativeVideoCompressor.deactivateBackgroundTask({});\n },\n} as VideoCompressorType;\n\nexport default Video;\n"]}
@@ -1,15 +1,18 @@
1
1
  import Video, { VideoCompressorType, backgroundUpload } from './Video';
2
2
  import Audio from './Audio';
3
3
  import Image from './Image';
4
- import { getDetails, uuidv4 } from './utils';
4
+ import { getDetails, uuidv4, generateFilePath, getRealPath, getVideoMetaData } from './utils';
5
5
  export { Video, Audio, Image, backgroundUpload //type
6
- , VideoCompressorType, getDetails, uuidv4 };
6
+ , VideoCompressorType, getDetails, uuidv4, generateFilePath, getRealPath, getVideoMetaData };
7
7
  export default {
8
8
  Video,
9
9
  Audio,
10
10
  Image,
11
11
  backgroundUpload,
12
12
  getDetails,
13
- uuidv4
13
+ uuidv4,
14
+ generateFilePath,
15
+ getRealPath,
16
+ getVideoMetaData
14
17
  };
15
18
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["index.tsx"],"names":["Video","VideoCompressorType","backgroundUpload","Audio","Image","getDetails","uuidv4"],"mappings":"AAAA,OAAOA,KAAP,IAAgBC,mBAAhB,EAAqCC,gBAArC,QAA6D,SAA7D;AACA,OAAOC,KAAP,MAAkB,SAAlB;AACA,OAAOC,KAAP,MAAkB,SAAlB;AACA,SAASC,UAAT,EAAqBC,MAArB,QAAmC,SAAnC;AAEA,SACEN,KADF,EAEEG,KAFF,EAGEC,KAHF,EAIEF,gBAJF,CAKE;AALF,EAMED,mBANF,EAOEI,UAPF,EAQEC,MARF;AAUA,eAAe;AACbN,EAAAA,KADa;AAEbG,EAAAA,KAFa;AAGbC,EAAAA,KAHa;AAIbF,EAAAA,gBAJa;AAKbG,EAAAA,UALa;AAMbC,EAAAA;AANa,CAAf","sourcesContent":["import Video, { VideoCompressorType, backgroundUpload } from './Video';\nimport Audio from './Audio';\nimport Image from './Image';\nimport { getDetails, uuidv4 } from './utils';\n\nexport {\n Video,\n Audio,\n Image,\n backgroundUpload,\n //type\n VideoCompressorType,\n getDetails,\n uuidv4,\n};\nexport default {\n Video,\n Audio,\n Image,\n backgroundUpload,\n getDetails,\n uuidv4,\n};\n"]}
1
+ {"version":3,"sources":["index.tsx"],"names":["Video","VideoCompressorType","backgroundUpload","Audio","Image","getDetails","uuidv4","generateFilePath","getRealPath","getVideoMetaData"],"mappings":"AAAA,OAAOA,KAAP,IAAgBC,mBAAhB,EAAqCC,gBAArC,QAA6D,SAA7D;AACA,OAAOC,KAAP,MAAkB,SAAlB;AACA,OAAOC,KAAP,MAAkB,SAAlB;AACA,SACEC,UADF,EAEEC,MAFF,EAGEC,gBAHF,EAIEC,WAJF,EAKEC,gBALF,QAMO,SANP;AAQA,SACET,KADF,EAEEG,KAFF,EAGEC,KAHF,EAIEF,gBAJF,CAKE;AALF,EAMED,mBANF,EAOEI,UAPF,EAQEC,MARF,EASEC,gBATF,EAUEC,WAVF,EAWEC,gBAXF;AAaA,eAAe;AACbT,EAAAA,KADa;AAEbG,EAAAA,KAFa;AAGbC,EAAAA,KAHa;AAIbF,EAAAA,gBAJa;AAKbG,EAAAA,UALa;AAMbC,EAAAA,MANa;AAObC,EAAAA,gBAPa;AAQbC,EAAAA,WARa;AASbC,EAAAA;AATa,CAAf","sourcesContent":["import Video, { VideoCompressorType, backgroundUpload } from './Video';\nimport Audio from './Audio';\nimport Image from './Image';\nimport {\n getDetails,\n uuidv4,\n generateFilePath,\n getRealPath,\n getVideoMetaData,\n} from './utils';\n\nexport {\n Video,\n Audio,\n Image,\n backgroundUpload,\n //type\n VideoCompressorType,\n getDetails,\n uuidv4,\n generateFilePath,\n getRealPath,\n getVideoMetaData,\n};\nexport default {\n Video,\n Audio,\n Image,\n backgroundUpload,\n getDetails,\n uuidv4,\n generateFilePath,\n getRealPath,\n getVideoMetaData,\n};\n"]}
@@ -12,12 +12,17 @@ export const DEFAULT_COMPRESS_AUDIO_OPTIONS = {
12
12
  quality: 'medium',
13
13
  outputFilePath: ''
14
14
  };
15
-
16
- const generateFile = extension => {
15
+ export const generateFilePath = extension => {
17
16
  return new Promise((resolve, reject) => {
18
- Compressor.generateFile(extension).then(result => resolve('file://' + result)).catch(error => reject(error));
17
+ Compressor.generateFilePath(extension).then(result => resolve('file://' + result)).catch(error => reject(error));
19
18
  });
20
19
  };
20
+ export const getRealPath = (path, type = 'video') => {
21
+ return Compressor.getRealPath(path, type);
22
+ };
23
+ export const getVideoMetaData = path => {
24
+ return Compressor.getVideoMetaData(path);
25
+ };
21
26
 
22
27
  const isValidUrl = url => /^(?:\w+:)?\/\/([^\s\.]+\.\S{2}|localhost[\:?\d]*)\S*$/.test(url);
23
28
 
@@ -107,7 +112,7 @@ export const checkUrlAndOptions = async (url, options) => {
107
112
  outputFilePath = options.outputFilePath;
108
113
  defaultResult.outputFilePath = outputFilePath;
109
114
  } else {
110
- outputFilePath = await generateFile('mp3');
115
+ outputFilePath = await generateFilePath('mp3');
111
116
  defaultResult.outputFilePath = outputFilePath;
112
117
  }
113
118