chore: lint project (#3395)

* chore: format swift code
* chore: format clang code
* chore: format kotlin code
* refactor: rename folder "API" to "api"
This commit is contained in:
Krzysztof Moch
2023-12-07 08:47:40 +01:00
committed by GitHub
parent 72679a7d63
commit 800aee09de
43 changed files with 1407 additions and 1364 deletions

View File

@@ -1,8 +1,8 @@
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
#import <CommonCrypto/CommonDigest.h>
#import <Foundation/Foundation.h>
#import <SPTPersistentCache/SPTPersistentCache.h>
#import <SPTPersistentCache/SPTPersistentCacheOptions.h>
#import <CommonCrypto/CommonDigest.h>
typedef NS_ENUM(NSUInteger, RCTVideoCacheStatus) {
RCTVideoCacheStatusMissingFileExtension,
@@ -14,25 +14,24 @@ typedef NS_ENUM(NSUInteger, RCTVideoCacheStatus) {
@class SPTPersistentCache;
@class SPTPersistentCacheOptions;
@interface RCTVideoCache : NSObject
{
SPTPersistentCache *videoCache;
NSString * _Nullable cachePath;
NSString * temporaryCachePath;
NSString * _Nullable cacheIdentifier;
@interface RCTVideoCache : NSObject {
SPTPersistentCache* videoCache;
NSString* _Nullable cachePath;
NSString* temporaryCachePath;
NSString* _Nullable cacheIdentifier;
}
@property(nonatomic, strong) SPTPersistentCache * _Nullable videoCache;
@property(nonatomic, strong) NSString * cachePath;
@property(nonatomic, strong) NSString * cacheIdentifier;
@property(nonatomic, strong) NSString * temporaryCachePath;
@property(nonatomic, strong) SPTPersistentCache* _Nullable videoCache;
@property(nonatomic, strong) NSString* cachePath;
@property(nonatomic, strong) NSString* cacheIdentifier;
@property(nonatomic, strong) NSString* temporaryCachePath;
+ (RCTVideoCache *)sharedInstance;
- (void)storeItem:(NSData *)data forUri:(NSString *)uri withCallback:(void(^)(BOOL))handler;
- (void)getItemForUri:(NSString *)url withCallback:(void(^)(RCTVideoCacheStatus, AVAsset * _Nullable)) handler;
- (NSURL *)createUniqueTemporaryFileUrl:(NSString * _Nonnull)url withExtension:(NSString * _Nonnull) extension;
- (AVURLAsset *)getItemFromTemporaryStorage:(NSString *)key;
- (BOOL)saveDataToTemporaryStorage:(NSData *)data key:(NSString *)key;
- (void) createTemporaryPath;
+ (RCTVideoCache*)sharedInstance;
- (void)storeItem:(NSData*)data forUri:(NSString*)uri withCallback:(void (^)(BOOL))handler;
- (void)getItemForUri:(NSString*)url withCallback:(void (^)(RCTVideoCacheStatus, AVAsset* _Nullable))handler;
- (NSURL*)createUniqueTemporaryFileUrl:(NSString* _Nonnull)url withExtension:(NSString* _Nonnull)extension;
- (AVURLAsset*)getItemFromTemporaryStorage:(NSString*)key;
- (BOOL)saveDataToTemporaryStorage:(NSData*)data key:(NSString*)key;
- (void)createTemporaryPath;
@end

View File

@@ -7,8 +7,8 @@
@synthesize cacheIdentifier;
@synthesize temporaryCachePath;
+ (RCTVideoCache *)sharedInstance {
static RCTVideoCache *sharedInstance = nil;
+ (RCTVideoCache*)sharedInstance {
static RCTVideoCache* sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
@@ -20,8 +20,9 @@
if (self = [super init]) {
self.cacheIdentifier = @"rct.video.cache";
self.temporaryCachePath = [NSTemporaryDirectory() stringByAppendingPathComponent:self.cacheIdentifier];
self.cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:self.cacheIdentifier];
SPTPersistentCacheOptions *options = [SPTPersistentCacheOptions new];
self.cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject
stringByAppendingPathComponent:self.cacheIdentifier];
SPTPersistentCacheOptions* options = [SPTPersistentCacheOptions new];
options.cachePath = self.cachePath;
options.cacheIdentifier = self.cacheIdentifier;
options.defaultExpirationPeriod = 60 * 60 * 24 * 30;
@@ -29,7 +30,7 @@
options.sizeConstraintBytes = 1024 * 1024 * 100;
options.useDirectorySeparation = NO;
#ifdef DEBUG
options.debugOutput = ^(NSString *string) {
options.debugOutput = ^(NSString* string) {
NSLog(@"VideoCache: debug %@", string);
};
#endif
@@ -40,8 +41,8 @@
return self;
}
- (void) createTemporaryPath {
NSError *error = nil;
- (void)createTemporaryPath {
NSError* error = nil;
BOOL success = [[NSFileManager defaultManager] createDirectoryAtPath:self.temporaryCachePath
withIntermediateDirectories:YES
attributes:nil
@@ -53,97 +54,101 @@
#endif
}
- (void)storeItem:(NSData *)data forUri:(NSString *)uri withCallback:(void(^)(BOOL))handler;
- (void)storeItem:(NSData*)data forUri:(NSString*)uri withCallback:(void (^)(BOOL))handler;
{
NSString *key = [self generateCacheKeyForUri:uri];
NSString* key = [self generateCacheKeyForUri:uri];
if (key == nil) {
handler(NO);
return;
}
[self saveDataToTemporaryStorage:data key:key];
[self.videoCache storeData:data forKey:key locked:NO withCallback:^(SPTPersistentCacheResponse * _Nonnull response) {
if (response.error) {
[self.videoCache storeData:data
forKey:key
locked:NO
withCallback:^(SPTPersistentCacheResponse* _Nonnull response) {
if (response.error) {
#ifdef DEBUG
NSLog(@"VideoCache: An error occured while saving the video into the cache: %@", [response.error localizedDescription]);
NSLog(@"VideoCache: An error occured while saving the video into the cache: %@", [response.error localizedDescription]);
#endif
handler(NO);
return;
}
handler(YES);
} onQueue:dispatch_get_main_queue()];
handler(NO);
return;
}
handler(YES);
}
onQueue:dispatch_get_main_queue()];
return;
}
- (AVURLAsset *)getItemFromTemporaryStorage:(NSString *)key {
NSString * temporaryFilePath = [self.temporaryCachePath stringByAppendingPathComponent:key];
- (AVURLAsset*)getItemFromTemporaryStorage:(NSString*)key {
NSString* temporaryFilePath = [self.temporaryCachePath stringByAppendingPathComponent:key];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:temporaryFilePath];
if (!fileExists) {
return nil;
}
NSURL *assetUrl = [[NSURL alloc] initFileURLWithPath:temporaryFilePath];
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:assetUrl options:nil];
NSURL* assetUrl = [[NSURL alloc] initFileURLWithPath:temporaryFilePath];
AVURLAsset* asset = [AVURLAsset URLAssetWithURL:assetUrl options:nil];
return asset;
}
- (BOOL)saveDataToTemporaryStorage:(NSData *)data key:(NSString *)key {
NSString *temporaryFilePath = [self.temporaryCachePath stringByAppendingPathComponent:key];
- (BOOL)saveDataToTemporaryStorage:(NSData*)data key:(NSString*)key {
NSString* temporaryFilePath = [self.temporaryCachePath stringByAppendingPathComponent:key];
[data writeToFile:temporaryFilePath atomically:YES];
return YES;
}
- (NSString *)generateCacheKeyForUri:(NSString *)uri {
NSString *uriWithoutQueryParams = uri;
- (NSString*)generateCacheKeyForUri:(NSString*)uri {
NSString* uriWithoutQueryParams = uri;
// parse file extension
if ([uri rangeOfString:@"?"].location != NSNotFound) {
NSArray<NSString*> * components = [uri componentsSeparatedByString:@"?"];
NSArray<NSString*>* components = [uri componentsSeparatedByString:@"?"];
uriWithoutQueryParams = [components objectAtIndex:0];
}
NSString * pathExtension = [uriWithoutQueryParams pathExtension];
NSArray * supportedExtensions = @[@"m4v", @"mp4", @"mov"];
NSString* pathExtension = [uriWithoutQueryParams pathExtension];
NSArray* supportedExtensions = @[ @"m4v", @"mp4", @"mov" ];
if ([pathExtension isEqualToString:@""]) {
NSDictionary *userInfo = @{
NSLocalizedDescriptionKey: NSLocalizedString(@"Missing file extension.", nil),
NSLocalizedFailureReasonErrorKey: NSLocalizedString(@"Missing file extension.", nil),
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Missing file extension.", nil)
};
NSError *error = [NSError errorWithDomain:@"RCTVideoCache"
code:RCTVideoCacheStatusMissingFileExtension userInfo:userInfo];
NSDictionary* userInfo = @{
NSLocalizedDescriptionKey : NSLocalizedString(@"Missing file extension.", nil),
NSLocalizedFailureReasonErrorKey : NSLocalizedString(@"Missing file extension.", nil),
NSLocalizedRecoverySuggestionErrorKey : NSLocalizedString(@"Missing file extension.", nil)
};
NSError* error = [NSError errorWithDomain:@"RCTVideoCache" code:RCTVideoCacheStatusMissingFileExtension userInfo:userInfo];
@throw error;
} else if (![supportedExtensions containsObject:pathExtension]) {
// Notably, we don't currently support m3u8 (HLS playlists)
NSDictionary *userInfo = @{
NSLocalizedDescriptionKey: NSLocalizedString(@"Unsupported file extension.", nil),
NSLocalizedFailureReasonErrorKey: NSLocalizedString(@"Unsupported file extension.", nil),
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Unsupported file extension.", nil)
};
NSError *error = [NSError errorWithDomain:@"RCTVideoCache"
code:RCTVideoCacheStatusUnsupportedFileExtension userInfo:userInfo];
NSDictionary* userInfo = @{
NSLocalizedDescriptionKey : NSLocalizedString(@"Unsupported file extension.", nil),
NSLocalizedFailureReasonErrorKey : NSLocalizedString(@"Unsupported file extension.", nil),
NSLocalizedRecoverySuggestionErrorKey : NSLocalizedString(@"Unsupported file extension.", nil)
};
NSError* error = [NSError errorWithDomain:@"RCTVideoCache" code:RCTVideoCacheStatusUnsupportedFileExtension userInfo:userInfo];
@throw error;
}
return [[self generateHashForUrl:uri] stringByAppendingPathExtension:pathExtension];
}
- (void)getItemForUri:(NSString *)uri withCallback:(void(^)(RCTVideoCacheStatus, AVAsset * _Nullable)) handler {
- (void)getItemForUri:(NSString*)uri withCallback:(void (^)(RCTVideoCacheStatus, AVAsset* _Nullable))handler {
@try {
NSString *key = [self generateCacheKeyForUri:uri];
AVURLAsset * temporaryAsset = [self getItemFromTemporaryStorage:key];
NSString* key = [self generateCacheKeyForUri:uri];
AVURLAsset* temporaryAsset = [self getItemFromTemporaryStorage:key];
if (temporaryAsset != nil) {
handler(RCTVideoCacheStatusAvailable, temporaryAsset);
return;
}
[self.videoCache loadDataForKey:key withCallback:^(SPTPersistentCacheResponse * _Nonnull response) {
if (response.record == nil || response.record.data == nil) {
handler(RCTVideoCacheStatusNotAvailable, nil);
return;
}
[self saveDataToTemporaryStorage:response.record.data key:key];
handler(RCTVideoCacheStatusAvailable, [self getItemFromTemporaryStorage:key]);
} onQueue:dispatch_get_main_queue()];
} @catch (NSError * err) {
[self.videoCache loadDataForKey:key
withCallback:^(SPTPersistentCacheResponse* _Nonnull response) {
if (response.record == nil || response.record.data == nil) {
handler(RCTVideoCacheStatusNotAvailable, nil);
return;
}
[self saveDataToTemporaryStorage:response.record.data key:key];
handler(RCTVideoCacheStatusAvailable, [self getItemFromTemporaryStorage:key]);
}
onQueue:dispatch_get_main_queue()];
} @catch (NSError* err) {
switch (err.code) {
case RCTVideoCacheStatusMissingFileExtension:
handler(RCTVideoCacheStatusMissingFileExtension, nil);
@@ -157,18 +162,14 @@
}
}
- (NSString *)generateHashForUrl:(NSString *)string {
const char *cStr = [string UTF8String];
- (NSString*)generateHashForUrl:(NSString*)string {
const char* cStr = [string UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5( cStr, (CC_LONG)strlen(cStr), result );
return [NSString stringWithFormat:
@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
];
CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
return [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", result[0], result[1], result[2],
result[3], result[4], result[5], result[6], result[7], result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]];
}
@end

View File

@@ -1,87 +1,97 @@
import Foundation
import AVFoundation
import DVAssetLoaderDelegate
import Foundation
import Promises
class RCTVideoCachingHandler: NSObject, DVAssetLoaderDelegatesDelegate {
private var _videoCache:RCTVideoCache! = RCTVideoCache.sharedInstance()
private var _videoCache: RCTVideoCache! = RCTVideoCache.sharedInstance()
var playerItemPrepareText: ((AVAsset?, NSDictionary?, String) -> AVPlayerItem)?
override init() {
super.init()
}
func shouldCache(source: VideoSource, textTracks:[TextTrack]?) -> Bool {
if source.isNetwork && source.shouldCache && ((textTracks == nil) || (textTracks!.count == 0)) {
func shouldCache(source: VideoSource, textTracks: [TextTrack]?) -> Bool {
if source.isNetwork && source.shouldCache && ((textTracks == nil) || (textTracks!.isEmpty)) {
/* The DVURLAsset created by cache doesn't have a tracksWithMediaType property, so trying
* to bring in the text track code will crash. I suspect this is because the asset hasn't fully loaded.
* Until this is fixed, we need to bypass caching when text tracks are specified.
*/
DebugLog("Caching is not supported for uri '\(source.uri)' because text tracks are not compatible with the cache. Checkout https://github.com/react-native-community/react-native-video/blob/master/docs/caching.md")
DebugLog("""
Caching is not supported for uri '\(source.uri)' because text tracks are not compatible with the cache.
Checkout https://github.com/react-native-community/react-native-video/blob/master/docs/caching.md
""")
return true
}
return false
}
func playerItemForSourceUsingCache(uri:String!, assetOptions options:NSDictionary!) -> Promise<AVPlayerItem?> {
func playerItemForSourceUsingCache(uri: String!, assetOptions options: NSDictionary!) -> Promise<AVPlayerItem?> {
let url = URL(string: uri)
return getItemForUri(uri)
.then{ [weak self] (videoCacheStatus:RCTVideoCacheStatus,cachedAsset:AVAsset?) -> AVPlayerItem in
guard let self = self, let playerItemPrepareText = self.playerItemPrepareText else {throw NSError(domain: "", code: 0, userInfo: nil)}
switch (videoCacheStatus) {
case .missingFileExtension:
DebugLog("Could not generate cache key for uri '\(uri)'. It is currently not supported to cache urls that do not include a file extension. The video file will not be cached. Checkout https://github.com/react-native-community/react-native-video/blob/master/docs/caching.md")
let asset:AVURLAsset! = AVURLAsset(url: url!, options:options as! [String : Any])
return playerItemPrepareText(asset, options, "")
case .unsupportedFileExtension:
DebugLog("Could not generate cache key for uri '\(uri)'. The file extension of that uri is currently not supported. The video file will not be cached. Checkout https://github.com/react-native-community/react-native-video/blob/master/docs/caching.md")
let asset:AVURLAsset! = AVURLAsset(url: url!, options:options as! [String : Any])
return playerItemPrepareText(asset, options, "")
default:
if let cachedAsset = cachedAsset {
DebugLog("Playing back uri '\(uri)' from cache")
// See note in playerItemForSource about not being able to support text tracks & caching
return AVPlayerItem(asset: cachedAsset)
.then { [weak self] (videoCacheStatus: RCTVideoCacheStatus, cachedAsset: AVAsset?) -> AVPlayerItem in
guard let self = self, let playerItemPrepareText = self.playerItemPrepareText else { throw NSError(domain: "", code: 0, userInfo: nil) }
switch videoCacheStatus {
case .missingFileExtension:
DebugLog("""
Could not generate cache key for uri '\(uri)'.
It is currently not supported to cache urls that do not include a file extension.
The video file will not be cached.
Checkout https://github.com/react-native-community/react-native-video/blob/master/docs/caching.md
""")
let asset: AVURLAsset! = AVURLAsset(url: url!, options: options as! [String: Any])
return playerItemPrepareText(asset, options, "")
case .unsupportedFileExtension:
DebugLog("""
Could not generate cache key for uri '\(uri)'.
The file extension of that uri is currently not supported.
The video file will not be cached.
Checkout https://github.com/react-native-community/react-native-video/blob/master/docs/caching.md
""")
let asset: AVURLAsset! = AVURLAsset(url: url!, options: options as! [String: Any])
return playerItemPrepareText(asset, options, "")
default:
if let cachedAsset = cachedAsset {
DebugLog("Playing back uri '\(uri)' from cache")
// See note in playerItemForSource about not being able to support text tracks & caching
return AVPlayerItem(asset: cachedAsset)
}
}
let asset: DVURLAsset! = DVURLAsset(url: url, options: options as! [String: Any], networkTimeout: 10000)
asset.loaderDelegate = self
/* More granular code to have control over the DVURLAsset
let resourceLoaderDelegate = DVAssetLoaderDelegate(url: url)
resourceLoaderDelegate.delegate = self
let components = NSURLComponents(url: url, resolvingAgainstBaseURL: false)
components?.scheme = DVAssetLoaderDelegate.scheme()
var asset: AVURLAsset? = nil
if let url = components?.url {
asset = AVURLAsset(url: url, options: options)
}
asset?.resourceLoader.setDelegate(resourceLoaderDelegate, queue: DispatchQueue.main)
*/
return AVPlayerItem(asset: asset)
}
let asset:DVURLAsset! = DVURLAsset(url:url, options:options as! [String : Any], networkTimeout:10000)
asset.loaderDelegate = self
/* More granular code to have control over the DVURLAsset
let resourceLoaderDelegate = DVAssetLoaderDelegate(url: url)
resourceLoaderDelegate.delegate = self
let components = NSURLComponents(url: url, resolvingAgainstBaseURL: false)
components?.scheme = DVAssetLoaderDelegate.scheme()
var asset: AVURLAsset? = nil
if let url = components?.url {
asset = AVURLAsset(url: url, options: options)
}
asset?.resourceLoader.setDelegate(resourceLoaderDelegate, queue: DispatchQueue.main)
*/
return AVPlayerItem(asset: asset)
}
}
func getItemForUri(_ uri:String) -> Promise<(videoCacheStatus:RCTVideoCacheStatus,cachedAsset:AVAsset?)> {
return Promise<(videoCacheStatus:RCTVideoCacheStatus,cachedAsset:AVAsset?)> { fulfill, reject in
self._videoCache.getItemForUri(uri, withCallback:{ (videoCacheStatus:RCTVideoCacheStatus,cachedAsset:AVAsset?) in
func getItemForUri(_ uri: String) -> Promise<(videoCacheStatus: RCTVideoCacheStatus, cachedAsset: AVAsset?)> {
return Promise<(videoCacheStatus: RCTVideoCacheStatus, cachedAsset: AVAsset?)> { fulfill, _ in
self._videoCache.getItemForUri(uri, withCallback: { (videoCacheStatus: RCTVideoCacheStatus, cachedAsset: AVAsset?) in
fulfill((videoCacheStatus, cachedAsset))
})
}
}
// MARK: - DVAssetLoaderDelegate
func dvAssetLoaderDelegate(_ loaderDelegate: DVAssetLoaderDelegate!, didLoad data: Data!, for url: URL!) {
_videoCache.storeItem(data as Data?, forUri:url.absoluteString, withCallback:{ (success:Bool) in
func dvAssetLoaderDelegate(_: DVAssetLoaderDelegate!, didLoad data: Data!, for url: URL!) {
_videoCache.storeItem(data as Data?, forUri: url.absoluteString, withCallback: { (_: Bool) in
DebugLog("Cache data stored successfully 🎉")
})
}
}