├── CachedImageExample ├── .watchmanconfig ├── .gitattributes ├── .babelrc ├── app.json ├── image1.jpg ├── loading.jpg ├── android │ ├── app │ │ ├── src │ │ │ └── main │ │ │ │ ├── res │ │ │ │ ├── values │ │ │ │ │ ├── strings.xml │ │ │ │ │ └── styles.xml │ │ │ │ ├── mipmap-hdpi │ │ │ │ │ └── ic_launcher.png │ │ │ │ ├── mipmap-mdpi │ │ │ │ │ └── ic_launcher.png │ │ │ │ ├── mipmap-xhdpi │ │ │ │ │ └── ic_launcher.png │ │ │ │ └── mipmap-xxhdpi │ │ │ │ │ └── ic_launcher.png │ │ │ │ ├── java │ │ │ │ └── com │ │ │ │ │ └── cachedimageexample │ │ │ │ │ ├── MainActivity.java │ │ │ │ │ └── MainApplication.java │ │ │ │ └── AndroidManifest.xml │ │ ├── BUCK │ │ ├── proguard-rules.pro │ │ └── build.gradle │ ├── keystores │ │ ├── debug.keystore.properties │ │ └── BUCK │ ├── gradle │ │ └── wrapper │ │ │ ├── gradle-wrapper.jar │ │ │ └── gradle-wrapper.properties │ ├── settings.gradle │ ├── build.gradle │ ├── gradle.properties │ ├── gradlew.bat │ └── gradlew ├── .buckconfig ├── __tests__ │ └── index.js ├── ios │ ├── CachedImageExample │ │ ├── AppDelegate.h │ │ ├── main.m │ │ ├── Images.xcassets │ │ │ └── AppIcon.appiconset │ │ │ │ └── Contents.json │ │ ├── AppDelegate.m │ │ ├── Info.plist │ │ └── Base.lproj │ │ │ └── LaunchScreen.xib │ ├── CachedImageExampleTests │ │ ├── Info.plist │ │ └── CachedImageExampleTests.m │ ├── CachedImageExample-tvOSTests │ │ └── Info.plist │ ├── CachedImageExample-tvOS │ │ └── Info.plist │ └── CachedImageExample.xcodeproj │ │ ├── xcshareddata │ │ └── xcschemes │ │ │ ├── CachedImageExample.xcscheme │ │ │ └── CachedImageExample-tvOS.xcscheme │ │ └── project.pbxproj ├── .gitignore ├── package.json ├── .flowconfig └── index.js ├── .babelrc ├── index.js ├── ImageCacheManagerOptionsPropTypes.js ├── .gitignore ├── __tests__ ├── SimpleMemoryCache.js ├── ImageCacheManager-test.js └── SimpleMemoryFs.js ├── LICENSE ├── ImageCachePreloader.js ├── package.json ├── ImageCacheProvider.js ├── utils ├── pathUtils.js └── fsUtils.js ├── index.d.ts ├── ImageCacheManager.js ├── README.md └── CachedImage.js /CachedImageExample/.watchmanconfig: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["react-native"] 3 | } -------------------------------------------------------------------------------- /CachedImageExample/.gitattributes: -------------------------------------------------------------------------------- 1 | *.pbxproj -text 2 | -------------------------------------------------------------------------------- /CachedImageExample/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["react-native"] 3 | } 4 | -------------------------------------------------------------------------------- /CachedImageExample/app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "CachedImageExample", 3 | "displayName": "CachedImageExample" 4 | } -------------------------------------------------------------------------------- /CachedImageExample/image1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kfiroo/react-native-cached-image/HEAD/CachedImageExample/image1.jpg -------------------------------------------------------------------------------- /CachedImageExample/loading.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kfiroo/react-native-cached-image/HEAD/CachedImageExample/loading.jpg -------------------------------------------------------------------------------- /CachedImageExample/android/app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | CachedImageExample 3 | 4 | -------------------------------------------------------------------------------- /CachedImageExample/.buckconfig: -------------------------------------------------------------------------------- 1 | 2 | [android] 3 | target = Google Inc.:Google APIs:23 4 | 5 | [maven_repositories] 6 | central = https://repo1.maven.org/maven2 7 | -------------------------------------------------------------------------------- /CachedImageExample/android/keystores/debug.keystore.properties: -------------------------------------------------------------------------------- 1 | key.store=debug.keystore 2 | key.alias=androiddebugkey 3 | key.store.password=android 4 | key.alias.password=android 5 | -------------------------------------------------------------------------------- /CachedImageExample/android/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kfiroo/react-native-cached-image/HEAD/CachedImageExample/android/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /CachedImageExample/android/app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kfiroo/react-native-cached-image/HEAD/CachedImageExample/android/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /CachedImageExample/android/app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kfiroo/react-native-cached-image/HEAD/CachedImageExample/android/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /CachedImageExample/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kfiroo/react-native-cached-image/HEAD/CachedImageExample/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /CachedImageExample/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kfiroo/react-native-cached-image/HEAD/CachedImageExample/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /CachedImageExample/android/keystores/BUCK: -------------------------------------------------------------------------------- 1 | keystore( 2 | name = "debug", 3 | properties = "debug.keystore.properties", 4 | store = "debug.keystore", 5 | visibility = [ 6 | "PUBLIC", 7 | ], 8 | ) 9 | -------------------------------------------------------------------------------- /CachedImageExample/android/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /CachedImageExample/android/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'CachedImageExample' 2 | include ':react-native-fetch-blob' 3 | project(':react-native-fetch-blob').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-fetch-blob/android') 4 | 5 | include ':app' 6 | -------------------------------------------------------------------------------- /CachedImageExample/android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | zipStoreBase=GRADLE_USER_HOME 4 | zipStorePath=wrapper/dists 5 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip 6 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports.CachedImage = require('./CachedImage'); 4 | module.exports.ImageCacheProvider = require('./ImageCacheProvider'); 5 | module.exports.ImageCacheManager = require('./ImageCacheManager'); 6 | module.exports.ImageCachePreloader = require('./ImageCachePreloader'); 7 | -------------------------------------------------------------------------------- /CachedImageExample/__tests__/index.js: -------------------------------------------------------------------------------- 1 | import 'react-native'; 2 | import React from 'react'; 3 | import Index from '../index.android.js'; 4 | 5 | // Note: test renderer must be required after react-native. 6 | import renderer from 'react-test-renderer'; 7 | 8 | it('renders correctly', () => { 9 | const tree = renderer.create( 10 | 11 | ); 12 | }); 13 | -------------------------------------------------------------------------------- /ImageCacheManagerOptionsPropTypes.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const PropTypes = require('prop-types'); 4 | 5 | module.exports = { 6 | headers: PropTypes.object, 7 | ttl: PropTypes.number, 8 | useQueryParamsInCacheKey: PropTypes.oneOfType([ 9 | PropTypes.bool, 10 | PropTypes.arrayOf(PropTypes.string) 11 | ]), 12 | cacheLocation: PropTypes.string, 13 | allowSelfSignedSSL: PropTypes.bool 14 | }; 15 | -------------------------------------------------------------------------------- /CachedImageExample/android/app/src/main/java/com/cachedimageexample/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.cachedimageexample; 2 | 3 | import com.facebook.react.ReactActivity; 4 | 5 | public class MainActivity extends ReactActivity { 6 | 7 | /** 8 | * Returns the name of the main component registered from JavaScript. 9 | * This is used to schedule rendering of the component. 10 | */ 11 | @Override 12 | protected String getMainComponentName() { 13 | return "CachedImageExample"; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /CachedImageExample/ios/CachedImageExample/AppDelegate.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-present, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | */ 9 | 10 | #import 11 | 12 | @interface AppDelegate : UIResponder 13 | 14 | @property (nonatomic, strong) UIWindow *window; 15 | 16 | @end 17 | -------------------------------------------------------------------------------- /CachedImageExample/ios/CachedImageExample/main.m: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-present, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | */ 9 | 10 | #import 11 | 12 | #import "AppDelegate.h" 13 | 14 | int main(int argc, char * argv[]) { 15 | @autoreleasepool { 16 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /CachedImageExample/.gitignore: -------------------------------------------------------------------------------- 1 | # OSX 2 | # 3 | .DS_Store 4 | 5 | # Xcode 6 | # 7 | build/ 8 | *.pbxuser 9 | !default.pbxuser 10 | *.mode1v3 11 | !default.mode1v3 12 | *.mode2v3 13 | !default.mode2v3 14 | *.perspectivev3 15 | !default.perspectivev3 16 | xcuserdata 17 | *.xccheckout 18 | *.moved-aside 19 | DerivedData 20 | *.hmap 21 | *.ipa 22 | *.xcuserstate 23 | project.xcworkspace 24 | 25 | # Android/IntelliJ 26 | # 27 | build/ 28 | .idea 29 | .gradle 30 | local.properties 31 | *.iml 32 | 33 | # node.js 34 | # 35 | node_modules/ 36 | npm-debug.log 37 | yarn-error.log 38 | 39 | # BUCK 40 | buck-out/ 41 | \.buckd/ 42 | android/app/libs 43 | *.keystore 44 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Runtime data 7 | pids 8 | *.pid 9 | *.seed 10 | 11 | # Directory for instrumented libs generated by jscoverage/JSCover 12 | lib-cov 13 | 14 | # Coverage directory used by tools like istanbul 15 | coverage 16 | 17 | # nyc test coverage 18 | .nyc_output 19 | 20 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 21 | .grunt 22 | 23 | # node-waf configuration 24 | .lock-wscript 25 | 26 | # Compiled binary addons (http://nodejs.org/api/addons.html) 27 | build/Release 28 | 29 | # Dependency directories 30 | node_modules 31 | jspm_packages 32 | 33 | # Optional npm cache directory 34 | .npm 35 | 36 | # Optional REPL history 37 | .node_repl_history 38 | /.idea/ 39 | -------------------------------------------------------------------------------- /CachedImageExample/android/build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | jcenter() 6 | } 7 | dependencies { 8 | classpath 'com.android.tools.build:gradle:2.2.3' 9 | 10 | // NOTE: Do not place your application dependencies here; they belong 11 | // in the individual module build.gradle files 12 | } 13 | } 14 | 15 | allprojects { 16 | repositories { 17 | mavenLocal() 18 | jcenter() 19 | maven { 20 | // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm 21 | url "$rootDir/../node_modules/react-native/android" 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /CachedImageExample/ios/CachedImageExample/Images.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "size" : "29x29", 6 | "scale" : "2x" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "size" : "29x29", 11 | "scale" : "3x" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "size" : "40x40", 16 | "scale" : "2x" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "size" : "40x40", 21 | "scale" : "3x" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "size" : "60x60", 26 | "scale" : "2x" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "size" : "60x60", 31 | "scale" : "3x" 32 | } 33 | ], 34 | "info" : { 35 | "version" : 1, 36 | "author" : "xcode" 37 | } 38 | } -------------------------------------------------------------------------------- /CachedImageExample/ios/CachedImageExampleTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /CachedImageExample/ios/CachedImageExample-tvOSTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /CachedImageExample/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "CachedImageExample", 3 | "version": "0.0.1", 4 | "private": true, 5 | "scripts": { 6 | "start": "node node_modules/react-native/local-cli/cli.js start", 7 | "test": "jest", 8 | "dev": "yarn && rm -rf ./node_modules/react-native-cached-image; sane 'rsync -av --include='utils/' --include='utils/*.js' --include='*.js' --include='package.json' --exclude='*' ../ ./node_modules/react-native-cached-image' ../ --glob '**/*.js' --glob 'package.json'" 9 | }, 10 | "dependencies": { 11 | "react": "16.0.0-alpha.12", 12 | "react-native": "^0.48.3", 13 | "react-native-cached-image": "../" 14 | }, 15 | "devDependencies": { 16 | "babel-jest": "^21.0.2", 17 | "babel-preset-react-native": "^3.0.2", 18 | "jest": "^21.0.2", 19 | "react-test-renderer": "^15.6.1", 20 | "sane": "^2.0.0" 21 | }, 22 | "jest": { 23 | "preset": "react-native" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /CachedImageExample/android/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true 19 | 20 | android.useDeprecatedNdk=true 21 | -------------------------------------------------------------------------------- /__tests__/SimpleMemoryCache.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const DEFAULT_EXPIRES = 999999; 4 | 5 | function currentTime() { 6 | return Math.floor((new Date().getTime() / 1000)); 7 | } 8 | 9 | let cache = {}; 10 | 11 | const SimpleMemoryCache = {}; 12 | 13 | SimpleMemoryCache.set = (key, value, expires = DEFAULT_EXPIRES) => { 14 | cache[key] = { 15 | value: value, 16 | expires: currentTime() + parseInt(expires) 17 | }; 18 | return Promise.resolve(); 19 | }; 20 | 21 | SimpleMemoryCache.get = (key) => { 22 | const curTime = currentTime(); 23 | const v = cache[key]; 24 | if (v && v.expires && v.expires >= curTime) { 25 | return Promise.resolve(v.value); 26 | } 27 | return Promise.resolve(); 28 | }; 29 | 30 | SimpleMemoryCache.remove = async (key) => { 31 | delete cache[key]; 32 | return Promise.resolve(); 33 | }; 34 | 35 | SimpleMemoryCache.flush = async () => { 36 | cache = {}; 37 | return Promise.resolve(); 38 | }; 39 | export default SimpleMemoryCache; -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Kfir Golan 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /ImageCachePreloader.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const _ = require('lodash'); 4 | 5 | function createPreloader(list) { 6 | const urls = _.clone(list); 7 | return { 8 | next() { 9 | return urls.shift(); 10 | } 11 | }; 12 | } 13 | 14 | function runPreloadTask(prefetcher, imageCacheManager) { 15 | const url = prefetcher.next(); 16 | if (!url) { 17 | return Promise.resolve(); 18 | } 19 | // console.log('START', url); 20 | return imageCacheManager.downloadAndCacheUrl(url) 21 | // allow prefetch task to fail without terminating other prefetch tasks 22 | .catch(_.noop) 23 | // .then(() => { 24 | // console.log('END', url); 25 | // }) 26 | // then run next task 27 | .then(() => runPreloadTask(prefetcher, imageCacheManager)); 28 | } 29 | 30 | module.exports = { 31 | 32 | /** 33 | * download and cache an list of urls 34 | * @param urls 35 | * @param imageCacheManager 36 | * @param numberOfConcurrentPreloads 37 | * @returns {Promise} 38 | */ 39 | preloadImages(urls, imageCacheManager, numberOfConcurrentPreloads) { 40 | const preloader = createPreloader(urls); 41 | const numberOfWorkers = numberOfConcurrentPreloads > 0 ? numberOfConcurrentPreloads : urls.length; 42 | const promises = _.times(numberOfWorkers, () => 43 | runPreloadTask(preloader, imageCacheManager) 44 | ); 45 | return Promise.all(promises); 46 | }, 47 | 48 | }; 49 | -------------------------------------------------------------------------------- /CachedImageExample/ios/CachedImageExample/AppDelegate.m: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-present, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | */ 9 | 10 | #import "AppDelegate.h" 11 | 12 | #import 13 | #import 14 | 15 | @implementation AppDelegate 16 | 17 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 18 | { 19 | NSURL *jsCodeLocation; 20 | 21 | jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil]; 22 | 23 | RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation 24 | moduleName:@"CachedImageExample" 25 | initialProperties:nil 26 | launchOptions:launchOptions]; 27 | rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1]; 28 | 29 | self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; 30 | UIViewController *rootViewController = [UIViewController new]; 31 | rootViewController.view = rootView; 32 | self.window.rootViewController = rootViewController; 33 | [self.window makeKeyAndVisible]; 34 | return YES; 35 | } 36 | 37 | @end 38 | -------------------------------------------------------------------------------- /CachedImageExample/android/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 15 | 16 | 22 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /CachedImageExample/android/app/src/main/java/com/cachedimageexample/MainApplication.java: -------------------------------------------------------------------------------- 1 | package com.cachedimageexample; 2 | 3 | import android.util.Log; 4 | import android.app.Application; 5 | 6 | import com.facebook.react.ReactApplication; 7 | import com.facebook.react.ReactInstanceManager; 8 | import com.facebook.react.ReactNativeHost; 9 | import com.facebook.react.ReactPackage; 10 | import com.facebook.react.shell.MainReactPackage; 11 | 12 | import com.facebook.soloader.SoLoader; 13 | 14 | import com.RNFetchBlob.RNFetchBlobPackage; 15 | 16 | import java.util.Arrays; 17 | import java.util.List; 18 | 19 | public class MainApplication extends Application implements ReactApplication { 20 | 21 | private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { 22 | @Override 23 | public boolean getUseDeveloperSupport() { 24 | return BuildConfig.DEBUG; 25 | } 26 | 27 | @Override 28 | protected String getJSMainModuleName() { 29 | return "index"; 30 | } 31 | 32 | @Override 33 | protected List getPackages() { 34 | return Arrays.asList( 35 | new MainReactPackage(), 36 | new RNFetchBlobPackage() 37 | ); 38 | } 39 | }; 40 | 41 | @Override 42 | public ReactNativeHost getReactNativeHost() { 43 | return mReactNativeHost; 44 | } 45 | 46 | @Override 47 | public void onCreate() { 48 | super.onCreate(); 49 | SoLoader.init(this, /* native exopackage */ false); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /__tests__/ImageCacheManager-test.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | jest.mock('react-native-fetch-blob', () => ({default: {fs: {}}})); 4 | jest.mock('react-native-clcasher/MemoryCache', () => ({default: {}})); 5 | 6 | import ImageCacheManager from '../ImageCacheManager'; 7 | import SimpleMemoryCache from './SimpleMemoryCache'; 8 | import SimpleMemoryFs from './SimpleMemoryFs'; 9 | 10 | const icm = ImageCacheManager({}, SimpleMemoryCache, SimpleMemoryFs); 11 | 12 | describe('ImageCacheManager', () => { 13 | 14 | beforeEach(() => icm.clearCache()); 15 | 16 | describe('downloadAndCacheUrl', () => { 17 | 18 | it('should fail if URL is not cacheable', () => { 19 | return icm.getCacheInfo() 20 | .then(res => console.log(res)) 21 | .then(() => { 22 | return expect(icm.downloadAndCacheUrl('not a real url')).rejects.toBeDefined(); 23 | }); 24 | }); 25 | 26 | it('should download a file when not in cache', () => { 27 | return icm.getCacheInfo() 28 | .then(res => console.log(res)) 29 | .then(() => icm.downloadAndCacheUrl('https://example.com/image.jpg')) 30 | .then(() => icm.getCacheInfo()) 31 | .then(res => console.log(res)) 32 | }); 33 | 34 | it('should add new entry to the cache if not in cache', () => { 35 | 36 | }); 37 | 38 | it('should return file name if image is in cache', () => { 39 | 40 | }); 41 | 42 | it('should not return cached entry if expired', () => { 43 | 44 | }); 45 | 46 | }); 47 | 48 | }); -------------------------------------------------------------------------------- /CachedImageExample/.flowconfig: -------------------------------------------------------------------------------- 1 | [ignore] 2 | ; We fork some components by platform 3 | .*/*[.]android.js 4 | 5 | ; Ignore "BUCK" generated dirs 6 | /\.buckd/ 7 | 8 | ; Ignore unexpected extra "@providesModule" 9 | .*/node_modules/.*/node_modules/fbjs/.* 10 | 11 | ; Ignore duplicate module providers 12 | ; For RN Apps installed via npm, "Libraries" folder is inside 13 | ; "node_modules/react-native" but in the source repo it is in the root 14 | .*/Libraries/react-native/React.js 15 | .*/Libraries/react-native/ReactNative.js 16 | 17 | [include] 18 | 19 | [libs] 20 | node_modules/react-native/Libraries/react-native/react-native-interface.js 21 | node_modules/react-native/flow 22 | flow/ 23 | 24 | [options] 25 | emoji=true 26 | 27 | module.system=haste 28 | 29 | experimental.strict_type_args=true 30 | 31 | munge_underscores=true 32 | 33 | module.name_mapper='^image![a-zA-Z0-9$_-]+$' -> 'GlobalImageStub' 34 | module.name_mapper='^[./a-zA-Z0-9$_-]+\.\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|webp\|m4v\|mov\|mp4\|mpeg\|mpg\|webm\|aac\|aiff\|caf\|m4a\|mp3\|wav\|html\|pdf\)$' -> 'RelativeImageStub' 35 | 36 | suppress_type=$FlowIssue 37 | suppress_type=$FlowFixMe 38 | suppress_type=$FixMe 39 | 40 | suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(>=0\\.\\(4[0-7]\\|[1-3][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\) 41 | suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(>=0\\.\\(4[0-7]\\|[1-3][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)?:? #[0-9]+ 42 | 43 | suppress_comment=\\(.\\|\n\\)*\\$FlowFixedInNextDeploy 44 | suppress_comment=\\(.\\|\n\\)*\\$FlowExpectedError 45 | 46 | unsafe.enable_getters_and_setters=true 47 | 48 | [version] 49 | ^0.47.0 -------------------------------------------------------------------------------- /CachedImageExample/ios/CachedImageExample/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleDisplayName 8 | CachedImageExample 9 | CFBundleExecutable 10 | $(EXECUTABLE_NAME) 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | $(PRODUCT_NAME) 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | 1.0 21 | CFBundleSignature 22 | ???? 23 | CFBundleVersion 24 | 1 25 | LSRequiresIPhoneOS 26 | 27 | NSAppTransportSecurity 28 | 29 | NSExceptionDomains 30 | 31 | localhost 32 | 33 | NSExceptionAllowsInsecureHTTPLoads 34 | 35 | 36 | 37 | 38 | NSLocationWhenInUseUsageDescription 39 | 40 | UILaunchStoryboardName 41 | LaunchScreen 42 | UIRequiredDeviceCapabilities 43 | 44 | armv7 45 | 46 | UISupportedInterfaceOrientations 47 | 48 | UIInterfaceOrientationPortrait 49 | UIInterfaceOrientationLandscapeLeft 50 | UIInterfaceOrientationLandscapeRight 51 | 52 | UIViewControllerBasedStatusBarAppearance 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /CachedImageExample/ios/CachedImageExample-tvOS/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | APPL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | LSRequiresIPhoneOS 24 | 25 | UILaunchStoryboardName 26 | LaunchScreen 27 | UIRequiredDeviceCapabilities 28 | 29 | armv7 30 | 31 | UISupportedInterfaceOrientations 32 | 33 | UIInterfaceOrientationPortrait 34 | UIInterfaceOrientationLandscapeLeft 35 | UIInterfaceOrientationLandscapeRight 36 | 37 | UIViewControllerBasedStatusBarAppearance 38 | 39 | NSLocationWhenInUseUsageDescription 40 | 41 | NSAppTransportSecurity 42 | 43 | 44 | NSExceptionDomains 45 | 46 | localhost 47 | 48 | NSExceptionAllowsInsecureHTTPLoads 49 | 50 | 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /CachedImageExample/android/app/BUCK: -------------------------------------------------------------------------------- 1 | # To learn about Buck see [Docs](https://buckbuild.com/). 2 | # To run your application with Buck: 3 | # - install Buck 4 | # - `npm start` - to start the packager 5 | # - `cd android` 6 | # - `keytool -genkey -v -keystore keystores/debug.keystore -storepass android -alias androiddebugkey -keypass android -dname "CN=Android Debug,O=Android,C=US"` 7 | # - `./gradlew :app:copyDownloadableDepsToLibs` - make all Gradle compile dependencies available to Buck 8 | # - `buck install -r android/app` - compile, install and run application 9 | # 10 | 11 | lib_deps = [] 12 | 13 | for jarfile in glob(['libs/*.jar']): 14 | name = 'jars__' + jarfile[jarfile.rindex('/') + 1: jarfile.rindex('.jar')] 15 | lib_deps.append(':' + name) 16 | prebuilt_jar( 17 | name = name, 18 | binary_jar = jarfile, 19 | ) 20 | 21 | for aarfile in glob(['libs/*.aar']): 22 | name = 'aars__' + aarfile[aarfile.rindex('/') + 1: aarfile.rindex('.aar')] 23 | lib_deps.append(':' + name) 24 | android_prebuilt_aar( 25 | name = name, 26 | aar = aarfile, 27 | ) 28 | 29 | android_library( 30 | name = "all-libs", 31 | exported_deps = lib_deps, 32 | ) 33 | 34 | android_library( 35 | name = "app-code", 36 | srcs = glob([ 37 | "src/main/java/**/*.java", 38 | ]), 39 | deps = [ 40 | ":all-libs", 41 | ":build_config", 42 | ":res", 43 | ], 44 | ) 45 | 46 | android_build_config( 47 | name = "build_config", 48 | package = "com.cachedimageexample", 49 | ) 50 | 51 | android_resource( 52 | name = "res", 53 | package = "com.cachedimageexample", 54 | res = "src/main/res", 55 | ) 56 | 57 | android_binary( 58 | name = "app", 59 | keystore = "//android/keystores:debug", 60 | manifest = "src/main/AndroidManifest.xml", 61 | package_type = "debug", 62 | deps = [ 63 | ":app-code", 64 | ], 65 | ) 66 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-native-cached-image", 3 | "version": "1.4.3", 4 | "description": "CachedImage component for react-native", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "./node_modules/.bin/jest" 8 | }, 9 | "jest": { 10 | "preset": "react-native", 11 | "globals": { 12 | "NODE_ENV": "test" 13 | }, 14 | "testPathIgnorePatterns": [ 15 | "/node_modules/", 16 | "/CachedImageExample/" 17 | ], 18 | "modulePathIgnorePatterns": [ 19 | "/CachedImageExample/" 20 | ], 21 | "verbose": true 22 | }, 23 | "repository": { 24 | "type": "git", 25 | "url": "https://github.com/kfiroo/react-native-cached-image" 26 | }, 27 | "keywords": [ 28 | "react-native", 29 | "cache", 30 | "image" 31 | ], 32 | "author": "kfiroo ", 33 | "license": "MIT", 34 | "bugs": { 35 | "url": "https://github.com/kfiroo/react-native-cached-image/issues" 36 | }, 37 | "homepage": "https://github.com/kfiroo/react-native-cached-image", 38 | "files": [ 39 | "index.js", 40 | "CachedImage.js", 41 | "ImageCacheProvider.js", 42 | "ImageCacheManager.js", 43 | "ImageCacheManagerOptionsPropTypes.js", 44 | "ImageCachePreloader.js", 45 | "utils/fsUtils.js", 46 | "utils/pathUtils.js" 47 | ], 48 | "typings": "./index.d.ts", 49 | "dependencies": { 50 | "crypto-js": "3.1.9-1", 51 | "lodash": "4.17.19", 52 | "prop-types": "15.5.10", 53 | "react-native-clcasher": "1.0.0", 54 | "react-native-fetch-blob": "0.10.8", 55 | "url-parse": "1.1.9" 56 | }, 57 | "devDependencies": { 58 | "babel-jest": "^21.0.2", 59 | "babel-preset-env": "*", 60 | "babel-preset-react-native": "^3.0.2", 61 | "jest": "^21.0.2", 62 | "jest-react-native": "^18.0.0", 63 | "react": "16.0.0-alpha.12", 64 | "react-native": "^0.48.3", 65 | "react-test-renderer": "^15.6.1", 66 | "regenerator-runtime": "^0.11.0" 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /CachedImageExample/ios/CachedImageExampleTests/CachedImageExampleTests.m: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-present, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | */ 9 | 10 | #import 11 | #import 12 | 13 | #import "RCTLog.h" 14 | #import "RCTRootView.h" 15 | 16 | #define TIMEOUT_SECONDS 600 17 | #define TEXT_TO_LOOK_FOR @"Welcome to React Native!" 18 | 19 | @interface CachedImageExampleTests : XCTestCase 20 | 21 | @end 22 | 23 | @implementation CachedImageExampleTests 24 | 25 | - (BOOL)findSubviewInView:(UIView *)view matching:(BOOL(^)(UIView *view))test 26 | { 27 | if (test(view)) { 28 | return YES; 29 | } 30 | for (UIView *subview in [view subviews]) { 31 | if ([self findSubviewInView:subview matching:test]) { 32 | return YES; 33 | } 34 | } 35 | return NO; 36 | } 37 | 38 | - (void)testRendersWelcomeScreen 39 | { 40 | UIViewController *vc = [[[RCTSharedApplication() delegate] window] rootViewController]; 41 | NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS]; 42 | BOOL foundElement = NO; 43 | 44 | __block NSString *redboxError = nil; 45 | RCTSetLogFunction(^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) { 46 | if (level >= RCTLogLevelError) { 47 | redboxError = message; 48 | } 49 | }); 50 | 51 | while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) { 52 | [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; 53 | [[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; 54 | 55 | foundElement = [self findSubviewInView:vc.view matching:^BOOL(UIView *view) { 56 | if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) { 57 | return YES; 58 | } 59 | return NO; 60 | }]; 61 | } 62 | 63 | RCTSetLogFunction(RCTDefaultLogFunction); 64 | 65 | XCTAssertNil(redboxError, @"RedBox error: %@", redboxError); 66 | XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS); 67 | } 68 | 69 | 70 | @end 71 | -------------------------------------------------------------------------------- /__tests__/SimpleMemoryFs.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const _ = require('lodash'); 4 | 5 | let fs = {}; 6 | 7 | /** 8 | * wrapper around common filesystem actions 9 | */ 10 | module.exports = { 11 | 12 | /** 13 | * returns the local cache dir 14 | * @returns {String} 15 | */ 16 | getCacheDir() { 17 | return '/imagesCacheDir'; 18 | }, 19 | 20 | /** 21 | * returns a promise that is resolved when the download of the requested file 22 | * is complete and the file is saved. 23 | * if the download fails, or was stopped the partial file is deleted, and the 24 | * promise is rejected 25 | * @param fromUrl String source url 26 | * @param toFile String destination path 27 | * @param headers Object with headers to use when downloading the file 28 | * @returns {Promise} 29 | */ 30 | downloadFile(fromUrl, toFile, headers) { 31 | fs[toFile] = fromUrl; 32 | return Promise.resolve(toFile); 33 | }, 34 | 35 | /** 36 | * remove the file in filePath if it exists. 37 | * this method always resolves 38 | * @param filePath 39 | * @returns {Promise} 40 | */ 41 | deleteFile(filePath) { 42 | delete fs[filePath]; 43 | return Promise.resolve(); 44 | }, 45 | 46 | /** 47 | * copy a file from fromFile to toFile 48 | * @param fromFile 49 | * @param toFile 50 | * @returns {Promise} 51 | */ 52 | copyFile(fromFile, toFile) { 53 | fs[toFile] = fs[fromFile] || fromFile; 54 | return Promise.resolve(); 55 | }, 56 | 57 | /** 58 | * remove the contents of dirPath 59 | * @param dirPath 60 | * @returns {Promise} 61 | */ 62 | cleanDir(dirPath) { 63 | fs = _.omitBy(fs, (v, k) => _.startsWith(k, dirPath)); 64 | return Promise.resolve(); 65 | }, 66 | 67 | /** 68 | * get info about files in a folder 69 | * @param dirPath 70 | * @returns {Promise.<{file:Array, size:Number}>} 71 | */ 72 | getDirInfo(dirPath) { 73 | const files = _(fs) 74 | .pickBy((v, k) => _.startsWith(k, dirPath)) 75 | .map((v, k) => ({ 76 | filename: k, 77 | source: v, 78 | size: 1 79 | })) 80 | .value(); 81 | return Promise.resolve({ 82 | files, 83 | size: files.length 84 | }); 85 | }, 86 | 87 | }; -------------------------------------------------------------------------------- /CachedImageExample/android/gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /CachedImageExample/android/app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | 19 | # Disabling obfuscation is useful if you collect stack traces from production crashes 20 | # (unless you are using a system that supports de-obfuscate the stack traces). 21 | -dontobfuscate 22 | 23 | # React Native 24 | 25 | # Keep our interfaces so they can be used by other ProGuard rules. 26 | # See http://sourceforge.net/p/proguard/bugs/466/ 27 | -keep,allowobfuscation @interface com.facebook.proguard.annotations.DoNotStrip 28 | -keep,allowobfuscation @interface com.facebook.proguard.annotations.KeepGettersAndSetters 29 | -keep,allowobfuscation @interface com.facebook.common.internal.DoNotStrip 30 | 31 | # Do not strip any method/class that is annotated with @DoNotStrip 32 | -keep @com.facebook.proguard.annotations.DoNotStrip class * 33 | -keep @com.facebook.common.internal.DoNotStrip class * 34 | -keepclassmembers class * { 35 | @com.facebook.proguard.annotations.DoNotStrip *; 36 | @com.facebook.common.internal.DoNotStrip *; 37 | } 38 | 39 | -keepclassmembers @com.facebook.proguard.annotations.KeepGettersAndSetters class * { 40 | void set*(***); 41 | *** get*(); 42 | } 43 | 44 | -keep class * extends com.facebook.react.bridge.JavaScriptModule { *; } 45 | -keep class * extends com.facebook.react.bridge.NativeModule { *; } 46 | -keepclassmembers,includedescriptorclasses class * { native ; } 47 | -keepclassmembers class * { @com.facebook.react.uimanager.UIProp ; } 48 | -keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactProp ; } 49 | -keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactPropGroup ; } 50 | 51 | -dontwarn com.facebook.react.** 52 | 53 | # TextLayoutBuilder uses a non-public Android constructor within StaticLayout. 54 | # See libs/proxy/src/main/java/com/facebook/fbui/textlayoutbuilder/proxy for details. 55 | -dontwarn android.text.StaticLayout 56 | 57 | # okhttp 58 | 59 | -keepattributes Signature 60 | -keepattributes *Annotation* 61 | -keep class okhttp3.** { *; } 62 | -keep interface okhttp3.** { *; } 63 | -dontwarn okhttp3.** 64 | 65 | # okio 66 | 67 | -keep class sun.misc.Unsafe { *; } 68 | -dontwarn java.nio.file.* 69 | -dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement 70 | -dontwarn okio.** 71 | -------------------------------------------------------------------------------- /ImageCacheProvider.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const _ = require('lodash'); 4 | const React = require('react'); 5 | const ReactNative = require('react-native'); 6 | 7 | const PropTypes = require('prop-types'); 8 | 9 | const ImageCacheManagerOptionsPropTypes = require('./ImageCacheManagerOptionsPropTypes'); 10 | 11 | const ImageCacheManager = require('./ImageCacheManager'); 12 | const ImageCachePreloader = require('./ImageCachePreloader'); 13 | 14 | class ImageCacheProvider extends React.Component { 15 | static propTypes = { 16 | // only a single child so we can render it without adding a View 17 | children: PropTypes.element, 18 | 19 | // ImageCacheManager options 20 | ...ImageCacheManagerOptionsPropTypes, 21 | 22 | // Preload urls 23 | urlsToPreload: PropTypes.arrayOf(PropTypes.string).isRequired, 24 | numberOfConcurrentPreloads: PropTypes.number.isRequired, 25 | 26 | onPreloadComplete: PropTypes.func.isRequired, 27 | }; 28 | 29 | static defaultProps = { 30 | urlsToPreload: [], 31 | numberOfConcurrentPreloads: 0, 32 | onPreloadComplete: _.noop, 33 | }; 34 | 35 | static childContextTypes = { 36 | getImageCacheManager: PropTypes.func, 37 | }; 38 | 39 | constructor(props) { 40 | super(props); 41 | 42 | this.getImageCacheManagerOptions = this.getImageCacheManagerOptions.bind(this); 43 | this.getImageCacheManager = this.getImageCacheManager.bind(this); 44 | this.preloadImages = this.preloadImages.bind(this); 45 | 46 | } 47 | 48 | getChildContext() { 49 | const self = this; 50 | return { 51 | getImageCacheManager() { 52 | return self.getImageCacheManager(); 53 | } 54 | }; 55 | } 56 | 57 | componentWillMount() { 58 | this.preloadImages(this.props.urlsToPreload); 59 | } 60 | 61 | componentWillReceiveProps(nextProps) { 62 | // reset imageCacheManager in case any option changed 63 | this.imageCacheManager = null; 64 | // preload new images if needed 65 | if (this.props.urlsToPreload !== nextProps.urlsToPreload) { 66 | this.preloadImages(nextProps.urlsToPreload); 67 | } 68 | } 69 | 70 | getImageCacheManagerOptions() { 71 | return _.pick(this.props, _.keys(ImageCacheManagerOptionsPropTypes)); 72 | } 73 | 74 | getImageCacheManager() { 75 | if (!this.imageCacheManager) { 76 | const options = this.getImageCacheManagerOptions(); 77 | this.imageCacheManager = ImageCacheManager(options); 78 | } 79 | return this.imageCacheManager; 80 | } 81 | 82 | preloadImages(urlsToPreload) { 83 | const imageCacheManager = this.getImageCacheManager(); 84 | ImageCachePreloader.preloadImages(urlsToPreload, imageCacheManager, this.props.numberOfConcurrentPreloads) 85 | .then(() => this.props.onPreloadComplete()); 86 | } 87 | 88 | render() { 89 | return React.Children.only(this.props.children); 90 | } 91 | 92 | } 93 | 94 | module.exports = ImageCacheProvider; 95 | -------------------------------------------------------------------------------- /utils/pathUtils.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const _ = require('lodash'); 4 | const URL = require('url-parse'); 5 | const SHA1 = require("crypto-js/sha1"); 6 | 7 | const defaultImageTypes = ['png', 'jpeg', 'jpg', 'gif', 'bmp', 'tiff', 'tif']; 8 | 9 | function serializeObjectKeys(obj) { 10 | return _(obj) 11 | .toPairs() 12 | .sortBy(a => a[0]) 13 | .map(a => a[1]) 14 | .value(); 15 | } 16 | 17 | function getQueryForCacheKey(url, useQueryParamsInCacheKey) { 18 | if (_.isArray(useQueryParamsInCacheKey)) { 19 | return serializeObjectKeys(_.pick(url.query, useQueryParamsInCacheKey)); 20 | } 21 | if (useQueryParamsInCacheKey) { 22 | return serializeObjectKeys(url.query); 23 | } 24 | return ''; 25 | } 26 | 27 | function generateCacheKey(url, useQueryParamsInCacheKey = true) { 28 | const parsedUrl = new URL(url, null, true); 29 | 30 | const pathParts = parsedUrl.pathname.split('/'); 31 | 32 | // last path part is the file name 33 | const fileName = pathParts.pop(); 34 | const filePath = pathParts.join('/'); 35 | 36 | const parts = fileName.split('.'); 37 | const fileType = parts.length > 1 ? _.toLower(parts.pop()) : ''; 38 | const type = defaultImageTypes.includes(fileType) ? fileType : 'jpg'; 39 | 40 | const cacheable = filePath + fileName + type + getQueryForCacheKey(parsedUrl, useQueryParamsInCacheKey); 41 | return SHA1(cacheable) + '.' + type; 42 | } 43 | 44 | function getHostCachePathComponent(url) { 45 | const { 46 | host 47 | } = new URL(url); 48 | 49 | return host.replace(/\.:/gi, '_').replace(/[^a-z0-9_]/gi, '_').toLowerCase() 50 | + '_' + SHA1(host); 51 | } 52 | 53 | /** 54 | * handle the resolution of URLs to local file paths 55 | */ 56 | module.exports = { 57 | 58 | /** 59 | * Given a URL and some options returns the file path in the file system corresponding to it's cached image location 60 | * @param url 61 | * @param cacheLocation 62 | * @returns {string} 63 | */ 64 | getImageFilePath(url, cacheLocation) { 65 | const hostCachePath = getHostCachePathComponent(url); 66 | const cacheKey = generateCacheKey(url); 67 | 68 | return `${cacheLocation}/${hostCachePath}/${cacheKey}`; 69 | }, 70 | 71 | /** 72 | * Given a URL returns the relative file path combined from host and url hash 73 | * @param url 74 | * @returns {string} 75 | */ 76 | 77 | getImageRelativeFilePath(url) { 78 | const hostCachePath = getHostCachePathComponent(url); 79 | const cacheKey = generateCacheKey(url); 80 | 81 | return `${hostCachePath}/${cacheKey}`; 82 | }, 83 | 84 | 85 | /** 86 | * returns the url after removing all unused query params 87 | * @param url 88 | * @param useQueryParamsInCacheKey 89 | * @returns {string} 90 | */ 91 | getCacheableUrl(url, useQueryParamsInCacheKey) { 92 | const parsedUrl = new URL(url, null, true); 93 | if (_.isArray(useQueryParamsInCacheKey)) { 94 | parsedUrl.set('query', _.pick(parsedUrl.query, useQueryParamsInCacheKey)); 95 | } 96 | if (!useQueryParamsInCacheKey) { 97 | parsedUrl.set('query', {}); 98 | } 99 | return parsedUrl.toString(); 100 | } 101 | 102 | }; 103 | -------------------------------------------------------------------------------- /CachedImageExample/ios/CachedImageExample/Base.lproj/LaunchScreen.xib: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 21 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | import * as ReactNative from "react-native"; 2 | import * as React from 'react' 3 | 4 | declare module "react-native-cached-image" { 5 | namespace CachedImage { 6 | interface Image extends ReactNative.Image { 7 | /** 8 | * props for the ActivityIndicator that is shown while the image is downloaded. 9 | */ 10 | activityIndicatorProps: ReactNative.ActivityIndicatorProperties 11 | /** 12 | * component prop to set custom ActivityIndicator 13 | */ 14 | loadingIndicator: ReactNative.ComponentInterface 15 | /** 16 | * function when provided, the returned object will be used as the headers object 17 | * when sending the request to download the image. (default: () => Promise.resolve({})) 18 | */ 19 | resolveHeaders: Promise<{}> 20 | /** 21 | * array|bool an array of keys to use from the source. 22 | * uri query string or a bool value stating whether to use the entire query string or not. (default: false) 23 | */ 24 | useQueryParamsInCacheKey: string[] | boolean 25 | /** 26 | * string allows changing the root directory to use for caching. 27 | * The default directory is sufficient for most use-cases. 28 | * Images in this directory may be purged by Android automatically to free up space. 29 | * Use ImageCacheProvider.LOCATION.BUNDLE if the cached images are critical 30 | * (you will have to manage cleanup manually). 31 | * (default: ImageCacheProvider.LOCATION.CACHE) 32 | */ 33 | cacheLocation: string 34 | /** 35 | * prop to display a background image while the source image is downloaded. 36 | * This will work even in android, but will not display background image 37 | * if there you set borderRadius on this component style prop 38 | */ 39 | defaultSource: ReactNative.ImageURISource 40 | /** 41 | * prop to set placeholder image. when source.uri is null or cached failed, the fallbackSource will be display. 42 | */ 43 | fallbackSource: string 44 | } 45 | 46 | interface CacheOptions { 47 | /** an object to be used as the headers when sending the request for the url */ 48 | headers: object 49 | /** the number of seconds each url will stay in the cache. default 2 weeks */ 50 | ttl: number 51 | /** 52 | * array|bool an array of keys to use from the source. 53 | * uri query string or a bool value stating whether to use the entire query string or not. (default: false) 54 | */ 55 | useQueryParamsInCacheKey: string[] | boolean 56 | /** 57 | * the root directory to use for caching, corresponds to CachedImage prop of same name, 58 | * defaults to system cache directory 59 | */ 60 | cacheLocation: string 61 | /** true to allow self signed SSL URLs to be downloaded. default false */ 62 | allowSelfSignedSSL: boolean 63 | } 64 | 65 | interface ImageCacheProvider extends CacheOptions { 66 | /** an array of URLs to preload when the component mounts */ 67 | urlsToPreload: string[] 68 | /** control the number of concurrent downloads, usually used when the urlsToPreload array is very big. default urlsToPreload.length */ 69 | numberOfConcurrentPreloads: number 70 | /** callback for when the preload is complete and all images are cached. */ 71 | onPreloadComplete: Function 72 | } 73 | 74 | interface CacheInfoFile { 75 | filename: string 76 | lastModified: number 77 | path: string 78 | size: number 79 | type: string 80 | } 81 | 82 | interface PromiseCacheInfo { 83 | files: CacheInfoFile[] 84 | size: number 85 | } 86 | 87 | interface ImageCacheManager { 88 | /** download an image and cache the result according to the given options */ 89 | downloadAndCacheUrl(url: String, options:CacheOptions ): Promise 90 | 91 | /** Delete the cached image corresponding to the given url */ 92 | deleteUrl(urls: string, options?: CacheOptions): Promise 93 | 94 | /** 95 | * Seed the cache of a specified url with a local image 96 | * Handy if you have a local copy of a remote image, e.g. you just uploaded local to url. 97 | */ 98 | seedAndCacheUrl(url: string, seedPath: string, options?: CacheOptions): Promise 99 | 100 | /** 101 | * Clear the entire cache. 102 | */ 103 | clearCache(): Promise 104 | 105 | /** 106 | * Return info about the cache, list of files and the total size of the cache. 107 | */ 108 | getCacheInfo(options?: CacheOptions): Promise 109 | // LOCATION : { 110 | // CACHE: string 111 | // BUNDLE: string 112 | // } 113 | } 114 | interface ImageCachePreloader { 115 | preloadImages(urls: string[], imageCacheManager: ImageCacheManager, numberOfConcurrentPreloads: number): Promise 116 | } 117 | } 118 | export class CachedImage extends React.Component {} 119 | export class ImageCacheProvider extends React.Component {} 120 | export const ImageCacheManager: CachedImage.ImageCacheManager 121 | export const ImageCachePreloader: CachedImage.ImageCachePreloader 122 | } -------------------------------------------------------------------------------- /CachedImageExample/ios/CachedImageExample.xcodeproj/xcshareddata/xcschemes/CachedImageExample.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 29 | 35 | 36 | 37 | 43 | 49 | 50 | 51 | 52 | 53 | 58 | 59 | 61 | 67 | 68 | 69 | 70 | 71 | 77 | 78 | 79 | 80 | 81 | 82 | 92 | 94 | 100 | 101 | 102 | 103 | 104 | 105 | 111 | 113 | 119 | 120 | 121 | 122 | 124 | 125 | 128 | 129 | 130 | -------------------------------------------------------------------------------- /ImageCacheManager.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const _ = require('lodash'); 4 | 5 | const fsUtils = require('./utils/fsUtils'); 6 | const pathUtils = require('./utils/pathUtils'); 7 | const MemoryCache = require('react-native-clcasher/MemoryCache').default; 8 | 9 | module.exports = (defaultOptions = {}, urlCache = MemoryCache, fs = fsUtils, path = pathUtils) => { 10 | 11 | const defaultDefaultOptions = { 12 | headers: {}, 13 | ttl: 60 * 60 * 24 * 14, // 2 weeks 14 | useQueryParamsInCacheKey: false, 15 | cacheLocation: fs.getCacheDir(), 16 | allowSelfSignedSSL: false, 17 | }; 18 | 19 | // apply default options 20 | _.defaults(defaultOptions, defaultDefaultOptions); 21 | 22 | function isCacheable(url) { 23 | return _.isString(url) && (_.startsWith(url.toLowerCase(), 'http://') || _.startsWith(url.toLowerCase(), 'https://')); 24 | } 25 | 26 | function cacheUrl(url, options, getCachedFile) { 27 | if (!isCacheable(url)) { 28 | return Promise.reject(new Error('Url is not cacheable')); 29 | } 30 | // allow CachedImage to provide custom options 31 | _.defaults(options, defaultOptions); 32 | // cacheableUrl contains only the needed query params 33 | const cacheableUrl = path.getCacheableUrl(url, options.useQueryParamsInCacheKey); 34 | // note: urlCache may remove the entry if it expired so we need to remove the leftover file manually 35 | return urlCache.get(cacheableUrl) 36 | .then(fileRelativePath => { 37 | if (!fileRelativePath) { 38 | // console.log('ImageCacheManager: url cache miss', cacheableUrl); 39 | throw new Error('URL expired or not in cache'); 40 | } 41 | // console.log('ImageCacheManager: url cache hit', cacheableUrl); 42 | const cachedFilePath = `${options.cacheLocation}/${fileRelativePath}`; 43 | 44 | return fs.exists(cachedFilePath) 45 | .then((exists) => { 46 | if (exists) { 47 | return cachedFilePath 48 | } else { 49 | throw new Error('file under URL stored in url cache doesn\'t exsts'); 50 | } 51 | }); 52 | }) 53 | // url is not found in the cache or is expired 54 | .catch(() => { 55 | const fileRelativePath = path.getImageRelativeFilePath(cacheableUrl); 56 | const filePath = `${options.cacheLocation}/${fileRelativePath}` 57 | 58 | // remove expired file if exists 59 | return fs.deleteFile(filePath) 60 | // get the image to cache (download / copy / etc) 61 | .then(() => getCachedFile(filePath)) 62 | // add to cache 63 | .then(() => urlCache.set(cacheableUrl, fileRelativePath, options.ttl)) 64 | // return filePath 65 | .then(() => filePath); 66 | }); 67 | } 68 | 69 | return { 70 | 71 | /** 72 | * download an image and cache the result according to the given options 73 | * @param url 74 | * @param options 75 | * @returns {Promise} 76 | */ 77 | downloadAndCacheUrl(url, options = {}) { 78 | return cacheUrl( 79 | url, 80 | options, 81 | filePath => fs.downloadFile(url, filePath, options.headers) 82 | ); 83 | }, 84 | 85 | /** 86 | * seed the cache for a specific url with a local file 87 | * @param url 88 | * @param seedPath 89 | * @param options 90 | * @returns {Promise} 91 | */ 92 | seedAndCacheUrl(url, seedPath, options = {}) { 93 | return cacheUrl( 94 | url, 95 | options, 96 | filePath => fs.copyFile(seedPath, filePath) 97 | ); 98 | }, 99 | 100 | /** 101 | * delete the cache entry and file for a given url 102 | * @param url 103 | * @param options 104 | * @returns {Promise} 105 | */ 106 | deleteUrl(url, options = {}) { 107 | if (!isCacheable(url)) { 108 | return Promise.reject(new Error('Url is not cacheable')); 109 | } 110 | _.defaults(options, defaultOptions); 111 | const cacheableUrl = path.getCacheableUrl(url, options.useQueryParamsInCacheKey); 112 | const filePath = path.getImageFilePath(cacheableUrl, options.cacheLocation); 113 | // remove file from cache 114 | return urlCache.remove(cacheableUrl) 115 | // remove file from disc 116 | .then(() => fs.deleteFile(filePath)); 117 | }, 118 | 119 | /** 120 | * delete all cached file from the filesystem and cache 121 | * @param options 122 | * @returns {Promise} 123 | */ 124 | clearCache(options = {}) { 125 | _.defaults(options, defaultOptions); 126 | return urlCache.flush() 127 | .then(() => fs.cleanDir(options.cacheLocation)); 128 | }, 129 | 130 | /** 131 | * return info about the cache, list of files and the total size of the cache 132 | * @param options 133 | * @returns {Promise.<{file: Array, size: Number}>} 134 | */ 135 | getCacheInfo(options = {}) { 136 | _.defaults(options, defaultOptions); 137 | return fs.getDirInfo(options.cacheLocation); 138 | }, 139 | 140 | }; 141 | }; 142 | -------------------------------------------------------------------------------- /CachedImageExample/ios/CachedImageExample.xcodeproj/xcshareddata/xcschemes/CachedImageExample-tvOS.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 29 | 35 | 36 | 37 | 43 | 49 | 50 | 51 | 52 | 53 | 58 | 59 | 61 | 67 | 68 | 69 | 70 | 71 | 77 | 78 | 79 | 80 | 81 | 82 | 92 | 94 | 100 | 101 | 102 | 103 | 104 | 105 | 111 | 113 | 119 | 120 | 121 | 122 | 124 | 125 | 128 | 129 | 130 | -------------------------------------------------------------------------------- /CachedImageExample/android/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /CachedImageExample/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const React = require('react'); 4 | const ReactNative = require('react-native'); 5 | 6 | const _ = require('lodash'); 7 | 8 | const { 9 | View, 10 | ScrollView, 11 | Button, 12 | Dimensions, 13 | StyleSheet, 14 | AppRegistry, 15 | ListView, 16 | } = ReactNative; 17 | 18 | const { 19 | CachedImage, 20 | ImageCacheProvider, 21 | ImageCacheManager, 22 | } = require('react-native-cached-image'); 23 | 24 | const { 25 | width 26 | } = Dimensions.get('window'); 27 | 28 | const styles = StyleSheet.create({ 29 | container: { 30 | flex: 1, 31 | marginTop: 20 32 | }, 33 | buttons: { 34 | flexDirection: 'row' 35 | }, 36 | button: { 37 | flex: 1, 38 | alignItems: 'center', 39 | justifyContent: 'center' 40 | }, 41 | image: { 42 | width, 43 | height: 300 44 | } 45 | }); 46 | 47 | const loading = require('./loading.jpg'); 48 | 49 | const image1 = 'https://wallpaperbrowse.com/media/images/bcf39e88-5731-43bb-9d4b-e5b3b2b1fdf2.jpg'; 50 | const image2 = 'https://d22cb02g3nv58u.cloudfront.net/0.676.0/assets/images/icons/fun-types/full/baby-shower-full.jpg'; 51 | 52 | const images = [ 53 | 'https://d22cb02g3nv58u.cloudfront.net/0.676.0/assets/images/icons/fun-types/full/after-work-drinks-full.jpg', 54 | 'https://i.ytimg.com/vi/b6m-XlOxjbk/hqdefault.jpg', 55 | 'https://d22cb02g3nv58u.cloudfront.net/0.676.0/assets/images/icons/fun-types/full/wrong-image.jpg', 56 | 'https://d22cb02g3nv58u.cloudfront.net/0.676.0/assets/images/icons/fun-types/full/bar-crawl-full.jpg', 57 | 'https://d22cb02g3nv58u.cloudfront.net/0.676.0/assets/images/icons/fun-types/full/cheeseburger-full.jpg', 58 | 'https://d22cb02g3nv58u.cloudfront.net/0.676.0/assets/images/icons/fun-types/full/friendsgiving-full.jpg', 59 | 'https://d22cb02g3nv58u.cloudfront.net/0.676.0/assets/images/icons/fun-types/full/dogs-play-date-full.jpg' 60 | ]; 61 | 62 | function formatBytes(bytes, decimals) { 63 | if (bytes === 0) { 64 | return '0 B'; 65 | } 66 | const k = 1000; 67 | const dm = decimals + 1 || 3; 68 | const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; 69 | const i = Math.floor(Math.log(bytes) / Math.log(k)); 70 | return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]; 71 | } 72 | 73 | const defaultImageCacheManager = ImageCacheManager(); 74 | 75 | class CachedImageExample extends React.Component { 76 | 77 | constructor(props) { 78 | super(props); 79 | 80 | const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); 81 | this.state = { 82 | showNextImage: false, 83 | dataSource: ds.cloneWithRows(images) 84 | }; 85 | 86 | this.cacheImages = this.cacheImages.bind(this); 87 | 88 | } 89 | 90 | componentWillMount() { 91 | defaultImageCacheManager.downloadAndCacheUrl(image1); 92 | } 93 | 94 | clearCache() { 95 | defaultImageCacheManager.clearCache() 96 | .then(() => { 97 | ReactNative.Alert.alert('Cache cleared'); 98 | }); 99 | } 100 | 101 | getCacheInfo() { 102 | defaultImageCacheManager.getCacheInfo() 103 | .then(({size, files}) => { 104 | // console.log(size, files); 105 | ReactNative.Alert.alert('Cache Info', `files: ${files.length}\nsize: ${formatBytes(size)}`); 106 | }); 107 | } 108 | 109 | cacheImages() { 110 | this.setState({ 111 | dataSource: this.state.dataSource.cloneWithRows([]) 112 | }, () => { 113 | this.setState({ 114 | dataSource: this.state.dataSource.cloneWithRows(images) 115 | }); 116 | }); 117 | } 118 | 119 | renderRow(uri) { 120 | return ( 121 | 126 | ); 127 | } 128 | 129 | render() { 130 | return ( 131 | 132 | 133 |