Browse Source

feat:add react native sdk for oss

Albert Luo 6 years ago
parent
commit
bb44eb6cf5
100 changed files with 9564 additions and 1 deletions
  1. 7
    0
      .gitignore
  2. 56
    0
      .npmignore
  3. 3
    0
      Example/.babelrc
  4. 6
    0
      Example/.buckconfig
  5. 54
    0
      Example/.flowconfig
  6. 1
    0
      Example/.gitattributes
  7. 56
    0
      Example/.gitignore
  8. 1
    0
      Example/.watchmanconfig
  9. 60
    0
      Example/App.js
  10. 28
    0
      Example/CSS/global.js
  11. 112
    0
      Example/Component/AuthManager.js
  12. 95
    0
      Example/Component/BucketManager.js
  13. 50
    0
      Example/Component/DownloadManager.js
  14. 142
    0
      Example/Component/ImageProcessManager.js
  15. 112
    0
      Example/Component/ObjectManager.js
  16. 251
    0
      Example/Component/UploadManager.js
  17. 65
    0
      Example/android/app/BUCK
  18. 152
    0
      Example/android/app/build.gradle
  19. 70
    0
      Example/android/app/proguard-rules.pro
  20. 35
    0
      Example/android/app/src/main/AndroidManifest.xml
  21. 15
    0
      Example/android/app/src/main/java/com/example/MainActivity.java
  22. 49
    0
      Example/android/app/src/main/java/com/example/MainApplication.java
  23. BIN
      Example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png
  24. BIN
      Example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png
  25. BIN
      Example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png
  26. BIN
      Example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
  27. 3
    0
      Example/android/app/src/main/res/values/strings.xml
  28. 8
    0
      Example/android/app/src/main/res/values/styles.xml
  29. 24
    0
      Example/android/build.gradle
  30. 20
    0
      Example/android/gradle.properties
  31. BIN
      Example/android/gradle/wrapper/gradle-wrapper.jar
  32. 5
    0
      Example/android/gradle/wrapper/gradle-wrapper.properties
  33. 164
    0
      Example/android/gradlew
  34. 90
    0
      Example/android/gradlew.bat
  35. 8
    0
      Example/android/keystores/BUCK
  36. 4
    0
      Example/android/keystores/debug.keystore.properties
  37. 7
    0
      Example/android/settings.gradle
  38. 4
    0
      Example/app.json
  39. 4
    0
      Example/index.js
  40. 54
    0
      Example/ios/Example-tvOS/Info.plist
  41. 24
    0
      Example/ios/Example-tvOSTests/Info.plist
  42. 1476
    0
      Example/ios/Example.xcodeproj/project.pbxproj
  43. 129
    0
      Example/ios/Example.xcodeproj/xcshareddata/xcschemes/Example-tvOS.xcscheme
  44. 129
    0
      Example/ios/Example.xcodeproj/xcshareddata/xcschemes/Example.xcscheme
  45. 14
    0
      Example/ios/Example/AppDelegate.h
  46. 35
    0
      Example/ios/Example/AppDelegate.m
  47. 42
    0
      Example/ios/Example/Base.lproj/LaunchScreen.xib
  48. 38
    0
      Example/ios/Example/Images.xcassets/AppIcon.appiconset/Contents.json
  49. 6
    0
      Example/ios/Example/Images.xcassets/Contents.json
  50. 56
    0
      Example/ios/Example/Info.plist
  51. 16
    0
      Example/ios/Example/main.m
  52. 68
    0
      Example/ios/ExampleTests/ExampleTests.m
  53. 24
    0
      Example/ios/ExampleTests/Info.plist
  54. 24
    0
      Example/package.json
  55. BIN
      Example/resource/putao.jpeg
  56. 21
    0
      LICENSE
  57. 441
    0
      README-CN.md
  58. 442
    1
      README.md
  59. 19
    0
      aliyun-oss-react-native.podspec
  60. 37
    0
      android/build.gradle
  61. 6
    0
      android/src/main/AndroidManifest.xml
  62. 175
    0
      android/src/main/java/com/reactlibrary/AliyunAuthManager.java
  63. 133
    0
      android/src/main/java/com/reactlibrary/AliyunBucketManager.java
  64. 133
    0
      android/src/main/java/com/reactlibrary/AliyunDownloadManager.java
  65. 180
    0
      android/src/main/java/com/reactlibrary/AliyunObjectManager.java
  66. 410
    0
      android/src/main/java/com/reactlibrary/AliyunUploadManager.java
  67. 30
    0
      android/src/main/java/com/reactlibrary/PromiseExceptionManager.java
  68. 375
    0
      android/src/main/java/com/reactlibrary/RNAliyunOssModule.java
  69. 27
    0
      android/src/main/java/com/reactlibrary/RNAliyunOssPackage.java
  70. 21
    0
      android/src/main/java/com/reactlibrary/utils/ConfigUtils.java
  71. 76
    0
      android/src/main/java/com/reactlibrary/utils/FileUtils.java
  72. 244
    0
      index.js
  73. BIN
      ios/AliyunSDK/AliyunOSSiOS.framework/AliyunOSSiOS
  74. 20
    0
      ios/AliyunSDK/AliyunOSSiOS.framework/Headers/AliyunOSSiOS.h
  75. 26
    0
      ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSBolts.h
  76. 42
    0
      ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSCancellationToken.h
  77. 29
    0
      ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSCancellationTokenRegistration.h
  78. 60
    0
      ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSCancellationTokenSource.h
  79. 273
    0
      ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSClient.h
  80. 81
    0
      ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSCompat.h
  81. 67
    0
      ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSDefine.h
  82. 62
    0
      ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSExecutor.h
  83. 40
    0
      ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSLog.h
  84. 1303
    0
      ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSModel.h
  85. 143
    0
      ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSNetworking.h
  86. 20
    0
      ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSService.h
  87. 281
    0
      ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSTask.h
  88. 89
    0
      ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSTaskCompletionSource.h
  89. 37
    0
      ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSUtil.h
  90. 6
    0
      ios/AliyunSDK/AliyunOSSiOS.framework/Modules/module.modulemap
  91. 12
    0
      ios/RNAliyunOSS+AUTH.h
  92. 78
    0
      ios/RNAliyunOSS+AUTH.m
  93. 12
    0
      ios/RNAliyunOSS+BUCKET.h
  94. 97
    0
      ios/RNAliyunOSS+BUCKET.m
  95. 12
    0
      ios/RNAliyunOSS+DOWNLOAD.h
  96. 65
    0
      ios/RNAliyunOSS+DOWNLOAD.m
  97. 12
    0
      ios/RNAliyunOSS+LOG.h
  98. 19
    0
      ios/RNAliyunOSS+LOG.m
  99. 12
    0
      ios/RNAliyunOSS+MULTIPARTUPLOAD.h
  100. 0
    0
      ios/RNAliyunOSS+MULTIPARTUPLOAD.m

+ 7
- 0
.gitignore View File

@@ -0,0 +1,7 @@
1
+android/build/
2
+android/aliyun-oss-react-native.iml
3
+node_modules/
4
+.idea
5
+.DS_Store
6
+Example/ios/Pods/
7
+package-lock.json

+ 56
- 0
.npmignore View File

@@ -0,0 +1,56 @@
1
+# IntelliJ project files
2
+.idea
3
+*.iml
4
+out
5
+gen
6
+
7
+Example/
8
+.gitignore
9
+
10
+.vscode
11
+
12
+# typings
13
+#
14
+typings
15
+typings.json
16
+# OSX
17
+#
18
+.DS_Store
19
+
20
+# Xcode
21
+#
22
+build/
23
+*.pbxuser
24
+!default.pbxuser
25
+*.mode1v3
26
+!default.mode1v3
27
+*.mode2v3
28
+!default.mode2v3
29
+*.perspectivev3
30
+!default.perspectivev3
31
+xcuserdata
32
+*.xccheckout
33
+*.moved-aside
34
+DerivedData
35
+*.hmap
36
+*.ipa
37
+*.xcuserstate
38
+project.xcworkspace
39
+
40
+# Android/IJ
41
+#
42
+*.iml
43
+.idea
44
+.gradle
45
+local.properties
46
+
47
+# node.js
48
+#
49
+node_modules/
50
+npm-debug.log
51
+
52
+# BUCK
53
+buck-out/
54
+\.buckd/
55
+android/app/libs
56
+android/keystores/debug.keystore

+ 3
- 0
Example/.babelrc View File

@@ -0,0 +1,3 @@
1
+{
2
+  "presets": ["react-native"]
3
+}

+ 6
- 0
Example/.buckconfig View File

@@ -0,0 +1,6 @@
1
+
2
+[android]
3
+  target = Google Inc.:Google APIs:23
4
+
5
+[maven_repositories]
6
+  central = https://repo1.maven.org/maven2

+ 54
- 0
Example/.flowconfig View File

@@ -0,0 +1,54 @@
1
+[ignore]
2
+; We fork some components by platform
3
+.*/*[.]android.js
4
+
5
+; Ignore "BUCK" generated dirs
6
+<PROJECT_ROOT>/\.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
+
16
+; Ignore polyfills
17
+.*/Libraries/polyfills/.*
18
+
19
+; Ignore metro
20
+.*/node_modules/metro/.*
21
+
22
+[include]
23
+
24
+[libs]
25
+node_modules/react-native/Libraries/react-native/react-native-interface.js
26
+node_modules/react-native/flow/
27
+node_modules/react-native/flow-github/
28
+
29
+[options]
30
+emoji=true
31
+
32
+module.system=haste
33
+
34
+munge_underscores=true
35
+
36
+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'
37
+
38
+module.file_ext=.js
39
+module.file_ext=.jsx
40
+module.file_ext=.json
41
+module.file_ext=.native.js
42
+
43
+suppress_type=$FlowIssue
44
+suppress_type=$FlowFixMe
45
+suppress_type=$FlowFixMeProps
46
+suppress_type=$FlowFixMeState
47
+
48
+suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(<VERSION>\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)
49
+suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(<VERSION>\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)?:? #[0-9]+
50
+suppress_comment=\\(.\\|\n\\)*\\$FlowFixedInNextDeploy
51
+suppress_comment=\\(.\\|\n\\)*\\$FlowExpectedError
52
+
53
+[version]
54
+^0.67.0

+ 1
- 0
Example/.gitattributes View File

@@ -0,0 +1 @@
1
+*.pbxproj -text

+ 56
- 0
Example/.gitignore View File

@@ -0,0 +1,56 @@
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
+*.keystore
43
+
44
+# fastlane
45
+#
46
+# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
47
+# screenshots whenever they are needed.
48
+# For more information about the recommended setup visit:
49
+# https://docs.fastlane.tools/best-practices/source-control/
50
+
51
+*/fastlane/report.xml
52
+*/fastlane/Preview.html
53
+*/fastlane/screenshots
54
+
55
+# Bundle artifact
56
+*.jsbundle

+ 1
- 0
Example/.watchmanconfig View File

@@ -0,0 +1 @@
1
+{}

+ 60
- 0
Example/App.js View File

@@ -0,0 +1,60 @@
1
+import React, { Component } from 'react';
2
+
3
+import {
4
+  StyleSheet,
5
+  View,
6
+  ScrollView,
7
+} from 'react-native';
8
+
9
+import { AuthManager } from './Component/AuthManager'
10
+import { UploadManager } from './Component/UploadManager'
11
+import { DownloadManager } from './Component/DownloadManager'
12
+import { ImageProcessManager } from './Component/ImageProcessManager'
13
+import { BucketManager } from './Component/BucketManager'
14
+import { ObjectManager } from './Component/ObjectManager'
15
+
16
+import AliyunOSS from 'aliyun-oss-react-native'
17
+//open log 
18
+AliyunOSS.enableDevMode()
19
+// defalut configraiton
20
+const configuration = {
21
+   maxRetryCount: 3,  
22
+   timeoutIntervalForRequest: 30,
23
+   timeoutIntervalForResource: 24 * 60 * 60
24
+};
25
+const config = {
26
+  AccessKey: 'XXX',
27
+  SecretKey: 'XXX',
28
+};
29
+const endPoint = 'oss-cn-zhangjiakou.aliyuncs.com';
30
+const companyserver = "http://XXX:PORT";
31
+const familyserver = "http://XXX:PORT";
32
+
33
+// AliyunOSS.initWithPlainTextAccessKey(config.AccessKey, config.SecretKey, endPoint, configuration);
34
+AliyunOSS.initWithServerSTS(familyserver,endPoint, configuration)
35
+
36
+type Props = {};
37
+
38
+export default class App extends Component<Props> {
39
+  render() {
40
+    return (
41
+      <ScrollView>
42
+        <View style={styles.container}>
43
+          <AuthManager/>
44
+          <UploadManager/>
45
+          <DownloadManager/>
46
+          <ImageProcessManager/>
47
+          <BucketManager/>
48
+          <ObjectManager/>
49
+        </View>
50
+     </ScrollView>
51
+    );
52
+  }
53
+}
54
+const styles = StyleSheet.create({
55
+  container: {
56
+    flexDirection:'column',
57
+    backgroundColor: '#F5FCFF',
58
+    flexWrap:'wrap'
59
+  }
60
+});

+ 28
- 0
Example/CSS/global.js View File

@@ -0,0 +1,28 @@
1
+
2
+import { StyleSheet } from 'react-native'
3
+
4
+export const styles = StyleSheet.create({
5
+  container: {
6
+    flexDirection:'column',
7
+    backgroundColor: '#F5FCFF',
8
+    flexWrap:'wrap'
9
+  },
10
+  description: {
11
+    fontSize:20,
12
+    marginTop:10,
13
+    marginLeft:10,
14
+    marginBottom:20
15
+  },
16
+  item: {
17
+    justifyContent:'space-around',
18
+    marginBottom:10
19
+  },
20
+  button:{
21
+    margin:10
22
+  },
23
+  detailitem: {
24
+    flexDirection:'row',
25
+    justifyContent:'flex-start',
26
+    flexWrap:'wrap'
27
+  }
28
+});

+ 112
- 0
Example/Component/AuthManager.js View File

@@ -0,0 +1,112 @@
1
+import React, { Component } from 'react';
2
+import {
3
+  Platform,
4
+  StyleSheet,
5
+  Text,
6
+  View,
7
+  Alert,
8
+  Button,
9
+  ScrollView,
10
+  Image
11
+} from 'react-native';
12
+
13
+
14
+const configuration = {
15
+   maxRetryCount: 3,  
16
+   timeoutIntervalForRequest: 30,
17
+   timeoutIntervalForResource: 24 * 60 * 60
18
+};
19
+
20
+const config = {
21
+  AccessKey: 'XXX',
22
+  SecretKey: 'XXX',
23
+};
24
+
25
+const STSConfig = {
26
+  AccessKeyId:'XXX',
27
+  SecretKeyId:'XXX',
28
+  SecurityToken:'XXX'
29
+}
30
+
31
+const endPoint = 'oss-cn-zhangjiakou.aliyuncs.com';
32
+const companyserver = "http://XXX:PORT"
33
+const familyserver = "http://XXX:PORT"
34
+
35
+//导入样式
36
+import { styles } from '../CSS/global.js' 
37
+
38
+export class AuthManager extends Component {
39
+  
40
+  render() {
41
+    return (
42
+      <View style={styles.item}>
43
+        <Text style={styles.description}>Client初始化</Text>
44
+        <View style={styles.detailitem}>
45
+          
46
+          <View style={styles.button}>
47
+            <Button
48
+              onPress={this.handClick.bind(this,"AKSK")}
49
+              title="AKSK明文"
50
+              color="#841584"
51
+            />
52
+          </View> 
53
+        
54
+          <View style={styles.button}>
55
+            <Button  style={styles.button}
56
+              onPress={this.handClick.bind(this,"Singer")}
57
+              title="自签"
58
+              color="#841584"
59
+            />
60
+          </View>
61
+
62
+          <View style={styles.button}>
63
+            <Button  style={styles.button}
64
+              onPress={this.handClick.bind(this,"STS")}
65
+              title="STS"
66
+              color="#841584"
67
+            />
68
+          </View>
69
+
70
+          <View style={styles.button}>
71
+            <Button  style={styles.button}
72
+              onPress={this.handClick.bind(this,"ServerSTS")}
73
+              title="Server STS"
74
+              color="#841584"
75
+            />
76
+          </View>
77
+        </View>
78
+      </View>
79
+    )
80
+  }
81
+
82
+  handClick(e) {
83
+    switch(e) {
84
+
85
+      case 'AKSK' : {
86
+        Alert.alert(Platform.OS);
87
+        if (Platform.OS == 'ios') {
88
+          AliyunOSS.initWithPlainTextAccessKey(config.AccessKey,config.SecretKey,endPoint,configuration);
89
+          Alert.alert("initAKSK success!")
90
+        } else {
91
+          Alert.alert('android do not support AK SK ,please use initWithSTS')
92
+        }
93
+      } break;
94
+
95
+      case 'Singer' : {
96
+        Alert.alert('initAKSK')
97
+      } break;
98
+
99
+      case "STS": {
100
+        AliyunOSS.initWithSecurityToken(STSConfig.SecurityToken,STSConfig.AccessKeyId,STSConfig.SecretKeyId,endPoint,configuration)
101
+        Alert.alert('STS success!')
102
+      } break;
103
+
104
+      case "ServerSTS" : {
105
+        AliyunOSS.initWithServerSTS(familyserver,endPoint, configuration)
106
+        Alert.alert('initServerSTS Success!')
107
+      } break;
108
+
109
+      default: break;
110
+     }
111
+  }
112
+}

+ 95
- 0
Example/Component/BucketManager.js View File

@@ -0,0 +1,95 @@
1
+import React, { Component } from 'react';
2
+import {
3
+  Platform,
4
+  StyleSheet,
5
+  Text,
6
+  View,
7
+  Alert,
8
+  Button,
9
+  ScrollView,
10
+  Image
11
+} from 'react-native';
12
+
13
+//导入样式
14
+import { styles } from '../CSS/global.js' 
15
+
16
+export class BucketManager extends Component {
17
+
18
+  render() {  
19
+    return ( 
20
+      <View style={styles.item}>
21
+        <Text style={styles.description}>管理Bucket</Text>
22
+        <View style={styles.detailitem}>
23
+            <View style={styles.button}>
24
+             <Button  style={styles.button}
25
+                onPress={this.handClick.bind(this,"asyncCreateBucket")}
26
+                title="创建bucket"
27
+                color="#841584"/>
28
+            </View>
29
+          <View style={styles.button}>
30
+            <Button style={styles.button}
31
+              onPress={this.handClick.bind(this,"getBucketACL")}
32
+              title="获取Bucket ACL "
33
+              color="#841584"
34
+            />
35
+          </View>
36
+          <View style={styles.button}>
37
+            <Button  style={styles.button}
38
+              onPress={this.handClick.bind(this,"getAllBuckets")}
39
+              title="获取所有bucket"
40
+              color="#841584"
41
+            />
42
+          </View>
43
+          <View style={styles.button}>
44
+            <Button  style={styles.button}
45
+              onPress={this.handClick.bind(this,"deleteBucket")}
46
+              title="删除bucket"
47
+              color="#841584"
48
+            />
49
+          </View>
50
+        </View>
51
+      </View>
52
+    )  
53
+  }
54
+
55
+  handClick(e) {
56
+    switch(e){
57
+      
58
+      case 'asyncCreateBucket': {
59
+        AliyunOSS.asyncCreateBucket('tyluoluo','private','oss-cn-zhangjiakou').then((e)=>{
60
+          console.log(e)
61
+        }).catch((e)=>{
62
+          console.log(e)
63
+        })
64
+      } break;
65
+
66
+      case "getBucketACL": {
67
+        
68
+        AliyunOSS.asyncGetBucketACL('luozhang002').then((e)=>{
69
+          console.log(e)
70
+        }).catch((e)=>{
71
+          console.log(e)
72
+        }) 
73
+      } break;
74
+
75
+      case "getAllBuckets": {
76
+        
77
+        AliyunOSS.asyncListBuckets().then((e) => {
78
+            console.log(e)
79
+          }).catch((e)=>{
80
+            console.log(e)
81
+        })
82
+      } break;
83
+
84
+      case 'deleteBucket': {
85
+        AliyunOSS.asyncDeleteBucket("tyluoluo").then((e)=>{
86
+          console.log(e)
87
+        }).catch((e)=>{
88
+          console.log(e)
89
+        })
90
+      } break;
91
+
92
+      default:break;
93
+    } 
94
+  } 
95
+ }

+ 50
- 0
Example/Component/DownloadManager.js View File

@@ -0,0 +1,50 @@
1
+import React, { Component } from 'react';
2
+
3
+import {
4
+  Platform,
5
+  StyleSheet,
6
+  Text,
7
+  View,
8
+  Alert,
9
+  Button,
10
+  ScrollView,
11
+  Image,
12
+  DeviceEventEmitter
13
+} from 'react-native';
14
+
15
+//导入样式
16
+import { styles } from '../CSS/global.js' 
17
+
18
+export class DownloadManager extends Component {
19
+	render() {
20
+		return (
21
+    	<View style={styles.item}>
22
+    	  <Text style={styles.description}>文件下载</Text>
23
+    	  <View style={styles.detailitem}>
24
+    	    <View style={styles.button}>
25
+    	      <Button
26
+    	        onPress={this.handClick}
27
+    	        title="下载文件"
28
+    	        color="#841584"
29
+    	      />
30
+    	    </View>        
31
+    	  </View>
32
+    	</View>
33
+		)
34
+	}
35
+	handClick() {
36
+    console.log("准备下载")
37
+    AliyunOSS.asyncDownload('luozhang002','yanxing').then((e)=>{
38
+      Alert.alert(e)
39
+      console.log(e)
40
+    }).catch((e)=>{
41
+      console.log(e)
42
+    })
43
+  }
44
+
45
+  componentDidMount(){
46
+    const downloadProgress = p => console.log(p.currentSize / p.totalSize);
47
+    AliyunOSS.addEventListener('downloadProgress', downloadProgress);
48
+  }
49
+
50
+}

+ 142
- 0
Example/Component/ImageProcessManager.js View File

@@ -0,0 +1,142 @@
1
+import React, { Component } from 'react';
2
+import {
3
+  Platform,
4
+  StyleSheet,
5
+  Text,
6
+  View,
7
+  Alert,
8
+  Button,
9
+  ScrollView,
10
+  Image
11
+} from 'react-native';
12
+
13
+//导入样式
14
+import { styles } from '../CSS/global.js' 
15
+
16
+export class ImageProcessManager extends Component {
17
+
18
+	render() {
19
+		return (
20
+      <View style={styles.item}>
21
+        <Text style={styles.description}>图片处理</Text>      
22
+        <View style={styles.detailitem}>  
23
+          
24
+          <View style={styles.button}>
25
+            <Button  style={styles.button}
26
+              onPress={this.handClick.bind(this,"GeShi")}
27
+              title="格式转换"
28
+              color="#841584"
29
+            />
30
+          </View>
31
+
32
+          <View style={styles.button}>
33
+            <Button  style={styles.button}
34
+              onPress={this.handClick.bind(this,"Scale")}
35
+              title="缩放比例"
36
+              color="#841584"
37
+            />
38
+          </View>
39
+
40
+          <View style={styles.button}>
41
+            <Button  style={styles.button}
42
+              onPress={this.handClick.bind(this,"Cut")}
43
+              title="裁剪比例"
44
+              color="#841584"
45
+            />
46
+          </View>
47
+
48
+          <View style={styles.button}>
49
+            <Button  style={styles.button}
50
+              onPress={this.handClick.bind(this,"Rotate")}
51
+              title="旋转操作"
52
+              color="#841584"
53
+            />
54
+          </View>
55
+
56
+          <View style={styles.button}>
57
+            <Button  style={styles.button}
58
+              onPress={this.handClick.bind(this,"Effect")}
59
+              title="图片效果"
60
+              color="#841584"
61
+            />
62
+          </View>
63
+
64
+          <View style={styles.button}>
65
+            <Button  style={styles.button}
66
+              onPress={this.handClick.bind(this,"ShuiYin")}
67
+              title="水印操作"
68
+              color="#841584"
69
+            />
70
+          </View>
71
+
72
+        </View>
73
+      </View>
74
+		)
75
+	}
76
+
77
+  handClick (e) {
78
+    switch (e) {
79
+      
80
+      case "GeShi" : {
81
+        //备注第三个参数必须穿入字符串
82
+        AliyunOSS.asyncDownload('luozhang002','yanxing',"",{"x-oss-process":'image/format,jpg'}).then((e)=>{
83
+          Alert.alert(e)
84
+          console.log(e)
85
+        }).catch((e)=>{
86
+          console.log(e)
87
+        })
88
+      } break;
89
+
90
+
91
+      case 'Scale': {
92
+        AliyunOSS.asyncDownload('luozhang002','yanxing',"",{"x-oss-process":'image/resize,h_100'}).then((e)=>{
93
+          Alert.alert(e)
94
+          console.log(e)
95
+        }).catch((e) => {
96
+          console.log(e)
97
+        })
98
+      } break;
99
+
100
+      case 'cut' : {
101
+        AliyunOSS.asyncDownload('luozhang002','yanxing',"",{"x-oss-process":'image/circle,r_100'}).then((e)=>{
102
+          Alert.alert(e)
103
+          console.log(e)
104
+        }).catch((e)=>{
105
+          console.log(e)
106
+        })
107
+      } break;
108
+
109
+      case 'Rotate': {
110
+        AliyunOSS.asyncDownload('luozhang002','yanxing',"",{"x-oss-process":'image/resize,w_100/auto-orient,1'}).then((e)=>{
111
+          Alert.alert(e)
112
+          console.log(e)
113
+        }).catch((e)=>{
114
+          console.log(e)
115
+        })
116
+      } break;
117
+
118
+      case "Effect": {
119
+         // image/bright,50
120
+        AliyunOSS.asyncDownload('luozhang002','yanxing',"",{"x-oss-process":'image/bright,50'}).then((e)=>{
121
+          Alert.alert(e)
122
+          console.log(e)
123
+        }).catch((e)=>{
124
+          console.log(e)
125
+        })
126
+      } break;
127
+
128
+      case "ShuiYin" : {
129
+        let xOss = "image/resize,w_400/watermark,image_cGFuZGEucG5nP3gtb3NzLXByb2Nlc3M9aW1hZ2UvcmVzaXplLFBfMzA,t_90,g_se,x_10,y_10"
130
+        AliyunOSS.asyncDownload('luozhang002','zhongji',"",{"x-oss-process":xOss}).then((e)=>{
131
+          Alert.alert(e)
132
+          console.log(e)
133
+        }).catch((e)=>{
134
+          console.log(e)
135
+        })
136
+      } break;
137
+
138
+      default : break;
139
+    } //end switch 
140
+
141
+  }
142
+}

+ 112
- 0
Example/Component/ObjectManager.js View File

@@ -0,0 +1,112 @@
1
+import React, { Component } from 'react';
2
+import {
3
+  Platform,
4
+  StyleSheet,
5
+  Text,
6
+  View,
7
+  Alert,
8
+  Button,
9
+  ScrollView,
10
+  Image
11
+} from 'react-native';
12
+
13
+//导入样式
14
+import { styles } from '../CSS/global.js' 
15
+
16
+export class ObjectManager extends Component {  
17
+  render() {  
18
+     return(
19
+           <View style={styles.item}>
20
+      <Text style={styles.description}>管理文件</Text>
21
+      <View style={styles.detailitem}>
22
+        <View style={styles.button}>
23
+          <Button  style={styles.button}
24
+            onPress={this.clickHandle.bind(this,"asyncHeadObject")}
25
+            title="asyncHeadObject"
26
+            color="#841584"
27
+          />
28
+        </View>
29
+
30
+        <View style={styles.button}>
31
+          <Button  style={styles.button}
32
+            onPress={this.clickHandle.bind(this,"asyncListObjects")}
33
+            title="asyncListObjects"
34
+            color="#841584"
35
+          />
36
+        </View>
37
+
38
+        <View style={styles.button}>
39
+          <Button  style={styles.button}
40
+            onPress={this.clickHandle.bind(this,"asyncCopyObject")}
41
+            title="asyncCopyObject"
42
+            color="#841584"
43
+          />
44
+        </View>
45
+
46
+        <View style={styles.button}>
47
+          <Button  style={styles.button}
48
+            onPress={this.clickHandle.bind(this,"doesObjectExist")}
49
+            title="doesObjectExist"
50
+            color="#841584"
51
+          />
52
+        </View>
53
+
54
+        <View style={styles.button}>
55
+          <Button  style={styles.button}
56
+            onPress={this.clickHandle.bind(this,"asyncDeleteObject")}
57
+            title="asyncDeleteObject"
58
+            color="#841584"
59
+          />
60
+        </View>
61
+      </View>
62
+    </View>
63
+     )  
64
+  } 
65
+  clickHandle(e) {
66
+    switch(e) {
67
+      case "asyncHeadObject" : {
68
+        AliyunOSS.asyncHeadObject('luozhang002','yanxing').then((e) => {
69
+          console.log(e)
70
+        }).catch((e)=> {
71
+          console.log(e)
72
+        })
73
+      } break;
74
+
75
+      case "asyncListObjects" : {
76
+        console.log("asyncListObjects")
77
+        AliyunOSS.asyncListObjects('luozhang002').then((e) => {
78
+          console.log(e)
79
+        }).catch((e)=>{
80
+          console.log(e)
81
+        })
82
+      } break;
83
+
84
+      case "asyncCopyObject" : {
85
+        AliyunOSS.asyncCopyObject('luozhang001',"2.png","luozhang002","sbsbsb").then((e) => {
86
+          console.log(e)
87
+        }).catch((e)=>{
88
+          console.log(e)
89
+        })
90
+      } break;
91
+
92
+      case "doesObjectExist": {
93
+        AliyunOSS.doesObjectExist('luozhang001','xx.png').then((e) => {
94
+          console.log(e)
95
+        }).catch((e)=>{
96
+          console.log(e)
97
+        })
98
+      } break;
99
+
100
+      case "asyncDeleteObject" : {
101
+        AliyunOSS.asyncDeleteObject('luozhang001','2.png').then((e)=>{
102
+          Alert.alert(e)
103
+        }).catch((e)=>{
104
+          console.log(e)
105
+        })
106
+      } break;
107
+
108
+      default :break;
109
+    }
110
+  }
111
+
112
+ }

+ 251
- 0
Example/Component/UploadManager.js View File

@@ -0,0 +1,251 @@
1
+import React, { Component } from 'react';
2
+import {
3
+  Platform,
4
+  StyleSheet,
5
+  Text,
6
+  View,
7
+  Alert,
8
+  Button,
9
+  ScrollView,
10
+  Image,
11
+  DeviceEventEmitter
12
+} from 'react-native';
13
+
14
+//保存初始化分片上传ID
15
+let uploadId;
16
+const multipartBucket = "luozhang002"
17
+const mulitipartObject = "extremlyboy"
18
+let ImagePicker = require('react-native-image-picker');
19
+
20
+//导入样式
21
+import { styles } from '../CSS/global.js' 
22
+
23
+const  options = {
24
+  title: 'Select Avatar',
25
+  customButtons: [
26
+    {name: 'fb', title: 'Choose Photo from Facebook'},
27
+  ],
28
+  storageOptions: {
29
+    skipBackup: true,
30
+    path: 'images'
31
+  }
32
+};
33
+
34
+export class UploadManager extends Component {  
35
+  render() {  
36
+    return(
37
+      <View style={styles.item}>
38
+        <Text style={styles.description}>文件上传操作</Text>
39
+        <Image source={require('../resource/putao.jpeg')}/>
40
+        <View style={styles.detailitem}>
41
+          
42
+          <View style={styles.button}>
43
+            <Button
44
+              onPress={this.handleClick.bind(this,"uploadFile")}
45
+              title="上传文件"
46
+              color="#841584"
47
+            />
48
+          </View> 
49
+        
50
+          <View style={styles.button}>
51
+            <Button  style={styles.button}
52
+              onPress={this.handleClick.bind(this,"appendObject")}
53
+              title="追加文件"
54
+              color="#841584"
55
+            />
56
+          </View>
57
+
58
+          <View style={styles.button}>
59
+            <Button  style={styles.button}
60
+              onPress={this.handleClick.bind(this,"resumeObject")}
61
+              title="断点续传"
62
+              color="#841584"
63
+            />
64
+          </View>
65
+
66
+          <View style={styles.button}>
67
+            <Button  style={styles.button}
68
+              onPress={this.handleClick.bind(this,"initMultipartUpload")}
69
+              title="初始化分片"
70
+              color="#841584"
71
+            />
72
+          </View>
73
+
74
+          <View style={styles.button}>
75
+            <Button  style={styles.button}
76
+              onPress={this.handleClick.bind(this,"multipartUpload")}
77
+              title="分片上传"
78
+              color="#841584"
79
+            />
80
+          </View>
81
+
82
+          <View style={styles.button}>
83
+            <Button  style={styles.button}
84
+              onPress={this.handleClick.bind(this,"abortMultipartUpload")}
85
+              title="取消分片上传"
86
+              color="#841584"
87
+            />
88
+          </View>
89
+
90
+          <View style={styles.button}>
91
+            <Button  style={styles.button}
92
+              onPress={this.handleClick.bind(this,"listParts")}
93
+              title="列出分片"
94
+              color="#841584"
95
+            />
96
+          </View>
97
+        </View>
98
+      </View>
99
+    )  
100
+  }
101
+
102
+  handleClick(e) {
103
+    switch (e) {
104
+
105
+      case 'uploadFile' : {
106
+        console.log("准备上传")
107
+        ImagePicker.showImagePicker(options, (response) => {
108
+          console.log('Response = ', response);
109
+          if (response.didCancel) {
110
+            console.log('User cancelled image picker');
111
+          }
112
+          else if (response.error) {
113
+            console.log('ImagePicker Error: ', response.error);
114
+          }
115
+          else if (response.customButton) {
116
+            console.log('User tapped custom button: ', response.customButton);
117
+          }
118
+          else {
119
+            
120
+            let source = { uri: response.uri };
121
+            
122
+            AliyunOSS.asyncUpload("luozhang002", "xxxxxxxx/yanxing", source.uri).then((res)=>{
123
+              Alert.alert(
124
+                'Alert Title',
125
+                "恭喜你成功上传到阿里云服务器",
126
+                [
127
+                  {text: 'Ask me later', onPress: () => console.log('Ask me later pressed')},
128
+                  {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
129
+                  {text: 'OK', onPress: () => console.log('OK Pressed')},
130
+                ],
131
+                { cancelable: false }
132
+              )
133
+            })
134
+          }
135
+        });
136
+      } break;
137
+
138
+      case "appendObject" : {
139
+
140
+         ImagePicker.showImagePicker(options, (response) => {
141
+          console.log('Response = ', response);
142
+          if (response.didCancel) {
143
+            console.log('User cancelled image picker');
144
+          }
145
+          else if (response.error) {
146
+            console.log('ImagePicker Error: ', response.error);
147
+          }
148
+          else if (response.customButton) {
149
+            console.log('User tapped custom button: ', response.customButton);
150
+          }
151
+          else {
152
+            
153
+            let source = { uri: response.uri };
154
+            let position = 0;
155
+            AliyunOSS.asyncAppendObject("luozhang002", "xxx", source.uri,{appendPostion:`${position}`}).then((res)=>{
156
+              nextPositon = res.nextPositon;
157
+              //再次调用即可
158
+            })
159
+          }
160
+        });
161
+      } break;
162
+
163
+      case "resumeObject" : {  
164
+        ImagePicker.showImagePicker(options, (response) => {
165
+          console.log('Response = ', response);
166
+          if (response.didCancel) {
167
+            console.log('User cancelled image picker');
168
+          }
169
+          else if (response.error) {
170
+            console.log('ImagePicker Error: ', response.error);
171
+          }
172
+          else if (response.customButton) {
173
+            console.log('User tapped custom button: ', response.customButton);
174
+          }
175
+          else {
176
+            let source = { uri: response.uri };
177
+            AliyunOSS.asyncResumableUpload("luozhang002", "zhongji", source.uri).then((res)=>{
178
+              Alert.alert(
179
+                'Alert Title',
180
+                "恭喜你上传成功",
181
+                [
182
+                  {text: 'Ask me later', onPress: () => console.log('Ask me later pressed')},
183
+                  {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
184
+                  {text: 'OK', onPress: () => console.log('OK Pressed')},
185
+                ],
186
+                { cancelable: false }
187
+                )
188
+            })
189
+          }
190
+        });
191
+      } break;
192
+
193
+      case "initMultipartUpload" : {
194
+        AliyunOSS.initMultipartUpload(multipartBucket,multipartBucket).then((e)=>{
195
+          Alert.alert("分片初始化成功:" + e);
196
+          uploadId = e;
197
+        }).catch((error)=>{
198
+          console.log(error)
199
+        })
200
+      } break
201
+
202
+      case "multipartUpload" : {
203
+        
204
+        ImagePicker.showImagePicker(options, (response) => {
205
+          console.log('Response = ', response);
206
+
207
+          if (response.didCancel) {
208
+            console.log('User cancelled image picker');
209
+          } else if (response.error) {
210
+            console.log('ImagePicker Error: ', response.error);
211
+          } else if (response.customButton) {
212
+            console.log('User tapped custom button: ', response.customButton);
213
+          } else {
214
+            let source = { uri: response.uri };
215
+            AliyunOSS.multipartUpload(multipartBucket,mulitipartObject,uploadId,source.uri).then((res)=>{
216
+              Alert.alert("分片上传成功");
217
+            }).catch((e)=>{
218
+              Alert.alert("分片上传失败");
219
+            })
220
+          }
221
+        });
222
+      } break;
223
+
224
+      case "abortMultipartUpload" : {
225
+        AliyunOSS.abortMultipartUpload(multipartBucket,multipartBucket,uploadId).then((e)=>{
226
+          Alert.alert("分片终止成功");
227
+        }).catch((e)=>{
228
+          Alert.alert("分片终止失败");
229
+        })
230
+      } break;
231
+
232
+      case "listParts" : {
233
+
234
+        AliyunOSS.listParts(multipartBucket,multipartBucket,uploadId).then((e)=>{
235
+          Alert.alert("onListParts"+e)
236
+        }).catch((e)=>{
237
+          Alert.alert("onListPartsError")
238
+        })
239
+
240
+      } break;
241
+
242
+      default : break;
243
+    }
244
+  }
245
+
246
+  componentDidMount() {
247
+    const uploadProgress = p => console.log(p.currentSize / p.totalSize);
248
+    AliyunOSS.addEventListener('uploadProgress', uploadProgress);
249
+  }
250
+  
251
+ }

+ 65
- 0
Example/android/app/BUCK View File

@@ -0,0 +1,65 @@
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.example",
49
+)
50
+
51
+android_resource(
52
+    name = "res",
53
+    package = "com.example",
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
+)

+ 152
- 0
Example/android/app/build.gradle View File

@@ -0,0 +1,152 @@
1
+apply plugin: "com.android.application"
2
+
3
+import com.android.build.OutputFile
4
+
5
+/**
6
+ * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
7
+ * and bundleReleaseJsAndAssets).
8
+ * These basically call `react-native bundle` with the correct arguments during the Android build
9
+ * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
10
+ * bundle directly from the development server. Below you can see all the possible configurations
11
+ * and their defaults. If you decide to add a configuration block, make sure to add it before the
12
+ * `apply from: "../../node_modules/react-native/react.gradle"` line.
13
+ *
14
+ * project.ext.react = [
15
+ *   // the name of the generated asset file containing your JS bundle
16
+ *   bundleAssetName: "index.android.bundle",
17
+ *
18
+ *   // the entry file for bundle generation
19
+ *   entryFile: "index.android.js",
20
+ *
21
+ *   // whether to bundle JS and assets in debug mode
22
+ *   bundleInDebug: false,
23
+ *
24
+ *   // whether to bundle JS and assets in release mode
25
+ *   bundleInRelease: true,
26
+ *
27
+ *   // whether to bundle JS and assets in another build variant (if configured).
28
+ *   // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
29
+ *   // The configuration property can be in the following formats
30
+ *   //         'bundleIn${productFlavor}${buildType}'
31
+ *   //         'bundleIn${buildType}'
32
+ *   // bundleInFreeDebug: true,
33
+ *   // bundleInPaidRelease: true,
34
+ *   // bundleInBeta: true,
35
+ *
36
+ *   // whether to disable dev mode in custom build variants (by default only disabled in release)
37
+ *   // for example: to disable dev mode in the staging build type (if configured)
38
+ *   devDisabledInStaging: true,
39
+ *   // The configuration property can be in the following formats
40
+ *   //         'devDisabledIn${productFlavor}${buildType}'
41
+ *   //         'devDisabledIn${buildType}'
42
+ *
43
+ *   // the root of your project, i.e. where "package.json" lives
44
+ *   root: "../../",
45
+ *
46
+ *   // where to put the JS bundle asset in debug mode
47
+ *   jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
48
+ *
49
+ *   // where to put the JS bundle asset in release mode
50
+ *   jsBundleDirRelease: "$buildDir/intermediates/assets/release",
51
+ *
52
+ *   // where to put drawable resources / React Native assets, e.g. the ones you use via
53
+ *   // require('./image.png')), in debug mode
54
+ *   resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
55
+ *
56
+ *   // where to put drawable resources / React Native assets, e.g. the ones you use via
57
+ *   // require('./image.png')), in release mode
58
+ *   resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
59
+ *
60
+ *   // by default the gradle tasks are skipped if none of the JS files or assets change; this means
61
+ *   // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
62
+ *   // date; if you have any other folders that you want to ignore for performance reasons (gradle
63
+ *   // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
64
+ *   // for example, you might want to remove it from here.
65
+ *   inputExcludes: ["android/**", "ios/**"],
66
+ *
67
+ *   // override which node gets called and with what additional arguments
68
+ *   nodeExecutableAndArgs: ["node"],
69
+ *
70
+ *   // supply additional arguments to the packager
71
+ *   extraPackagerArgs: []
72
+ * ]
73
+ */
74
+
75
+project.ext.react = [
76
+    entryFile: "index.js"
77
+]
78
+
79
+apply from: "../../node_modules/react-native/react.gradle"
80
+
81
+/**
82
+ * Set this to true to create two separate APKs instead of one:
83
+ *   - An APK that only works on ARM devices
84
+ *   - An APK that only works on x86 devices
85
+ * The advantage is the size of the APK is reduced by about 4MB.
86
+ * Upload all the APKs to the Play Store and people will download
87
+ * the correct one based on the CPU architecture of their device.
88
+ */
89
+def enableSeparateBuildPerCPUArchitecture = false
90
+
91
+/**
92
+ * Run Proguard to shrink the Java bytecode in release builds.
93
+ */
94
+def enableProguardInReleaseBuilds = false
95
+
96
+android {
97
+    compileSdkVersion 23
98
+    buildToolsVersion "23.0.1"
99
+
100
+    defaultConfig {
101
+        applicationId "com.example"
102
+        minSdkVersion 16
103
+        targetSdkVersion 22
104
+        versionCode 1
105
+        versionName "1.0"
106
+        ndk {
107
+            abiFilters "armeabi-v7a", "x86"
108
+        }
109
+    }
110
+    splits {
111
+        abi {
112
+            reset()
113
+            enable enableSeparateBuildPerCPUArchitecture
114
+            universalApk false  // If true, also generate a universal APK
115
+            include "armeabi-v7a", "x86"
116
+        }
117
+    }
118
+    buildTypes {
119
+        release {
120
+            minifyEnabled enableProguardInReleaseBuilds
121
+            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
122
+        }
123
+    }
124
+    // applicationVariants are e.g. debug, release
125
+    applicationVariants.all { variant ->
126
+        variant.outputs.each { output ->
127
+            // For each separate APK per architecture, set a unique version code as described here:
128
+            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
129
+            def versionCodes = ["armeabi-v7a":1, "x86":2]
130
+            def abi = output.getFilter(OutputFile.ABI)
131
+            if (abi != null) {  // null for the universal-debug, universal-release variants
132
+                output.versionCodeOverride =
133
+                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
134
+            }
135
+        }
136
+    }
137
+}
138
+
139
+dependencies {
140
+    compile project(':react-native-image-picker')
141
+    compile project(':aliyun-oss-react-native')
142
+    compile fileTree(dir: "libs", include: ["*.jar"])
143
+    compile "com.android.support:appcompat-v7:23.0.1"
144
+    compile "com.facebook.react:react-native:+"  // From node_modules
145
+}
146
+
147
+// Run this once to be able to run the application with BUCK
148
+// puts all compile dependencies into folder libs for BUCK to use
149
+task copyDownloadableDepsToLibs(type: Copy) {
150
+    from configurations.compile
151
+    into 'libs'
152
+}

+ 70
- 0
Example/android/app/proguard-rules.pro View File

@@ -0,0 +1,70 @@
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 <methods>; }
47
+-keepclassmembers class *  { @com.facebook.react.uimanager.UIProp <fields>; }
48
+-keepclassmembers class *  { @com.facebook.react.uimanager.annotations.ReactProp <methods>; }
49
+-keepclassmembers class *  { @com.facebook.react.uimanager.annotations.ReactPropGroup <methods>; }
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.**

+ 35
- 0
Example/android/app/src/main/AndroidManifest.xml View File

@@ -0,0 +1,35 @@
1
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
2
+    xmlns:tools="http://schemas.android.com/tools"
3
+    package="com.example">
4
+
5
+    <uses-permission android:name="android.permission.INTERNET" />
6
+    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
7
+    <uses-permission android:name="android.permission.CAMERA" />
8
+    <uses-permission android:name="android.permission.INTERNET" />
9
+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
10
+    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
11
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
12
+    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"
13
+        tools:ignore="ProtectedPermissions" />
14
+
15
+    <application
16
+      android:name=".MainApplication"
17
+      android:label="@string/app_name"
18
+      android:icon="@mipmap/ic_launcher"
19
+      android:allowBackup="false"
20
+      android:theme="@style/AppTheme"
21
+      tools:replace="android:allowBackup">
22
+      <activity
23
+        android:name=".MainActivity"
24
+        android:label="@string/app_name"
25
+        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
26
+        android:windowSoftInputMode="adjustResize">
27
+        <intent-filter>
28
+            <action android:name="android.intent.action.MAIN" />
29
+            <category android:name="android.intent.category.LAUNCHER" />
30
+        </intent-filter>
31
+      </activity>
32
+      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
33
+    </application>
34
+
35
+</manifest>

+ 15
- 0
Example/android/app/src/main/java/com/example/MainActivity.java View File

@@ -0,0 +1,15 @@
1
+package com.example;
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 "Example";
14
+    }
15
+}

+ 49
- 0
Example/android/app/src/main/java/com/example/MainApplication.java View File

@@ -0,0 +1,49 @@
1
+package com.example;
2
+
3
+import android.app.Application;
4
+
5
+import com.facebook.react.ReactApplication;
6
+import com.imagepicker.ImagePickerPackage;
7
+import com.reactlibrary.RNAliyunOssPackage;
8
+import com.facebook.react.ReactNativeHost;
9
+import com.facebook.react.ReactPackage;
10
+import com.facebook.react.shell.MainReactPackage;
11
+import com.facebook.soloader.SoLoader;
12
+
13
+import java.util.Arrays;
14
+import java.util.List;
15
+
16
+public class MainApplication extends Application implements ReactApplication {
17
+
18
+  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
19
+    @Override
20
+    public boolean getUseDeveloperSupport() {
21
+      return BuildConfig.DEBUG;
22
+    }
23
+
24
+    @Override
25
+    protected List<ReactPackage> getPackages() {
26
+      return Arrays.<ReactPackage>asList(
27
+          new MainReactPackage(),
28
+            new ImagePickerPackage(),
29
+            new RNAliyunOssPackage()
30
+      );
31
+    }
32
+
33
+    @Override
34
+    protected String getJSMainModuleName() {
35
+      return "index";
36
+    }
37
+  };
38
+
39
+  @Override
40
+  public ReactNativeHost getReactNativeHost() {
41
+    return mReactNativeHost;
42
+  }
43
+
44
+  @Override
45
+  public void onCreate() {
46
+    super.onCreate();
47
+    SoLoader.init(this, /* native exopackage */ false);
48
+  }
49
+}

BIN
Example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png View File


BIN
Example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png View File


BIN
Example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png View File


BIN
Example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png View File


+ 3
- 0
Example/android/app/src/main/res/values/strings.xml View File

@@ -0,0 +1,3 @@
1
+<resources>
2
+    <string name="app_name">Example</string>
3
+</resources>

+ 8
- 0
Example/android/app/src/main/res/values/styles.xml View File

@@ -0,0 +1,8 @@
1
+<resources>
2
+
3
+    <!-- Base application theme. -->
4
+    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
5
+        <!-- Customize your theme here. -->
6
+    </style>
7
+
8
+</resources>

+ 24
- 0
Example/android/build.gradle View File

@@ -0,0 +1,24 @@
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
+}

+ 20
- 0
Example/android/gradle.properties View File

@@ -0,0 +1,20 @@
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

BIN
Example/android/gradle/wrapper/gradle-wrapper.jar View File


+ 5
- 0
Example/android/gradle/wrapper/gradle-wrapper.properties View File

@@ -0,0 +1,5 @@
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

+ 164
- 0
Example/android/gradlew View File

@@ -0,0 +1,164 @@
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 "$@"

+ 90
- 0
Example/android/gradlew.bat View File

@@ -0,0 +1,90 @@
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

+ 8
- 0
Example/android/keystores/BUCK View File

@@ -0,0 +1,8 @@
1
+keystore(
2
+    name = "debug",
3
+    properties = "debug.keystore.properties",
4
+    store = "debug.keystore",
5
+    visibility = [
6
+        "PUBLIC",
7
+    ],
8
+)

+ 4
- 0
Example/android/keystores/debug.keystore.properties View File

@@ -0,0 +1,4 @@
1
+key.store=debug.keystore
2
+key.alias=androiddebugkey
3
+key.store.password=android
4
+key.alias.password=android

+ 7
- 0
Example/android/settings.gradle View File

@@ -0,0 +1,7 @@
1
+rootProject.name = 'Example'
2
+include ':react-native-image-picker'
3
+project(':react-native-image-picker').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-image-picker/android')
4
+include ':aliyun-oss-react-native'
5
+project(':aliyun-oss-react-native').projectDir = new File(rootProject.projectDir, '../node_modules/aliyun-oss-react-native/android')
6
+
7
+include ':app'

+ 4
- 0
Example/app.json View File

@@ -0,0 +1,4 @@
1
+{
2
+  "name": "Example",
3
+  "displayName": "Example"
4
+}

+ 4
- 0
Example/index.js View File

@@ -0,0 +1,4 @@
1
+import { AppRegistry } from 'react-native';
2
+import App from './App';
3
+
4
+AppRegistry.registerComponent('Example', () => App);

+ 54
- 0
Example/ios/Example-tvOS/Info.plist View File

@@ -0,0 +1,54 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+<plist version="1.0">
4
+<dict>
5
+	<key>CFBundleDevelopmentRegion</key>
6
+	<string>en</string>
7
+	<key>CFBundleExecutable</key>
8
+	<string>$(EXECUTABLE_NAME)</string>
9
+	<key>CFBundleIdentifier</key>
10
+	<string>org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)</string>
11
+	<key>CFBundleInfoDictionaryVersion</key>
12
+	<string>6.0</string>
13
+	<key>CFBundleName</key>
14
+	<string>$(PRODUCT_NAME)</string>
15
+	<key>CFBundlePackageType</key>
16
+	<string>APPL</string>
17
+	<key>CFBundleShortVersionString</key>
18
+	<string>1.0</string>
19
+	<key>CFBundleSignature</key>
20
+	<string>????</string>
21
+	<key>CFBundleVersion</key>
22
+	<string>1</string>
23
+	<key>LSRequiresIPhoneOS</key>
24
+	<true/>
25
+	<key>UILaunchStoryboardName</key>
26
+	<string>LaunchScreen</string>
27
+	<key>UIRequiredDeviceCapabilities</key>
28
+	<array>
29
+		<string>armv7</string>
30
+	</array>
31
+	<key>UISupportedInterfaceOrientations</key>
32
+	<array>
33
+		<string>UIInterfaceOrientationPortrait</string>
34
+		<string>UIInterfaceOrientationLandscapeLeft</string>
35
+		<string>UIInterfaceOrientationLandscapeRight</string>
36
+	</array>
37
+	<key>UIViewControllerBasedStatusBarAppearance</key>
38
+	<false/>
39
+	<key>NSLocationWhenInUseUsageDescription</key>
40
+	<string></string>
41
+	<key>NSAppTransportSecurity</key>
42
+	<!--See http://ste.vn/2015/06/10/configuring-app-transport-security-ios-9-osx-10-11/ -->
43
+	<dict>
44
+		<key>NSExceptionDomains</key>
45
+		<dict>
46
+			<key>localhost</key>
47
+			<dict>
48
+				<key>NSExceptionAllowsInsecureHTTPLoads</key>
49
+				<true/>
50
+			</dict>
51
+		</dict>
52
+	</dict>
53
+</dict>
54
+</plist>

+ 24
- 0
Example/ios/Example-tvOSTests/Info.plist View File

@@ -0,0 +1,24 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+<plist version="1.0">
4
+<dict>
5
+	<key>CFBundleDevelopmentRegion</key>
6
+	<string>en</string>
7
+	<key>CFBundleExecutable</key>
8
+	<string>$(EXECUTABLE_NAME)</string>
9
+	<key>CFBundleIdentifier</key>
10
+	<string>org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)</string>
11
+	<key>CFBundleInfoDictionaryVersion</key>
12
+	<string>6.0</string>
13
+	<key>CFBundleName</key>
14
+	<string>$(PRODUCT_NAME)</string>
15
+	<key>CFBundlePackageType</key>
16
+	<string>BNDL</string>
17
+	<key>CFBundleShortVersionString</key>
18
+	<string>1.0</string>
19
+	<key>CFBundleSignature</key>
20
+	<string>????</string>
21
+	<key>CFBundleVersion</key>
22
+	<string>1</string>
23
+</dict>
24
+</plist>

+ 1476
- 0
Example/ios/Example.xcodeproj/project.pbxproj
File diff suppressed because it is too large
View File


+ 129
- 0
Example/ios/Example.xcodeproj/xcshareddata/xcschemes/Example-tvOS.xcscheme View File

@@ -0,0 +1,129 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<Scheme
3
+   LastUpgradeVersion = "0820"
4
+   version = "1.3">
5
+   <BuildAction
6
+      parallelizeBuildables = "NO"
7
+      buildImplicitDependencies = "YES">
8
+      <BuildActionEntries>
9
+         <BuildActionEntry
10
+            buildForTesting = "YES"
11
+            buildForRunning = "YES"
12
+            buildForProfiling = "YES"
13
+            buildForArchiving = "YES"
14
+            buildForAnalyzing = "YES">
15
+            <BuildableReference
16
+               BuildableIdentifier = "primary"
17
+               BlueprintIdentifier = "2D2A28121D9B038B00D4039D"
18
+               BuildableName = "libReact.a"
19
+               BlueprintName = "React-tvOS"
20
+               ReferencedContainer = "container:../node_modules/react-native/React/React.xcodeproj">
21
+            </BuildableReference>
22
+         </BuildActionEntry>
23
+         <BuildActionEntry
24
+            buildForTesting = "YES"
25
+            buildForRunning = "YES"
26
+            buildForProfiling = "YES"
27
+            buildForArchiving = "YES"
28
+            buildForAnalyzing = "YES">
29
+            <BuildableReference
30
+               BuildableIdentifier = "primary"
31
+               BlueprintIdentifier = "2D02E47A1E0B4A5D006451C7"
32
+               BuildableName = "Example-tvOS.app"
33
+               BlueprintName = "Example-tvOS"
34
+               ReferencedContainer = "container:Example.xcodeproj">
35
+            </BuildableReference>
36
+         </BuildActionEntry>
37
+         <BuildActionEntry
38
+            buildForTesting = "YES"
39
+            buildForRunning = "YES"
40
+            buildForProfiling = "NO"
41
+            buildForArchiving = "NO"
42
+            buildForAnalyzing = "YES">
43
+            <BuildableReference
44
+               BuildableIdentifier = "primary"
45
+               BlueprintIdentifier = "2D02E48F1E0B4A5D006451C7"
46
+               BuildableName = "Example-tvOSTests.xctest"
47
+               BlueprintName = "Example-tvOSTests"
48
+               ReferencedContainer = "container:Example.xcodeproj">
49
+            </BuildableReference>
50
+         </BuildActionEntry>
51
+      </BuildActionEntries>
52
+   </BuildAction>
53
+   <TestAction
54
+      buildConfiguration = "Debug"
55
+      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
56
+      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
57
+      shouldUseLaunchSchemeArgsEnv = "YES">
58
+      <Testables>
59
+         <TestableReference
60
+            skipped = "NO">
61
+            <BuildableReference
62
+               BuildableIdentifier = "primary"
63
+               BlueprintIdentifier = "2D02E48F1E0B4A5D006451C7"
64
+               BuildableName = "Example-tvOSTests.xctest"
65
+               BlueprintName = "Example-tvOSTests"
66
+               ReferencedContainer = "container:Example.xcodeproj">
67
+            </BuildableReference>
68
+         </TestableReference>
69
+      </Testables>
70
+      <MacroExpansion>
71
+         <BuildableReference
72
+            BuildableIdentifier = "primary"
73
+            BlueprintIdentifier = "2D02E47A1E0B4A5D006451C7"
74
+            BuildableName = "Example-tvOS.app"
75
+            BlueprintName = "Example-tvOS"
76
+            ReferencedContainer = "container:Example.xcodeproj">
77
+         </BuildableReference>
78
+      </MacroExpansion>
79
+      <AdditionalOptions>
80
+      </AdditionalOptions>
81
+   </TestAction>
82
+   <LaunchAction
83
+      buildConfiguration = "Debug"
84
+      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
85
+      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
86
+      launchStyle = "0"
87
+      useCustomWorkingDirectory = "NO"
88
+      ignoresPersistentStateOnLaunch = "NO"
89
+      debugDocumentVersioning = "YES"
90
+      debugServiceExtension = "internal"
91
+      allowLocationSimulation = "YES">
92
+      <BuildableProductRunnable
93
+         runnableDebuggingMode = "0">
94
+         <BuildableReference
95
+            BuildableIdentifier = "primary"
96
+            BlueprintIdentifier = "2D02E47A1E0B4A5D006451C7"
97
+            BuildableName = "Example-tvOS.app"
98
+            BlueprintName = "Example-tvOS"
99
+            ReferencedContainer = "container:Example.xcodeproj">
100
+         </BuildableReference>
101
+      </BuildableProductRunnable>
102
+      <AdditionalOptions>
103
+      </AdditionalOptions>
104
+   </LaunchAction>
105
+   <ProfileAction
106
+      buildConfiguration = "Release"
107
+      shouldUseLaunchSchemeArgsEnv = "YES"
108
+      savedToolIdentifier = ""
109
+      useCustomWorkingDirectory = "NO"
110
+      debugDocumentVersioning = "YES">
111
+      <BuildableProductRunnable
112
+         runnableDebuggingMode = "0">
113
+         <BuildableReference
114
+            BuildableIdentifier = "primary"
115
+            BlueprintIdentifier = "2D02E47A1E0B4A5D006451C7"
116
+            BuildableName = "Example-tvOS.app"
117
+            BlueprintName = "Example-tvOS"
118
+            ReferencedContainer = "container:Example.xcodeproj">
119
+         </BuildableReference>
120
+      </BuildableProductRunnable>
121
+   </ProfileAction>
122
+   <AnalyzeAction
123
+      buildConfiguration = "Debug">
124
+   </AnalyzeAction>
125
+   <ArchiveAction
126
+      buildConfiguration = "Release"
127
+      revealArchiveInOrganizer = "YES">
128
+   </ArchiveAction>
129
+</Scheme>

+ 129
- 0
Example/ios/Example.xcodeproj/xcshareddata/xcschemes/Example.xcscheme View File

@@ -0,0 +1,129 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<Scheme
3
+   LastUpgradeVersion = "0620"
4
+   version = "1.3">
5
+   <BuildAction
6
+      parallelizeBuildables = "NO"
7
+      buildImplicitDependencies = "YES">
8
+      <BuildActionEntries>
9
+         <BuildActionEntry
10
+            buildForTesting = "YES"
11
+            buildForRunning = "YES"
12
+            buildForProfiling = "YES"
13
+            buildForArchiving = "YES"
14
+            buildForAnalyzing = "YES">
15
+            <BuildableReference
16
+               BuildableIdentifier = "primary"
17
+               BlueprintIdentifier = "83CBBA2D1A601D0E00E9B192"
18
+               BuildableName = "libReact.a"
19
+               BlueprintName = "React"
20
+               ReferencedContainer = "container:../node_modules/react-native/React/React.xcodeproj">
21
+            </BuildableReference>
22
+         </BuildActionEntry>
23
+         <BuildActionEntry
24
+            buildForTesting = "YES"
25
+            buildForRunning = "YES"
26
+            buildForProfiling = "YES"
27
+            buildForArchiving = "YES"
28
+            buildForAnalyzing = "YES">
29
+            <BuildableReference
30
+               BuildableIdentifier = "primary"
31
+               BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
32
+               BuildableName = "Example.app"
33
+               BlueprintName = "Example"
34
+               ReferencedContainer = "container:Example.xcodeproj">
35
+            </BuildableReference>
36
+         </BuildActionEntry>
37
+         <BuildActionEntry
38
+            buildForTesting = "YES"
39
+            buildForRunning = "YES"
40
+            buildForProfiling = "NO"
41
+            buildForArchiving = "NO"
42
+            buildForAnalyzing = "YES">
43
+            <BuildableReference
44
+               BuildableIdentifier = "primary"
45
+               BlueprintIdentifier = "00E356ED1AD99517003FC87E"
46
+               BuildableName = "ExampleTests.xctest"
47
+               BlueprintName = "ExampleTests"
48
+               ReferencedContainer = "container:Example.xcodeproj">
49
+            </BuildableReference>
50
+         </BuildActionEntry>
51
+      </BuildActionEntries>
52
+   </BuildAction>
53
+   <TestAction
54
+      buildConfiguration = "Debug"
55
+      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
56
+      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
57
+      shouldUseLaunchSchemeArgsEnv = "YES">
58
+      <Testables>
59
+         <TestableReference
60
+            skipped = "NO">
61
+            <BuildableReference
62
+               BuildableIdentifier = "primary"
63
+               BlueprintIdentifier = "00E356ED1AD99517003FC87E"
64
+               BuildableName = "ExampleTests.xctest"
65
+               BlueprintName = "ExampleTests"
66
+               ReferencedContainer = "container:Example.xcodeproj">
67
+            </BuildableReference>
68
+         </TestableReference>
69
+      </Testables>
70
+      <MacroExpansion>
71
+         <BuildableReference
72
+            BuildableIdentifier = "primary"
73
+            BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
74
+            BuildableName = "Example.app"
75
+            BlueprintName = "Example"
76
+            ReferencedContainer = "container:Example.xcodeproj">
77
+         </BuildableReference>
78
+      </MacroExpansion>
79
+      <AdditionalOptions>
80
+      </AdditionalOptions>
81
+   </TestAction>
82
+   <LaunchAction
83
+      buildConfiguration = "Debug"
84
+      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
85
+      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
86
+      launchStyle = "0"
87
+      useCustomWorkingDirectory = "NO"
88
+      ignoresPersistentStateOnLaunch = "NO"
89
+      debugDocumentVersioning = "YES"
90
+      debugServiceExtension = "internal"
91
+      allowLocationSimulation = "YES">
92
+      <BuildableProductRunnable
93
+         runnableDebuggingMode = "0">
94
+         <BuildableReference
95
+            BuildableIdentifier = "primary"
96
+            BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
97
+            BuildableName = "Example.app"
98
+            BlueprintName = "Example"
99
+            ReferencedContainer = "container:Example.xcodeproj">
100
+         </BuildableReference>
101
+      </BuildableProductRunnable>
102
+      <AdditionalOptions>
103
+      </AdditionalOptions>
104
+   </LaunchAction>
105
+   <ProfileAction
106
+      buildConfiguration = "Release"
107
+      shouldUseLaunchSchemeArgsEnv = "YES"
108
+      savedToolIdentifier = ""
109
+      useCustomWorkingDirectory = "NO"
110
+      debugDocumentVersioning = "YES">
111
+      <BuildableProductRunnable
112
+         runnableDebuggingMode = "0">
113
+         <BuildableReference
114
+            BuildableIdentifier = "primary"
115
+            BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
116
+            BuildableName = "Example.app"
117
+            BlueprintName = "Example"
118
+            ReferencedContainer = "container:Example.xcodeproj">
119
+         </BuildableReference>
120
+      </BuildableProductRunnable>
121
+   </ProfileAction>
122
+   <AnalyzeAction
123
+      buildConfiguration = "Debug">
124
+   </AnalyzeAction>
125
+   <ArchiveAction
126
+      buildConfiguration = "Release"
127
+      revealArchiveInOrganizer = "YES">
128
+   </ArchiveAction>
129
+</Scheme>

+ 14
- 0
Example/ios/Example/AppDelegate.h View File

@@ -0,0 +1,14 @@
1
+/**
2
+ * Copyright (c) 2015-present, Facebook, Inc.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+#import <UIKit/UIKit.h>
9
+
10
+@interface AppDelegate : UIResponder <UIApplicationDelegate>
11
+
12
+@property (nonatomic, strong) UIWindow *window;
13
+
14
+@end

+ 35
- 0
Example/ios/Example/AppDelegate.m View File

@@ -0,0 +1,35 @@
1
+/**
2
+ * Copyright (c) 2015-present, Facebook, Inc.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+#import "AppDelegate.h"
9
+
10
+#import <React/RCTBundleURLProvider.h>
11
+#import <React/RCTRootView.h>
12
+
13
+@implementation AppDelegate
14
+
15
+- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
16
+{
17
+  NSURL *jsCodeLocation;
18
+
19
+  jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
20
+
21
+  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
22
+                                                      moduleName:@"Example"
23
+                                               initialProperties:nil
24
+                                                   launchOptions:launchOptions];
25
+  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
26
+
27
+  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
28
+  UIViewController *rootViewController = [UIViewController new];
29
+  rootViewController.view = rootView;
30
+  self.window.rootViewController = rootViewController;
31
+  [self.window makeKeyAndVisible];
32
+  return YES;
33
+}
34
+
35
+@end

+ 42
- 0
Example/ios/Example/Base.lproj/LaunchScreen.xib View File

@@ -0,0 +1,42 @@
1
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
2
+<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="7702" systemVersion="14D136" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES">
3
+    <dependencies>
4
+        <deployment identifier="iOS"/>
5
+        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="7701"/>
6
+        <capability name="Constraints with non-1.0 multipliers" minToolsVersion="5.1"/>
7
+    </dependencies>
8
+    <objects>
9
+        <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
10
+        <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
11
+        <view contentMode="scaleToFill" id="iN0-l3-epB">
12
+            <rect key="frame" x="0.0" y="0.0" width="480" height="480"/>
13
+            <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
14
+            <subviews>
15
+                <label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Powered by React Native" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" minimumFontSize="9" translatesAutoresizingMaskIntoConstraints="NO" id="8ie-xW-0ye">
16
+                    <rect key="frame" x="20" y="439" width="441" height="21"/>
17
+                    <fontDescription key="fontDescription" type="system" pointSize="17"/>
18
+                    <color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
19
+                    <nil key="highlightedColor"/>
20
+                </label>
21
+                <label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Example" textAlignment="center" lineBreakMode="middleTruncation" baselineAdjustment="alignBaselines" minimumFontSize="18" translatesAutoresizingMaskIntoConstraints="NO" id="kId-c2-rCX">
22
+                    <rect key="frame" x="20" y="140" width="441" height="43"/>
23
+                    <fontDescription key="fontDescription" type="boldSystem" pointSize="36"/>
24
+                    <color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
25
+                    <nil key="highlightedColor"/>
26
+                </label>
27
+            </subviews>
28
+            <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
29
+            <constraints>
30
+                <constraint firstItem="kId-c2-rCX" firstAttribute="centerY" secondItem="iN0-l3-epB" secondAttribute="bottom" multiplier="1/3" constant="1" id="5cJ-9S-tgC"/>
31
+                <constraint firstAttribute="centerX" secondItem="kId-c2-rCX" secondAttribute="centerX" id="Koa-jz-hwk"/>
32
+                <constraint firstAttribute="bottom" secondItem="8ie-xW-0ye" secondAttribute="bottom" constant="20" id="Kzo-t9-V3l"/>
33
+                <constraint firstItem="8ie-xW-0ye" firstAttribute="leading" secondItem="iN0-l3-epB" secondAttribute="leading" constant="20" symbolic="YES" id="MfP-vx-nX0"/>
34
+                <constraint firstAttribute="centerX" secondItem="8ie-xW-0ye" secondAttribute="centerX" id="ZEH-qu-HZ9"/>
35
+                <constraint firstItem="kId-c2-rCX" firstAttribute="leading" secondItem="iN0-l3-epB" secondAttribute="leading" constant="20" symbolic="YES" id="fvb-Df-36g"/>
36
+            </constraints>
37
+            <nil key="simulatedStatusBarMetrics"/>
38
+            <freeformSimulatedSizeMetrics key="simulatedDestinationMetrics"/>
39
+            <point key="canvasLocation" x="548" y="455"/>
40
+        </view>
41
+    </objects>
42
+</document>

+ 38
- 0
Example/ios/Example/Images.xcassets/AppIcon.appiconset/Contents.json View File

@@ -0,0 +1,38 @@
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
+}

+ 6
- 0
Example/ios/Example/Images.xcassets/Contents.json View File

@@ -0,0 +1,6 @@
1
+{
2
+  "info" : {
3
+    "version" : 1,
4
+    "author" : "xcode"
5
+  }
6
+}

+ 56
- 0
Example/ios/Example/Info.plist View File

@@ -0,0 +1,56 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+<plist version="1.0">
4
+<dict>
5
+	<key>CFBundleDevelopmentRegion</key>
6
+	<string>en</string>
7
+	<key>CFBundleDisplayName</key>
8
+	<string>Example</string>
9
+	<key>CFBundleExecutable</key>
10
+	<string>$(EXECUTABLE_NAME)</string>
11
+	<key>CFBundleIdentifier</key>
12
+	<string>org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)</string>
13
+	<key>CFBundleInfoDictionaryVersion</key>
14
+	<string>6.0</string>
15
+	<key>CFBundleName</key>
16
+	<string>$(PRODUCT_NAME)</string>
17
+	<key>CFBundlePackageType</key>
18
+	<string>APPL</string>
19
+	<key>CFBundleShortVersionString</key>
20
+	<string>1.0</string>
21
+	<key>CFBundleSignature</key>
22
+	<string>????</string>
23
+	<key>CFBundleVersion</key>
24
+	<string>1</string>
25
+	<key>LSRequiresIPhoneOS</key>
26
+	<true/>
27
+	<key>UILaunchStoryboardName</key>
28
+	<string>LaunchScreen</string>
29
+	<key>UIRequiredDeviceCapabilities</key>
30
+	<array>
31
+		<string>armv7</string>
32
+	</array>
33
+	<key>UISupportedInterfaceOrientations</key>
34
+	<array>
35
+		<string>UIInterfaceOrientationPortrait</string>
36
+		<string>UIInterfaceOrientationLandscapeLeft</string>
37
+		<string>UIInterfaceOrientationLandscapeRight</string>
38
+	</array>
39
+	<key>UIViewControllerBasedStatusBarAppearance</key>
40
+	<false/>
41
+	<key>NSLocationWhenInUseUsageDescription</key>
42
+	<string></string>
43
+	<key>NSAppTransportSecurity</key>
44
+	<!--See http://ste.vn/2015/06/10/configuring-app-transport-security-ios-9-osx-10-11/ -->
45
+	<dict>
46
+		<key>NSExceptionDomains</key>
47
+		<dict>
48
+			<key>localhost</key>
49
+			<dict>
50
+				<key>NSExceptionAllowsInsecureHTTPLoads</key>
51
+				<true/>
52
+			</dict>
53
+		</dict>
54
+	</dict>
55
+</dict>
56
+</plist>

+ 16
- 0
Example/ios/Example/main.m View File

@@ -0,0 +1,16 @@
1
+/**
2
+ * Copyright (c) 2015-present, Facebook, Inc.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+#import <UIKit/UIKit.h>
9
+
10
+#import "AppDelegate.h"
11
+
12
+int main(int argc, char * argv[]) {
13
+  @autoreleasepool {
14
+    return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
15
+  }
16
+}

+ 68
- 0
Example/ios/ExampleTests/ExampleTests.m View File

@@ -0,0 +1,68 @@
1
+/**
2
+ * Copyright (c) 2015-present, Facebook, Inc.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+#import <UIKit/UIKit.h>
9
+#import <XCTest/XCTest.h>
10
+
11
+#import <React/RCTLog.h>
12
+#import <React/RCTRootView.h>
13
+
14
+#define TIMEOUT_SECONDS 600
15
+#define TEXT_TO_LOOK_FOR @"Welcome to React Native!"
16
+
17
+@interface ExampleTests : XCTestCase
18
+
19
+@end
20
+
21
+@implementation ExampleTests
22
+
23
+- (BOOL)findSubviewInView:(UIView *)view matching:(BOOL(^)(UIView *view))test
24
+{
25
+  if (test(view)) {
26
+    return YES;
27
+  }
28
+  for (UIView *subview in [view subviews]) {
29
+    if ([self findSubviewInView:subview matching:test]) {
30
+      return YES;
31
+    }
32
+  }
33
+  return NO;
34
+}
35
+
36
+- (void)testRendersWelcomeScreen
37
+{
38
+  UIViewController *vc = [[[RCTSharedApplication() delegate] window] rootViewController];
39
+  NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS];
40
+  BOOL foundElement = NO;
41
+
42
+  __block NSString *redboxError = nil;
43
+  RCTSetLogFunction(^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) {
44
+    if (level >= RCTLogLevelError) {
45
+      redboxError = message;
46
+    }
47
+  });
48
+
49
+  while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) {
50
+    [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
51
+    [[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
52
+
53
+    foundElement = [self findSubviewInView:vc.view matching:^BOOL(UIView *view) {
54
+      if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) {
55
+        return YES;
56
+      }
57
+      return NO;
58
+    }];
59
+  }
60
+
61
+  RCTSetLogFunction(RCTDefaultLogFunction);
62
+
63
+  XCTAssertNil(redboxError, @"RedBox error: %@", redboxError);
64
+  XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS);
65
+}
66
+
67
+
68
+@end

+ 24
- 0
Example/ios/ExampleTests/Info.plist View File

@@ -0,0 +1,24 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+<plist version="1.0">
4
+<dict>
5
+	<key>CFBundleDevelopmentRegion</key>
6
+	<string>en</string>
7
+	<key>CFBundleExecutable</key>
8
+	<string>$(EXECUTABLE_NAME)</string>
9
+	<key>CFBundleIdentifier</key>
10
+	<string>org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)</string>
11
+	<key>CFBundleInfoDictionaryVersion</key>
12
+	<string>6.0</string>
13
+	<key>CFBundleName</key>
14
+	<string>$(PRODUCT_NAME)</string>
15
+	<key>CFBundlePackageType</key>
16
+	<string>BNDL</string>
17
+	<key>CFBundleShortVersionString</key>
18
+	<string>1.0</string>
19
+	<key>CFBundleSignature</key>
20
+	<string>????</string>
21
+	<key>CFBundleVersion</key>
22
+	<string>1</string>
23
+</dict>
24
+</plist>

+ 24
- 0
Example/package.json View File

@@ -0,0 +1,24 @@
1
+{
2
+  "name": "Example",
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
+  },
9
+  "dependencies": {
10
+    "aliyun-oss-react-native": "^1.0.0-alpha.1",
11
+    "react": "16.0.0-alpha.6",
12
+    "react-native": "0.44.3",
13
+    "react-native-image-picker": "^0.26.10"
14
+  },
15
+  "devDependencies": {
16
+    "babel-jest": "23.0.1",
17
+    "babel-preset-react-native": "4.0.0",
18
+    "jest": "23.1.0",
19
+    "react-test-renderer": "16.3.1"
20
+  },
21
+  "jest": {
22
+    "preset": "react-native"
23
+  }
24
+}

BIN
Example/resource/putao.jpeg View File


+ 21
- 0
LICENSE View File

@@ -0,0 +1,21 @@
1
+The MIT License (MIT)
2
+
3
+Copyright (c) ali-sdk and other contributors.
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.

+ 441
- 0
README-CN.md View File

@@ -0,0 +1,441 @@
1
+# Aliyun OSS SDK for React Native
2
+
3
+## [README of English](#https://github.com/aliyun/aliyun-oss-react-native/blob/develop/README.md)
4
+
5
+## 简介
6
+
7
+本文档主要介绍OSS React Native SDK的安装和使用。本文档假设您已经开通了阿里云OSS 服务,并创建了Access Key ID 和Access Key Secret。文中的ID 指的是Access Key ID,KEY 指的是Access Key Secret。如果您还没有开通或者还不了解OSS,请登录[OSS产品主页](http://www.aliyun.com/product/oss)获取更多的帮助。
8
+
9
+## 开发语言
10
+
11
+* JavaScript 、JAVA、Objective-C
12
+
13
+## 环境要求
14
+
15
+- Android系统版本: 2.3及以上
16
+- IOS系统版本: 8.0及以上
17
+- 必须注册有Aliyun.com用户账户,并开通OSS服务。
18
+- Node版本: 8.0及以上
19
+- React Native版本:0.44.0及以上
20
+
21
+## 内容
22
+
23
+- [安装](#安装)
24
+- [使用](#使用)
25
+- [接口](#接口)
26
+- [示例](#示例)
27
+- [常见问题](#常见问题)
28
+- [参与开源](#参与开源)
29
+- [证书](#证书)
30
+- [联系我们](#联系我们)
31
+- [未来](#未来)
32
+- [文档](#文档)
33
+
34
+## 安装
35
+
36
+注意: react-native版本建议0.44.0及以上,建议使用fackebook官方[react-native-cli](https://www.npmjs.com/package/react-native-cli)或者[create-react-native-app](https://www.npmjs.com/package/create-react-native-app)脚手架进行react native项目构建。aliyun-oss-react-native可通过npm或者yarn安装
37
+
38
+* npm
39
+
40
+```script
41
+npm install aliyun-oss-react-native  --save
42
+```
43
+
44
+* yarn
45
+
46
+```script
47
+yarn install aliyun-oss-react-native --save
48
+```
49
+### 自动安装
50
+
51
+react native项目下运行`react-native link`命令
52
+
53
+```script
54
+react-native link
55
+```
56
+
57
+注意:由于react native脚手架不同版本的问题,有时候自动安装可能会失败,可手动添加android和iOS的的依赖库。同样为了兼容IPv6-Only网络,iOS工程中需参考aliyun-oss-ios-sdk说明中引入以下包。
58
+```html
59
+1. libresolv.tbd
60
+2. CoreTelephony.framework
61
+3. SystemConfiguration.framework
62
+```
63
+
64
+### 手动安装
65
+
66
+#### iOS
67
+
68
+- **CocoaPods**
69
+```
70
+pod 'aliyun-oss-react-native', :path => '../node_modules/aliyun-oss-react-native'
71
+````
72
+
73
+- **非CocoaPods**
74
+
75
+1. 在XCode  Project navigator面板中, 右键单击工程Libraries文件 ➜ 选择`Add Files to <...>` 进入 `node_modules` ➜ `aliyun-oss-react-native` ➜ `ios` ➜ select `RNAliyunOSS.xcodeproj`
76
+2. 在XCode  Project navigator面板中, 添加`RNAliyunOSS.a` to `Build Phases -> Link Binary With Libraries`
77
+3. 在XCode  Project navigator面板中,右键单击[framework] ➜ Add Files to [your project's name]. 进入node_modules ➜ aliyun-oss-rn-sdk ➜ AliyunSDK. Add AliyunOSSiOS.framework
78
+
79
+#### Android
80
+1. `settings.gradle`
81
+    ```gradle
82
+    include ':aliyun-oss-react-native'
83
+    project(':aliyun-oss-react-native').projectDir = new File(rootProject.projectDir, '../node_modules/aliyun-oss-react-native/android')
84
+    ```
85
+2. `build.gradle`
86
+    ```gradle
87
+    dependencies {
88
+        compile project(':aliyun-oss-react-native')
89
+    }
90
+    ```
91
+
92
+3. `MainApplication.java`
93
+    ```java
94
+   import com.reactlibrary.RNAliyunOssPackage;
95
+
96
+    public class MainApplication extends Application implements ReactApplication {
97
+     @Override
98
+       protected List<ReactPackage> getPackages() {
99
+         return Arrays.<ReactPackage>asList(
100
+             new MainReactPackage(),
101
+               new ImagePickerPackage(),
102
+               new RNAliyunOssPackage()
103
+         );
104
+       }
105
+    }
106
+    ```
107
+## 使用
108
+
109
+目前接口除了初始化客户端和开启日志功能接口外,其他的接口都返回Promise对象,开发者可以使用async await的语法,也可使用原生的
110
+`promise().then(/**/).catch(/**/)`,接口的使用基本一样,以上传接口为例进行说明
111
+
112
+* step-1:导入AliyunOSS
113
+```
114
+import AliyunOSS from 'aliyun-oss-react-native'
115
+```
116
+* step-2:开启调试模式 (可选)
117
+
118
+```
119
+AliyunOSS.enableDevMode();
120
+```
121
+
122
+* step-3:初始化配置选项(可选)
123
+```javascript
124
+const configuration = {
125
+   maxRetryCount: 3,
126
+   timeoutIntervalForRequest: 30,
127
+   timeoutIntervalForResource: 24 * 60 * 60
128
+};
129
+```
130
+
131
+* step-4:初始化OSS Client,目前提供了4中初始化OSS Client方式,这里调用initWithServerSTS,其他的几个接口可参考该文档中的API
132
+
133
+```javascript
134
+const endpoint = "xxxx.aliyuncs.com"
135
+
136
+AliyunOSS.initWithServerSTS("/***http://ip:端口/****/",endPoint, configuration)
137
+```
138
+备注:仓库文件中提供Node脚步启用本地鉴权服务,打开script文件夹运行,运行以下命令:
139
+
140
+1. `npm istall`
141
+2. 修改config中accessKeyId 和 accessKeySecret
142
+3. node index.js,端口默认9000,鉴权服务地址为:(http|https)://ip.com:9000/
143
+
144
+*  step-5:
145
+
146
+```javascript
147
+    <!-- 备注:目前接口仅暴漏filePath,上传路径为file:/// -->
148
+    AliyunOSS.asyncUpload(bucketname, objectkey, filePath).then( (res) => {
149
+        <!-- log的查看可以通过React Native自带的调试工具也可通过XCode Log控制台进行查看 -->
150
+        console.log(res)
151
+    }).catch((error)=>{
152
+        console.log(error)
153
+    })
154
+    <!-- 监听上传事件和上传进度-->
155
+   const downloadProgress = p => console.log(p.currentSize / p.totalSize);
156
+   AliyunOSS.addEventListener('uploadProgress', downloadProgress);
157
+```
158
+
159
+## 接口
160
+
161
+主要介绍目前React Native SDK已经实现并部分支持的API,主要涉及到日志管理、Bucket管理、Object管理、授权、文件上传和下载等。后续持续完善相关API和BUG修复。API列表如下
162
+
163
+API | Android | iOS
164
+-------------- | ---- |---- |
165
+enableDevMode |支持| 支持
166
+initWithPlainTextAccessKey | 支持| 支持
167
+initWithSigner | 支持| 支持
168
+initWithSecurityToken | 支持| 支持
169
+initWithServerSTS  | 支持| 支持
170
+asyncUpload  | 支持| 支持
171
+asyncAppendObject  ||
172
+asyncResumableUpload  ||
173
+initMultipartUpload  | 支持| 支持
174
+multipartUpload   | 支持| 支持
175
+listParts   | 支持| 支持
176
+abortMultipartUpload | 支持| 支持
177
+asyncDownload  | 支持| 支持
178
+asyncCreateBucket   | 支持| 支持
179
+asyncGetBucketACL   | 支持| 支持
180
+asyncListBuckets  | 支持 | 支持
181
+asyncDeleteBucket  | 支持| 支持
182
+asyncHeadObject  | 支持| 支持
183
+asyncListObjects  | 支持| 支持
184
+doesObjectExist  | 支持| 支持
185
+asyncCopyObject |支持|支持
186
+asyncDeleteObject | 支持| 支持
187
+
188
+### enableDevMode
189
+
190
+该接口主要是开启日志记录功能,具体使用参考:
191
+
192
+```
193
+AliyunOSS.enableDevMode()
194
+```
195
+
196
+### initWithPlainTextAccessKey
197
+
198
+该接口需要通过明文授权acckeyId和accekeySecret,使用可查看
199
+
200
+```javascript
201
+const endPoint = "XXX"
202
+const configuration = {
203
+    maxRetryCount: 3,
204
+    timeoutIntervalForRequest: 30,
205
+    timeoutIntervalForResource: 24 * 60 * 60
206
+ };
207
+AliyunOSS.initWithPlainTextAccessKey(accessKey, secretKey, endPoint, configuration);
208
+```
209
+
210
+### initWithSigner
211
+
212
+该接口通过自签方式授权,请参考[自签名模式](https://help.aliyun.com/document_detail/32046.html?spm=a2c4g.11186623.2.12.W3Zm1U),使用可查看
213
+
214
+```javascript
215
+AliyunOSS.initWithSigner(signature, accessKey, endPoint, configuration);
216
+```
217
+
218
+### initWithSecurityToken
219
+
220
+该接口通过SecurityToken授权,参考[STS访问控制](https://help.aliyun.com/document_detail/32046.html?spm=a2c4g.11186623.2.8.dfV9i0),使用可查看
221
+
222
+```
223
+AliyunOSS.initWithSecurityToken(signature, accessKey, endPoint, configuration);
224
+```
225
+
226
+### initWithServerSTS
227
+
228
+该接口通过本地鉴权服务器授权,使用可查看
229
+
230
+```javascript
231
+AliyunOSS.initWithSecurityToken(signature, accessKey, endPoint, configuration);
232
+```
233
+
234
+### asyncUpload
235
+
236
+```
237
+AliyunOSS.asyncUpload(bucketname, objectKey, filepath).then().catch()
238
+
239
+```
240
+### asyncAppendObject
241
+### asyncResumableUpload
242
+### initMultipartUpload
243
+
244
+```javascript
245
+ AliyunOSS.initMultipartUpload(bucketname,objectkey).then((e)=>{
246
+         console.log(e)
247
+         //e 为uploadId
248
+    }).catch((error) => {
249
+        console.log(error)
250
+ })
251
+```
252
+### multipartUpload
253
+
254
+```
255
+//uploadId为initMultipartUpload成功回调后的返回值
256
+AliyunOSS.multipartUpload(multipartBucket,mulitipartObjectKey,uploadId,filepath).then((res)=>{
257
+    Alert.alert("分片上传成功");
258
+  }).catch((e) => {
259
+    Alert.alert("分片上传失败");
260
+  })
261
+```
262
+### listParts
263
+
264
+```
265
+AliyunOSS.listParts(multipartBucket,multipartObjectKey,upoadId).then((e)=>{
266
+    Alert.alert("onListParts"+e)
267
+  }).catch((e)=>{
268
+    Alert.alert("onListPartsError")
269
+ })
270
+```
271
+### abortMultipartUpload
272
+
273
+```
274
+ AliyunOSS.abortMultipartUpload(multipartBucket,multipartBucket,uploadId).then((e)=>{
275
+    Alert.alert("分片终止成功");
276
+  }).catch((e)=>{
277
+    Alert.alert("分片终止失败");
278
+  })
279
+```
280
+
281
+### asyncDownload
282
+
283
+```
284
+ // xxx为图片处理选项,具体可查看官网
285
+ AliyunOSS.asyncDownload(bucketname,objectkey,{"x-oss-process":'xxxx'}).then((e) => {
286
+    console.log(e)
287
+  }).catch((e)=>{
288
+    console.log(e)
289
+  })
290
+```
291
+### asyncCreateBucket
292
+
293
+```
294
+ AliyunOSS.asyncCreateBucket('tyluoluo','private','oss-cn-zhangjiakou').then((e) => {
295
+    console.log(e)
296
+  }).catch((e)=>{
297
+     console.log(e)
298
+  })
299
+```
300
+
301
+### asyncGetBucketACL
302
+
303
+```javascript
304
+ AliyunOSS.asyncGetBucketACL('luozhang002').then((e) => {
305
+    console.log(e)
306
+  }).catch((e)=>{
307
+    console.log(e)
308
+  })
309
+```
310
+### asyncListBuckets
311
+
312
+```
313
+AliyunOSS.asyncListBuckets().then((e) => {
314
+    console.log(e)
315
+  }).catch((e) => {
316
+    console.log(e)
317
+  })
318
+```
319
+### asyncDeleteBucket
320
+
321
+```
322
+ AliyunOSS.asyncDeleteBucket("tyluoluo").then((e) => {
323
+    console.log(e)
324
+  }).catch((e) => {
325
+    console.log(e)
326
+  })
327
+```
328
+### asyncHeadObject
329
+
330
+```
331
+ AliyunOSS.asyncHeadObject('luozhang002','yanxing').then((e)=>{
332
+    console.log(e)
333
+  }).catch((e)=> {
334
+     console.log(e)
335
+ })
336
+```
337
+### asyncListObjects
338
+
339
+```
340
+ AliyunOSS.asyncListObjects('luozhang002').then((e)=>{
341
+    console.log(e)
342
+  }).catch((e)=>{
343
+     console.log(e)
344
+  })
345
+```
346
+### doesObjectExist
347
+
348
+```
349
+ AliyunOSS.doesObjectExist('luozhang001','xx.png').then((e)=>{
350
+    console.log(e)
351
+  }).catch((e)=>{
352
+     console.log(e)
353
+  })
354
+```
355
+
356
+### asyncCopyObject
357
+
358
+```
359
+ AliyunOSS.asyncCopyObject('luozhang001',"2.png","luozhang002","sbsbsb").then((e)=>{
360
+      console.log(e)
361
+    }).catch((e)=>{
362
+      console.log("xxxx")
363
+      console.log(e)
364
+    })
365
+```
366
+### asyncDeleteObject
367
+
368
+```
369
+ AliyunOSS.asyncDeleteObject('luozhang001','2.png').then((e)=>{
370
+     Alert.alert(e)
371
+  }).catch((e)=>{
372
+    console.log(e)
373
+  })
374
+```
375
+
376
+
377
+## 示例
378
+
379
+仓库Example中提供了React Native android和iOS端运行demo,Android为Example下的android工程,iOS为Example下的NativeAddRN工程,目前Example提供了所有已开发的API DEMO,还在完善中,欢迎参与共建。如何运行Example呢?
380
+
381
+* step-1:克隆项目并安装依赖包
382
+
383
+```
384
+1. git clone https://github.com/aliyun/aliyun-oss-react-native.git
385
+2. cd Example
386
+3. npm install
387
+```
388
+
389
+* step-2:启动本地鉴权服务器并修改Example/App.js中initWithServerSTS服务地址,注意服务地址要以IP开口
390
+
391
+```
392
+1. cd script/sts-app-server-node
393
+2. node index.js
394
+```
395
+
396
+* step-3:运行项目
397
+
398
+1. npm run start
399
+2. 安卓使用Android Studio打开工程Example/android编译并运行,效果如图
400
+
401
+<image  text-align="center" width="200" height="400" src="https://img.alicdn.com/tfs/TB1nQ2pqSBYBeNjy0FeXXbnmFXa-658-1230.png"/>
402
+
403
+3. ios使用XCode打开工程Example/NativeAddRN编译并运行,效果如图
404
+
405
+<image width="200" height="400" src="https://img.alicdn.com/tfs/TB1ejWwqH9YBuNjy0FgXXcxcXXa-778-1488.png"/>
406
+
407
+## 常见问题
408
+
409
+* iOS端由于React Native自身环境的复杂性,会莫名奇妙的报各种编译错,请移步[stackoverflow](https://stackoverflow.com/questions/tagged/react-native),或者直接可运行项目Example目录下IOS工程NativeAddRN进行对比,如何运行Example请参考[示例](#示例)
410
+* 关闭代理
411
+* 针对Android Studio调试环境下看不到界面,请删除工程文件下的Build/文件夹重新编译
412
+
413
+## 参与开源
414
+
415
+目前React Native SDK处于起步阶段,开发者使用React Native API的过程中,遇到任何问题都可以向官方仓库提Issue或者PR,我们会第一时间进行处理。欢迎广大开发者参与共建,修复和完善更多的API
416
+来更好的服务使用阿里云存储服务的客户和开发者。具体开发可参考如下文档
417
+
418
+* React Native Android Native Modules:http://facebook.github.io/react-native/docs/native-modules-android.html
419
+* React Native IOS Native Modules:http://facebook.github.io/react-native/docs/native-modules-ios.html
420
+* React Native Debugging: http://facebook.github.io/react-native/docs/debugging.html
421
+* 阿里云OSS安卓SDK:https://github.com/aliyun/aliyun-oss-android-sdk
422
+* 阿里云OSS IOS SDK https://github.com/aliyun/aliyun-oss-ios-sdk
423
+
424
+## License
425
+
426
+* MIT
427
+
428
+## 联系我们
429
+
430
+* 阿里云OSS官方网站:http://oss.aliyun.com
431
+* 阿里云OSS官方论坛:http://bbs.aliyun.com
432
+* 阿里云OSS官方文档中心:http://www.aliyun.com/product/oss#Docs
433
+* 阿里云官方技术支持 登录OSS控制台 https://home.console.aliyun.com -> 点击"工单系统"
434
+
435
+## 未来
436
+
437
+* 未来持续改进、优化代码文档、新增接口、修复Bug等
438
+
439
+## 文档
440
+
441
+* 后续完善

+ 442
- 1
README.md View File

@@ -1 +1,442 @@
1
-## Alibaba Cloud OSS SDK for React Native
1
+# Alibaba Cloud OSS SDK for React Native
2
+
3
+## [README of Chinese](#https://github.com/aliyun/aliyun-oss-react-native/blob/develop/README-CN.md)
4
+
5
+## Introduction
6
+
7
+This document mainly describes how to install and use the OSS React Native SDK. This document assumes that you have already activated the Alibaba Cloud OSS service and created an *AccessKeyID* and an *AccessKeySecret*. In the document, *ID* refers to the *AccessKeyID* and *KEY* indicates the *AccessKeySecret*. If you have not yet activated or do not know about the OSS service, log on to the [OSS Product Homepage](http://www.aliyun.com/product/oss) for more help.
8
+
9
+## Lanaguage
10
+
11
+* JavaScript、JAVA、Objective-C
12
+
13
+## Environment requirements
14
+
15
+- Android ***2.3*** or above
16
+- IOS ***8.0*** or above
17
+- You must have registered an Alibaba Cloud account with the OSS activated.
18
+- Node ***8.0*** or above
19
+- React Native ***0.44.0*** or above
20
+
21
+## Table of Contents
22
+
23
+- [Installation](#installation)
24
+- [Usage](#usage)
25
+- [API](#api)
26
+- [DEMO](#DEMO)
27
+- [FAQ](#FAQ)
28
+- [JOIN](#join)
29
+- [License](#license)
30
+- [CONTACT](#contact)
31
+- [Future](#Future)
32
+- [Documentation](#Documentaion)
33
+
34
+## Installation
35
+
36
+NOTE: THIS PACKAGE IS NOW BUILT FOR REACT NATIVE 0.40 OR GREATER
37
+* npm
38
+
39
+```
40
+npm install aliyun-oss-react-native --save
41
+```
42
+* yarn
43
+
44
+```
45
+yarn install aliyun-oss-react-native --save
46
+```
47
+
48
+### Automatic Installation
49
+
50
+run `react-native link` in the react native project
51
+
52
+```
53
+react-native link
54
+```
55
+
56
+### Manual Installation
57
+
58
+#### iOS
59
+
60
+- **CocoaPods**
61
+
62
+```
63
+pod 'aliyun-oss-react-native', :path => '../node_modules/aliyun-oss-react-native'
64
+````
65
+
66
+- **no CocoaPods**
67
+
68
+1. In the XCode's "Project navigator", right click on your project's Libraries folder ➜ `Add Files to <...>` Go to `node_modules` ➜ `aliyun-oss-react-native` ➜ `ios` ➜ select `RNAliyunOSS.xcodeproj`
69
+2. Add `RNAliyun.a` to `Build Phases -> Link Binary With Libraries`
70
+3. In XCode, in the project navigator, right click `Frameworks` ➜ `Add Files to [your project's name]`. Go to `node_modules` ➜ `aliyun-oss-react-native` ➜ `AliyunSDK`. Add `AliyunOSSiOS.framework`, and select *Copy items if needed* in the pop-up box.
71
+
72
+#### Android
73
+1. Add the following lines to `android/settings.gradle`:
74
+    ```gradle
75
+    include ':react-native-rn-sdk'
76
+    project(':react-native-rn-sdk').projectDir = new File(rootProject.projectDir, '../node_modules/aliyun-oss-rn-sdk/android')
77
+    ```
78
+
79
+2. Add the compile line to the dependencies in `android/app/build.gradle`:
80
+    ```gradle
81
+    dependencies {
82
+        compile project(':aliyun-oss-react-native')
83
+    }
84
+    ```
85
+
86
+3. Add the required permissions in `AndroidManifest.xml`:
87
+    ```xml
88
+       <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
89
+       <uses-permission android:name="android.permission.CAMERA" />
90
+    ```
91
+4. Add the import and link the package in `MainApplication.java`:
92
+
93
+    ```java
94
+      import com.reactlibrary.RNAliyunOssPackage;
95
+
96
+       public class MainApplication extends Application implements ReactApplication {
97
+        @Override
98
+          protected List<ReactPackage> getPackages() {
99
+            return Arrays.<ReactPackage>asList(
100
+                new MainReactPackage(),
101
+                  new RNAliyunOssPackage()
102
+            );
103
+          }
104
+       }
105
+      ```
106
+
107
+## Usage
108
+
109
+Now ,all the API returns Promise Object exception init OSS Client API and enableDevMode API,so you can use  ES6 `async await ` or
110
+`promise().then(/**/).catch(/**/)`,we take asyncUpload interface as an example.
111
+
112
+* step-1:import AliyunOSS
113
+```
114
+import AliyunOSS from 'aliyun-oss-react-native'
115
+```
116
+* step-2:open debug mode  (optional)
117
+
118
+```
119
+AliyunOSS.enableDevMode();
120
+```
121
+
122
+* step-3:init configuration(optional)
123
+
124
+```javascript
125
+const configuration = {
126
+   maxRetryCount: 3,
127
+   timeoutIntervalForRequest: 30,
128
+   timeoutIntervalForResource: 24 * 60 * 60
129
+};
130
+```
131
+
132
+* step-4:init OSS Client,we provide 4 ways to init OSS Client. here we recommend initWithServerSTS
133
+
134
+```javascript
135
+const endpoint = "xxxx.aliyuncs.com"
136
+
137
+AliyunOSS.initWithServerSTS("/***http://ip:port/****/",endPoint, configuration)
138
+```
139
+Note:We provide auth server with node shell in Script folder,you can run command link this.
140
+
141
+1. `npm istall`
142
+2. modify accessKeyId and accessKeySecret in the config.js
143
+3. node index.js,port is defalut 9000,The  auth server is like (http|https)://ip.com:9000/
144
+
145
+*  step-5:
146
+
147
+```javascript
148
+    <!-- note:filepath must start with file:/// -->
149
+    AliyunOSS.asyncUpload(bucketname, objectkey, filePath).then( (res) => {
150
+        <!-- you can see the log with React Native debugg tools or XCode 、Android studio console -->
151
+        console.log(res)
152
+    }).catch((error)=>{
153
+        console.log(error)
154
+    })
155
+    <!-- addEventlistener uploadPross-->
156
+   const downloadProgress = p => console.log(p.currentSize / p.totalSize);
157
+   AliyuOSS.addEventListener('uploadProgress', downloadProgress);
158
+```
159
+
160
+## api
161
+
162
+This section describes the APIs that are currently implemented and partially supported by the React Native SDK. These APIs mainly cover log management, bucket management, object management, authorization, file upload, and download. Follow-up to improve the relevant API and BUG repair. API list is as follows
163
+
164
+
165
+API | Android | iOS
166
+----| ---- | ---- |
167
+enableDevMode|Y|Y|
168
+initWithPlainTextAccessKey  |Y|Y
169
+initWithSigner  |Y|Y
170
+initWithSecurityToken   |Y|Y
171
+initWithServerSTS   |Y|Y
172
+asyncUpload   |Y| Y
173
+asyncAppendObject  ||
174
+asyncResumableUpload  ||
175
+initMultipartUpload |Y|Y
176
+multipartUpload  | Y | Y
177
+listParts |Y|Y
178
+abortMultipartUpload |Y|Y
179
+asyncDownload  |Y|Y
180
+asyncCreateBucket  |Y|Y
181
+asyncGetBucketACL  |Y|Y
182
+asyncListBuckets  |Y|Y
183
+asyncDeleteBucket  |Y|Y
184
+asyncHeadObject  |Y|Y
185
+asyncListObjects |Y|Y
186
+doesObjectExist |Y|Y
187
+doesObjectExist |Y|Y
188
+asyncDeleteObject  |Y|Y
189
+
190
+
191
+### enableDevMode
192
+
193
+open dev log,please refer to the code
194
+
195
+```
196
+AliyunOSS.enableDevMode()
197
+```
198
+
199
+### initWithPlainTextAccessKey
200
+
201
+init auth client with accessKeyId and accessKeySecret,please refer to the code.
202
+
203
+```javascript
204
+const endPoint = "XXX"
205
+const configuration = {
206
+    maxRetryCount: 3,
207
+    timeoutIntervalForRequest: 30,
208
+    timeoutIntervalForResource: 24 * 60 * 60
209
+ };
210
+AliyunOSS.initWithPlainTextAccessKey(accessKey, secretKey, endPoint, configuration);
211
+```
212
+
213
+### initWithSigner
214
+
215
+init auth client the sign
216
+
217
+```javascript
218
+AliyunOSS.initWithSigner(signature, accessKey, endPoint, configuration);
219
+```
220
+
221
+### initWithSecurityToken
222
+
223
+init client with SecurityToken
224
+
225
+```
226
+AliyunOSS.initWithSecurityToken(signature, accessKey, endPoint, configuration);
227
+```
228
+
229
+### initWithServerSTS
230
+
231
+init auth client with loacl auth server
232
+
233
+```javascript
234
+AliyunOSS.initWithSecurityToken(signature, accessKey, endPoint, configuration);
235
+```
236
+
237
+### asyncUpload
238
+
239
+```
240
+AliyunOSS.asyncUpload(bucketname, objectKye, filepath).then().catch()
241
+```
242
+### asyncAppendObject
243
+### asyncResumableUpload
244
+### initMultipartUpload
245
+
246
+```javascript
247
+ AliyunOSS.initMultipartUpload(bucketname,objectkey).then((e)=>{
248
+         console.log(e)
249
+         //e is uploadId
250
+    }).catch((error) => {
251
+        console.log(error)
252
+ })
253
+```
254
+### multipartUpload
255
+
256
+```
257
+//uploadId is  the value When call initMultipartUpload ,success callback return
258
+AliyunOSS.multipartUpload(multipartBucket,mulitipartObjectKey,uploadId,filepath).then((res)=>{
259
+    Alert.alert("success");
260
+  }).catch((e) => {
261
+    Alert.alert("fail");
262
+  })
263
+```
264
+### listParts
265
+
266
+```
267
+AliyunOSS.listParts(multipartBucket,multipartObjectKey,upoadId).then((e)=>{
268
+    Alert.alert("onListParts"+e)
269
+  }).catch((e)=>{
270
+    Alert.alert("onListPartsError")
271
+ })
272
+```
273
+### abortMultipartUpload
274
+
275
+```
276
+ AliyunOSS.abortMultipartUpload(multipartBucket,multipartBucket,uploadId).then((e)=>{
277
+    Alert.alert("abort success");
278
+  }).catch((e)=>{
279
+    Alert.alert("abort fali");
280
+  })
281
+```
282
+
283
+### asyncDownload
284
+
285
+```
286
+ // xxx is the image process option
287
+ AliyunOSS.asyncDownload(bucketname,objectkey,{"x-oss-process":'xxxx'}).then((e) => {
288
+    console.log(e)
289
+  }).catch((e)=>{
290
+    console.log(e)
291
+  })
292
+```
293
+### asyncCreateBucket
294
+
295
+```
296
+ AliyunOSS.asyncCreateBucket('tyluoluo','private','oss-cn-zhangjiakou').then((e) => {
297
+    console.log(e)
298
+  }).catch((e)=>{
299
+     console.log(e)
300
+  })
301
+```
302
+
303
+### asyncGetBucketACL
304
+
305
+```javascript
306
+ AliyunOSS.asyncGetBucketACL('luozhang002').then((e) => {
307
+    console.log(e)
308
+  }).catch((e)=>{
309
+    console.log(e)
310
+  })
311
+```
312
+### asyncListBuckets
313
+
314
+```
315
+AliyunOSS.asyncListBuckets().then((e) => {
316
+    console.log(e)
317
+  }).catch((e) => {
318
+    console.log(e)
319
+  })
320
+```
321
+### asyncDeleteBucket
322
+
323
+```
324
+ AliyunOSS.asyncDeleteBucket("tyluoluo").then((e) => {
325
+    console.log(e)
326
+  }).catch((e) => {
327
+    console.log(e)
328
+  })
329
+```
330
+### asyncHeadObject
331
+
332
+```
333
+ AliyunOSS.asyncHeadObject('luozhang002','yanxing').then((e)=>{
334
+    console.log(e)
335
+  }).catch((e)=> {
336
+     console.log(e)
337
+ })
338
+```
339
+### asyncListObjects
340
+
341
+```
342
+ AliyunOSS.asyncListObjects('luozhang002').then((e)=>{
343
+    console.log(e)
344
+  }).catch((e)=>{
345
+     console.log(e)
346
+  })
347
+```
348
+### doesObjectExist
349
+
350
+```
351
+ AliyunOSS.doesObjectExist('luozhang001','xx.png').then((e)=>{
352
+    console.log(e)
353
+  }).catch((e)=>{
354
+     console.log(e)
355
+  })
356
+```
357
+
358
+### asyncCopyObject
359
+
360
+```
361
+ AliyunOSS.asyncCopyObject('luozhang001',"2.png","luozhang002","sbsbsb").then((e)=>{
362
+      console.log(e)
363
+    }).catch((e)=>{
364
+      console.log("xxxx")
365
+      console.log(e)
366
+    })
367
+```
368
+### asyncDeleteObject
369
+
370
+```
371
+ AliyunOSS.asyncDeleteObject('luozhang001','2.png').then((e)=>{
372
+     Alert.alert(e)
373
+  }).catch((e)=>{
374
+    console.log(e)
375
+  })
376
+```
377
+
378
+## DEMO
379
+
380
+In the repository, we prodive RN SDK DEMO in the Example folder including andriod and ios,`Example/android` provide the android demo;`Example/NativeAddRN` provide the ios demo.Welcome to join us, how to run the Example ?
381
+
382
+* step-1:clone the project and install some dependencies
383
+
384
+```
385
+1. git clone https://github.com/aliyun/aliyun-oss-react-native.git
386
+2. cd Example
387
+3. npm install
388
+```
389
+
390
+* step-2:start local auth server and modify the URL in initWithServerSTS function of Example/App.js,Server address must begin with ip,of cource you can refer to the scrpts folder we provied.defalut port is 9000
391
+
392
+```
393
+1. cd script/sts-app-server-node
394
+2. node index.js
395
+```
396
+
397
+* step-3:run the project
398
+
399
+1. npm run start
400
+2. open Example/android ,compile and run with Android Studio.The effect is as follows
401
+
402
+<image  text-align="center" width="200" height="400" src="https://img.alicdn.com/tfs/TB1nQ2pqSBYBeNjy0FeXXbnmFXa-658-1230.png"/>
403
+
404
+3. open Example/NativeAddRN ,compile and run with XCode,The effect is as follows
405
+
406
+<image width="200" height="400" src="https://img.alicdn.com/tfs/TB1ejWwqH9YBuNjy0FgXXcxcXXa-778-1488.png"/>
407
+
408
+## F&Q
409
+
410
+* Due to the complexity of React Native's own environment on the iOS side,it ofen occur differrent errors, please go to [stackoverflow](https://stackoverflow.com/questions/tagged/react-native)
411
+* close proxy
412
+* Sometimes,you can not see the ui in the debugging mode of the Android Studio Envrionment,  please delete the Build folder under the project file and then recompile
413
+
414
+## Join
415
+
416
+Now, React Native SDK is in the initial stage. When the developers use React Native API, any problem can be raised to the official warehouse for issue or PR. We will deal with it in time. Wecome much more developers to join us to serve customers and developers that who use aliyun storage services
417
+To better serve customers and developers who use aliyun storage services.You can refer to the following documentation.
418
+
419
+* React Native Android Native Modules:http://facebook.github.io/react-native/docs/native-modules-android.html
420
+* React Native IOS Native Modules:http://facebook.github.io/react-native/docs/native-modules-ios.html
421
+* React Native Debugging: http://facebook.github.io/react-native/docs/debugging.html
422
+* Aliyun OSS Android SDK: https://github.com/aliyun/aliyun-oss-android-sdk
423
+* Aliyun OSS iOS SDK: https://github.com/aliyun/aliyun-oss-ios-sdk
424
+
425
+## License
426
+
427
+* MIT
428
+
429
+## Contact us
430
+
431
+* [Alibaba Cloud OSS official website](http://oss.aliyun.com).
432
+* [Alibaba Cloud OSS official forum](http://bbs.aliyun.com).
433
+* [Alibaba Cloud OSS official documentation center](http://www.aliyun.com/product/oss#Docs).
434
+* Alibaba Cloud official technical support: [Submit a ticket](https://workorder.console.aliyun.com/#/ticket/createIndex).
435
+
436
+## Future
437
+
438
+in the future, Continuously optimizing code documentation、add interfaces 、fix bugs, etc.
439
+
440
+## Documentation
441
+
442
+enhancement

+ 19
- 0
aliyun-oss-react-native.podspec View File

@@ -0,0 +1,19 @@
1
+require 'json'
2
+package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
3
+
4
+Pod::Spec.new do |s|
5
+  s.name          = package['name']
6
+  s.version       = package["version"]
7
+  s.summary       = package['description']
8
+  s.author        = { 'albertluo' => 'luozhang002@126.com' }
9
+  s.license       = package['license']
10
+  s.homepage      = package['homepage']
11
+  s.source        = { :git => 'https://github.com/aliyun/aliyun-oss-react-native.git' }
12
+  s.platform      = :ios, '8.0'
13
+
14
+  s.source_files  = 'ios/*.{h,m}'
15
+
16
+  s.dependency 'React'
17
+  s.dependency 'AliyunOSSiOS'
18
+
19
+end

+ 37
- 0
android/build.gradle View File

@@ -0,0 +1,37 @@
1
+
2
+buildscript {
3
+    repositories {
4
+        jcenter()
5
+    }
6
+
7
+    dependencies {
8
+        classpath 'com.android.tools.build:gradle:1.3.1'
9
+    }
10
+}
11
+
12
+apply plugin: 'com.android.library'
13
+
14
+android {
15
+    compileSdkVersion 23
16
+    buildToolsVersion '27.0.3'
17
+
18
+    defaultConfig {
19
+        minSdkVersion 16
20
+        targetSdkVersion 22
21
+        versionCode 1
22
+        versionName "1.0"
23
+    }
24
+    lintOptions {
25
+        abortOnError false
26
+    }
27
+}
28
+
29
+repositories {
30
+    mavenCentral()
31
+}
32
+
33
+dependencies {
34
+    compile 'com.facebook.react:react-native:+'
35
+    compile 'com.aliyun.dpa:oss-android-sdk:+'
36
+}
37
+  

+ 6
- 0
android/src/main/AndroidManifest.xml View File

@@ -0,0 +1,6 @@
1
+
2
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
3
+          package="com.reactlibrary">
4
+
5
+</manifest>
6
+  

+ 175
- 0
android/src/main/java/com/reactlibrary/AliyunAuthManager.java View File

@@ -0,0 +1,175 @@
1
+package com.reactlibrary;
2
+
3
+import android.content.Context;
4
+import android.util.Log;
5
+
6
+import com.alibaba.sdk.android.oss.ClientConfiguration;
7
+import com.alibaba.sdk.android.oss.OSS;
8
+import com.alibaba.sdk.android.oss.OSSClient;
9
+import com.alibaba.sdk.android.oss.common.OSSConstants;
10
+import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
11
+import com.alibaba.sdk.android.oss.common.auth.OSSCustomSignerCredentialProvider;
12
+import com.alibaba.sdk.android.oss.common.auth.OSSFederationCredentialProvider;
13
+import com.alibaba.sdk.android.oss.common.auth.OSSFederationToken;
14
+import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
15
+import com.alibaba.sdk.android.oss.common.utils.IOUtils;
16
+import com.facebook.react.bridge.ReactMethod;
17
+import com.facebook.react.bridge.ReadableMap;
18
+import com.reactlibrary.utils.ConfigUtils;
19
+
20
+import org.json.JSONObject;
21
+
22
+import java.io.InputStream;
23
+import java.net.HttpURLConnection;
24
+import java.net.URL;
25
+
26
+public class AliyunAuthManager {
27
+    private OSS mOSS;
28
+    private Context mContext;
29
+    private AuthListener mAuthListener;
30
+
31
+    /**
32
+     * AliyunAuthManager constructor
33
+     * @param context
34
+     * @param listener
35
+     */
36
+    public AliyunAuthManager(Context context, AuthListener listener) {
37
+        mContext = context;
38
+        mAuthListener = listener;
39
+    }
40
+
41
+    /**
42
+     * inteface AuthListener
43
+     */
44
+    public interface AuthListener {
45
+        void onAuthFinished(OSS oss);
46
+    }
47
+
48
+    /**
49
+     * initWithSigner
50
+     * @param signature
51
+     * @param accessKey
52
+     * @param endPoint
53
+     * @param configuration
54
+     */
55
+    public void initWithSigner(final String signature,
56
+                               final String accessKey,
57
+                               String endPoint,
58
+                               ReadableMap configuration) {
59
+
60
+        OSSCredentialProvider credentialProvider = new OSSCustomSignerCredentialProvider() {
61
+            @Override
62
+            public String signContent(String content) {
63
+                return "OSS " + accessKey + ":" + signature;
64
+            }
65
+        };
66
+
67
+        // init conf
68
+        ClientConfiguration conf = ConfigUtils.initAuthConfig(configuration);
69
+
70
+        mOSS = new OSSClient(mContext, endPoint, credentialProvider, conf);
71
+        Log.d("AliyunOSS", "OSS initWithSigner ok!");
72
+        mAuthListener.onAuthFinished(mOSS);
73
+    }
74
+
75
+    /**
76
+     * initWithPlainTextAccessKey
77
+     * @param accessKeyId
78
+     * @param accessKeySecret
79
+     * @param endPoint
80
+     * @param configuration
81
+     */
82
+    public void initWithPlainTextAccessKey(String accessKeyId,
83
+                                           String accessKeySecret,
84
+                                           String endPoint,
85
+                                           ReadableMap configuration) {
86
+        OSSCredentialProvider credentialProvider = new OSSFederationCredentialProvider() {
87
+            @Override
88
+            public OSSFederationToken getFederationToken() {
89
+                try {
90
+                    URL stsUrl = new URL("http://yourip:port");
91
+                    HttpURLConnection conn = (HttpURLConnection) stsUrl.openConnection();
92
+                    InputStream input = conn.getInputStream();
93
+                    String jsonText = IOUtils.readStreamAsString(input, OSSConstants.DEFAULT_CHARSET_NAME);
94
+                    JSONObject jsonObjs = new JSONObject(jsonText);
95
+                    String ak = jsonObjs.getString("AccessKeyId");
96
+                    String sk = jsonObjs.getString("AccessKeySecret");
97
+                    String token = jsonObjs.getString("SecurityToken");
98
+                    String expiration = jsonObjs.getString("Expiration");
99
+                    return new OSSFederationToken(ak, sk, token, expiration);
100
+                } catch (Exception e) {
101
+                    e.printStackTrace();
102
+                }
103
+                return null;
104
+            }
105
+        };
106
+
107
+        // init conf
108
+        ClientConfiguration conf = ConfigUtils.initAuthConfig(configuration);
109
+
110
+        mOSS = new OSSClient(mContext, endPoint, credentialProvider, conf);
111
+        Log.d("AliyunOSS", "OSS initWithKey ok!");
112
+        mAuthListener.onAuthFinished(mOSS);
113
+    }
114
+
115
+    /**
116
+     * initWithPlainTextAccessKey
117
+     * @param securityToken
118
+     * @param accessKeyId
119
+     * @param accessKeySecret
120
+     * @param endPoint
121
+     * @param configuration
122
+     */
123
+    public void initWithSecurityToken(String securityToken,
124
+                                      String accessKeyId,
125
+                                      String accessKeySecret,
126
+                                      String endPoint,
127
+                                      ReadableMap configuration) {
128
+        OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
129
+
130
+        // init conf
131
+        ClientConfiguration conf = ConfigUtils.initAuthConfig(configuration);
132
+
133
+        mOSS = new OSSClient(mContext, endPoint, credentialProvider, conf);
134
+        Log.d("AliyunOSS", "OSS initWithKey ok!");
135
+        mAuthListener.onAuthFinished(mOSS);
136
+    }
137
+
138
+    /**
139
+     * initWithServerSTS
140
+     * @param server
141
+     * @param endPoint
142
+     * @param configuration
143
+     */
144
+    public void initWithServerSTS(final String server,
145
+                                  String endPoint,
146
+                                  ReadableMap configuration) {
147
+        OSSCredentialProvider credentialProvider = new OSSFederationCredentialProvider() {
148
+            @Override
149
+            public OSSFederationToken getFederationToken() {
150
+                try {
151
+                    URL stsUrl = new URL(server);
152
+                    HttpURLConnection conn = (HttpURLConnection) stsUrl.openConnection();
153
+                    InputStream input = conn.getInputStream();
154
+                    String jsonText = IOUtils.readStreamAsString(input, OSSConstants.DEFAULT_CHARSET_NAME);
155
+                    JSONObject jsonObjs = new JSONObject(jsonText);
156
+                    String ak = jsonObjs.getString("AccessKeyId");
157
+                    String sk = jsonObjs.getString("AccessKeySecret");
158
+                    String token = jsonObjs.getString("SecurityToken");
159
+                    String expiration = jsonObjs.getString("Expiration");
160
+                    return new OSSFederationToken(ak, sk, token, expiration);
161
+                } catch (Exception e) {
162
+                    e.printStackTrace();
163
+                }
164
+                return null;
165
+            }
166
+        };
167
+
168
+        // init conf
169
+        ClientConfiguration conf = ConfigUtils.initAuthConfig(configuration);
170
+
171
+        mOSS = new OSSClient(mContext, endPoint, credentialProvider, conf);
172
+        Log.d("AliyunOSS", "OSS initWithKey ok!");
173
+        mAuthListener.onAuthFinished(mOSS);
174
+    }
175
+}

+ 133
- 0
android/src/main/java/com/reactlibrary/AliyunBucketManager.java View File

@@ -0,0 +1,133 @@
1
+package com.reactlibrary;
2
+
3
+import android.util.Log;
4
+
5
+import com.alibaba.sdk.android.oss.ClientException;
6
+import com.alibaba.sdk.android.oss.OSS;
7
+import com.alibaba.sdk.android.oss.ServiceException;
8
+import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
9
+import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
10
+import com.alibaba.sdk.android.oss.model.CannedAccessControlList;
11
+import com.alibaba.sdk.android.oss.model.CreateBucketRequest;
12
+import com.alibaba.sdk.android.oss.model.CreateBucketResult;
13
+import com.alibaba.sdk.android.oss.model.DeleteBucketRequest;
14
+import com.alibaba.sdk.android.oss.model.DeleteBucketResult;
15
+import com.alibaba.sdk.android.oss.model.GetBucketACLRequest;
16
+import com.alibaba.sdk.android.oss.model.GetBucketACLResult;
17
+import com.alibaba.sdk.android.oss.model.ListBucketsRequest;
18
+import com.alibaba.sdk.android.oss.model.ListBucketsResult;
19
+import com.facebook.react.bridge.Arguments;
20
+import com.facebook.react.bridge.Promise;
21
+import com.facebook.react.bridge.ReactMethod;
22
+import com.facebook.react.bridge.WritableMap;
23
+
24
+public class AliyunBucketManager {
25
+    private OSS mOSS;
26
+
27
+    /**
28
+     * AliyunBucketManager
29
+     * @param oss
30
+     */
31
+    public AliyunBucketManager(OSS oss) {
32
+        mOSS = oss;
33
+    }
34
+
35
+    /**
36
+     * asyncCreateBucket
37
+     * @param bucketName
38
+     * @param acl
39
+     * @param region
40
+     * @param promise
41
+     */
42
+    public void asyncCreateBucket(String bucketName, String acl, String region, final Promise promise) {
43
+        CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
44
+        createBucketRequest.setBucketACL(CannedAccessControlList.parseACL(acl));
45
+        createBucketRequest.setLocationConstraint(region);
46
+        OSSAsyncTask createTask = mOSS.asyncCreateBucket(createBucketRequest, new OSSCompletedCallback<CreateBucketRequest, CreateBucketResult>() {
47
+            @Override
48
+            public void onSuccess(CreateBucketRequest createBucketRequest, CreateBucketResult createBucketResult) {
49
+                Log.d("locationConstraint", createBucketRequest.getLocationConstraint());
50
+                promise.resolve("createBucket success");
51
+            }
52
+
53
+            @Override
54
+            public void onFailure(CreateBucketRequest createBucketRequest, ClientException e, ServiceException e1) {
55
+               PromiseExceptionManager.resolvePromiseException(e,e1,promise);
56
+            }
57
+        });
58
+    }
59
+
60
+    /**
61
+     * asyncGetBucketACL
62
+     * @param bucketName
63
+     * @param promise
64
+     */
65
+    public void asyncGetBucketACL(String bucketName, final Promise promise) {
66
+        GetBucketACLRequest getBucketACLRequest = new GetBucketACLRequest(bucketName);
67
+        OSSAsyncTask getBucketAclTask = mOSS.asyncGetBucketACL(getBucketACLRequest, new OSSCompletedCallback<GetBucketACLRequest, GetBucketACLResult>() {
68
+            @Override
69
+            public void onSuccess(GetBucketACLRequest getBucketACLRequest, GetBucketACLResult getBucketACLResult) {
70
+                Log.d("BucketAcl", getBucketACLResult.getBucketACL());
71
+                Log.d("Owner", getBucketACLResult.getBucketOwner());
72
+                Log.d("ID", getBucketACLResult.getBucketOwnerID());
73
+
74
+                WritableMap map = Arguments.createMap();
75
+                map.putString("BucketAcl", getBucketACLResult.getBucketACL());
76
+                map.putString("Owner", getBucketACLResult.getBucketOwner());
77
+                map.putString("ID", getBucketACLResult.getBucketOwnerID());
78
+                promise.resolve(map);
79
+            }
80
+
81
+            @Override
82
+            public void onFailure(GetBucketACLRequest getBucketACLRequest, ClientException e, ServiceException e1) {
83
+                PromiseExceptionManager.resolvePromiseException(e, e1, promise);
84
+            }
85
+        });
86
+    }
87
+
88
+    /**
89
+     * asyncListBuckets
90
+     * @param promise
91
+     */
92
+    public void asyncListBuckets(final Promise promise) {
93
+
94
+        ListBucketsRequest listBuckets = new ListBucketsRequest();
95
+
96
+        OSSAsyncTask task = mOSS.asyncListBuckets(listBuckets, new OSSCompletedCallback<ListBucketsRequest, ListBucketsResult>() {
97
+            @Override
98
+            public void onSuccess(ListBucketsRequest request, ListBucketsResult result) {
99
+                Log.d("listBuckets", "Success!");
100
+                WritableMap map = Arguments.createMap();
101
+                for (int i = 0;i < result.getBuckets().size();i++) {
102
+                    map.putString("Bucket"+i,result.getBuckets().get(i).toString());
103
+                    Log.d("asyncListBuckets","bucket:"+result.getBuckets().get(i));
104
+                }
105
+                promise.resolve(map);
106
+            }
107
+
108
+            @Override
109
+            public void onFailure(ListBucketsRequest request, ClientException clientException, ServiceException serviceException) {
110
+                PromiseExceptionManager.resolvePromiseException(clientException,serviceException,promise);
111
+            }
112
+        });
113
+    }
114
+
115
+    /**
116
+     * asyncDeleteBucket
117
+     * @param bucketName
118
+     * @param promise
119
+     */
120
+    public void asyncDeleteBucket(String bucketName,final Promise promise) {
121
+        DeleteBucketRequest deleteBucketRequest = new DeleteBucketRequest(bucketName);
122
+        OSSAsyncTask deleteBucketTask = mOSS.asyncDeleteBucket(deleteBucketRequest, new OSSCompletedCallback<DeleteBucketRequest, DeleteBucketResult>() {
123
+            @Override
124
+            public void onSuccess(DeleteBucketRequest request, DeleteBucketResult result) {
125
+                promise.resolve("Delete Bucket Success!!!!!");
126
+            }
127
+            @Override
128
+            public void onFailure(DeleteBucketRequest request, ClientException clientException, ServiceException serviceException) {
129
+                PromiseExceptionManager.resolvePromiseException(clientException,serviceException,promise);
130
+            }
131
+        });
132
+    }
133
+}

+ 133
- 0
android/src/main/java/com/reactlibrary/AliyunDownloadManager.java View File

@@ -0,0 +1,133 @@
1
+package com.reactlibrary;
2
+
3
+import android.os.Environment;
4
+import android.util.Log;
5
+
6
+import com.alibaba.sdk.android.oss.ClientException;
7
+import com.alibaba.sdk.android.oss.OSS;
8
+import com.alibaba.sdk.android.oss.ServiceException;
9
+import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
10
+import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
11
+import com.alibaba.sdk.android.oss.model.GetObjectRequest;
12
+import com.alibaba.sdk.android.oss.model.GetObjectResult;
13
+import com.facebook.react.bridge.Arguments;
14
+import com.facebook.react.bridge.Promise;
15
+import com.facebook.react.bridge.ReactContext;
16
+import com.facebook.react.bridge.ReactMethod;
17
+import com.facebook.react.bridge.ReadableMap;
18
+import com.facebook.react.bridge.WritableMap;
19
+import com.facebook.react.modules.core.DeviceEventManagerModule;
20
+
21
+import java.io.File;
22
+import java.io.FileNotFoundException;
23
+import java.io.FileOutputStream;
24
+import java.io.IOException;
25
+import java.io.InputStream;
26
+
27
+public class AliyunDownloadManager {
28
+    private OSS mOSS;
29
+
30
+    /**
31
+     * AliyunDownloadManager
32
+     * @param oss
33
+     */
34
+    public AliyunDownloadManager(OSS oss) {
35
+        mOSS = oss;
36
+    }
37
+
38
+    public void asyncDownload(final ReactContext context,String bucketName, String ossFile, String updateDate, ReadableMap options, final Promise promise) {
39
+        GetObjectRequest get = new GetObjectRequest(bucketName, ossFile);
40
+
41
+        String xOssPositon = options.getString("x-oss-process");
42
+        //process image
43
+        get.setxOssProcess(xOssPositon);
44
+
45
+        OSSAsyncTask task = mOSS.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
46
+            @Override
47
+            public void onSuccess(GetObjectRequest request, GetObjectResult result) {
48
+
49
+                Log.d("Content-Length", "" + result.getContentLength());
50
+
51
+                InputStream inputStream = result.getObjectContent();
52
+                long resultLength = result.getContentLength();
53
+
54
+                byte[] buffer = new byte[2048];
55
+                int len;
56
+
57
+                FileOutputStream outputStream = null;
58
+                String localImgURL = Environment.getExternalStorageDirectory().getAbsolutePath() +
59
+                        "/ImgCache/" +
60
+                        System.currentTimeMillis() +
61
+                        ".jpg";
62
+                Log.d("localImgURL", localImgURL);
63
+                File cacheFile = new File(localImgURL);
64
+                if (!cacheFile.exists()) {
65
+                    cacheFile.getParentFile().mkdirs();
66
+                    try {
67
+                        cacheFile.createNewFile();
68
+                    } catch (IOException e) {
69
+                        e.printStackTrace();
70
+                        promise.reject("DownloadFaile", e);
71
+                    }
72
+                }
73
+                long readSize = cacheFile.length();
74
+                try {
75
+                    outputStream = new FileOutputStream(cacheFile, true);
76
+                } catch (FileNotFoundException e) {
77
+                    e.printStackTrace();
78
+                    promise.reject("DownloadFaile", e);
79
+                }
80
+                if (resultLength == -1) {
81
+                    promise.reject("DownloadFaile", "message:lengtherror");
82
+                }
83
+
84
+                try {
85
+                    while ((len = inputStream.read(buffer)) != -1) {
86
+                       // resove download data
87
+                        try {
88
+                            outputStream.write(buffer, 0, len);
89
+                            readSize += len;
90
+
91
+                            String str_currentSize = Long.toString(readSize);
92
+                            String str_totalSize = Long.toString(resultLength);
93
+                            WritableMap onProgressValueData = Arguments.createMap();
94
+                            onProgressValueData.putString("currentSize", str_currentSize);
95
+                            onProgressValueData.putString("totalSize", str_totalSize);
96
+                            context.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
97
+                                    .emit("downloadProgress", onProgressValueData);
98
+
99
+                        } catch (IOException e) {
100
+                            e.printStackTrace();
101
+                            promise.reject("DownloadFaile", e);
102
+                        }
103
+                    }
104
+                    outputStream.flush();
105
+                } catch (IOException e) {
106
+                    e.printStackTrace();
107
+                    promise.reject("DownloadFaile", e);
108
+                } finally {
109
+                    if (outputStream != null) {
110
+                        try {
111
+                            outputStream.close();
112
+                        } catch (IOException e) {
113
+                            promise.reject("DownloadFaile", e);
114
+                        }
115
+                    }
116
+                    if (inputStream != null) {
117
+                        try {
118
+                            inputStream.close();
119
+                        } catch (IOException e) {
120
+                            promise.reject("DownloadFaile", e);
121
+                        }
122
+                    }
123
+                    promise.resolve(localImgURL);
124
+                }
125
+            }
126
+
127
+            @Override
128
+            public void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
129
+                PromiseExceptionManager.resolvePromiseException(clientExcepion,serviceException,promise);
130
+            }
131
+        });
132
+    }
133
+}

+ 180
- 0
android/src/main/java/com/reactlibrary/AliyunObjectManager.java View File

@@ -0,0 +1,180 @@
1
+package com.reactlibrary;
2
+
3
+import android.util.Log;
4
+
5
+import com.alibaba.sdk.android.oss.ClientException;
6
+import com.alibaba.sdk.android.oss.OSS;
7
+import com.alibaba.sdk.android.oss.ServiceException;
8
+import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
9
+import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
10
+import com.alibaba.sdk.android.oss.model.CopyObjectRequest;
11
+import com.alibaba.sdk.android.oss.model.CopyObjectResult;
12
+import com.alibaba.sdk.android.oss.model.DeleteObjectRequest;
13
+import com.alibaba.sdk.android.oss.model.DeleteObjectResult;
14
+import com.alibaba.sdk.android.oss.model.HeadObjectRequest;
15
+import com.alibaba.sdk.android.oss.model.HeadObjectResult;
16
+import com.alibaba.sdk.android.oss.model.ListObjectsRequest;
17
+import com.alibaba.sdk.android.oss.model.ListObjectsResult;
18
+import com.facebook.react.bridge.Arguments;
19
+import com.facebook.react.bridge.Promise;
20
+import com.facebook.react.bridge.ReadableMap;
21
+import com.facebook.react.bridge.WritableMap;
22
+
23
+public class AliyunObjectManager {
24
+    private OSS mOSS;
25
+
26
+    /**
27
+     * AliyunObjectManager contructro
28
+     * @param oss
29
+     */
30
+    public AliyunObjectManager(OSS oss) {
31
+        mOSS = oss;
32
+    }
33
+
34
+    /**
35
+     * asyncHeadObject
36
+     * @param bucketName
37
+     * @param objectKey
38
+     * @param promise
39
+     */
40
+    public void asyncHeadObject(String bucketName, String objectKey, final Promise promise) {
41
+
42
+        HeadObjectRequest head = new HeadObjectRequest(bucketName, objectKey);
43
+        OSSAsyncTask task = mOSS.asyncHeadObject(head, new OSSCompletedCallback<HeadObjectRequest, HeadObjectResult>() {
44
+            @Override
45
+            public void onSuccess(HeadObjectRequest headObjectRequest, HeadObjectResult headObjectResult) {
46
+                float objectSize = headObjectResult.getMetadata().getContentLength();
47
+                String objectContentType = headObjectResult.getMetadata().getContentType();
48
+                Log.d("headObject", "object Size: " + headObjectResult.getMetadata().getContentLength());
49
+                Log.d("headObject", "object Content Type: " + headObjectResult.getMetadata().getContentType());
50
+                WritableMap map = Arguments.createMap();
51
+                map.putDouble("objectSize", objectSize);
52
+                map.putString("objectContentType", objectContentType);
53
+                promise.resolve(map);
54
+            }
55
+
56
+            @Override
57
+            public void onFailure(HeadObjectRequest headObjectRequest, ClientException e, ServiceException e1) {
58
+                PromiseExceptionManager.resolvePromiseException(e,e1,promise);
59
+            }
60
+        });
61
+    }
62
+
63
+    /**
64
+     * doesObjectExist
65
+     * @param bucketName
66
+     * @param objectKey
67
+     * @param promise
68
+     */
69
+    public void doesObjectExist(String bucketName,String objectKey,final Promise promise) {
70
+        try {
71
+            if (mOSS.doesObjectExist(bucketName,objectKey)) {
72
+                Log.d("doesObjectExist", "object exist.");
73
+                promise.resolve("object exist");
74
+            } else {
75
+                Log.d("doesObjectExist", "object does not exist.");
76
+                promise.resolve("object does not exist");
77
+            }
78
+        } catch (ClientException e) {
79
+            // 本地异常如网络异常等
80
+            e.printStackTrace();
81
+            promise.reject(e);
82
+        } catch (ServiceException e) {
83
+            // 服务异常
84
+            Log.e("ErrorCode", e.getErrorCode());
85
+            Log.e("RequestId", e.getRequestId());
86
+            Log.e("HostId", e.getHostId());
87
+            Log.e("RawMessage", e.getRawMessage());
88
+            promise.reject(e);
89
+        }
90
+    }
91
+
92
+    /**
93
+     * asyncListObjects
94
+     * @param bucketName
95
+     * @param prefix
96
+     * @param promise
97
+     */
98
+    public void asyncListObjects(String bucketName,String prefix,final Promise promise) {
99
+        ListObjectsRequest listObjects = new ListObjectsRequest(bucketName);
100
+        listObjects.setPrefix(prefix);
101
+
102
+        // set success 、set fail 、set async request
103
+        OSSAsyncTask task = mOSS.asyncListObjects(listObjects, new OSSCompletedCallback<ListObjectsRequest, ListObjectsResult>() {
104
+            @Override
105
+            public void onSuccess(ListObjectsRequest request, ListObjectsResult result) {
106
+                Log.d("AyncListObjects", "Success!");
107
+                WritableMap map = Arguments.createMap();
108
+
109
+                for (int i = 0; i < result.getObjectSummaries().size(); i++) {
110
+                    map.putString("objectKey"+i , result.getObjectSummaries().get(i).getKey());
111
+                    Log.d("AyncListObjects", "object: " + result.getObjectSummaries().get(i).getKey() + " "
112
+                            + result.getObjectSummaries().get(i).getETag() + " "
113
+                            + result.getObjectSummaries().get(i).getLastModified());
114
+                }
115
+                promise.resolve(map);
116
+            }
117
+
118
+            @Override
119
+            public void onFailure(ListObjectsRequest request, ClientException clientExcepion, ServiceException serviceException) {
120
+                PromiseExceptionManager.resolvePromiseException(clientExcepion,serviceException,promise);
121
+            }
122
+        });
123
+
124
+    }
125
+
126
+    public void asyncCopyObject(String srcBucketName,
127
+                                String srcObjectKey,
128
+                                String desBucketName,
129
+                                String destObjectKey,
130
+                                ReadableMap options,
131
+                                final Promise promise) {
132
+
133
+        CopyObjectRequest copyObjectRequest = new CopyObjectRequest(srcBucketName, srcObjectKey,
134
+                desBucketName, destObjectKey);
135
+//
136
+//        set copy metadata
137
+//        ObjectMetadata objectMetadata = new ObjectMetadata();
138
+//        objectMetadata.setContentType("application/octet-stream");
139
+//        copyObjectRequest.setNewObjectMetadata(objectMetadata);
140
+
141
+        // async copy
142
+        OSSAsyncTask copyTask = mOSS.asyncCopyObject(copyObjectRequest, new OSSCompletedCallback<CopyObjectRequest, CopyObjectResult>() {
143
+            @Override
144
+            public void onSuccess(CopyObjectRequest request, CopyObjectResult result) {
145
+                Log.d("copyObject", "copy success!");
146
+                promise.resolve("copy success!");
147
+            }
148
+
149
+            @Override
150
+            public void onFailure(CopyObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
151
+              PromiseExceptionManager.resolvePromiseException(clientExcepion,serviceException,promise);
152
+            }
153
+        });
154
+    }
155
+
156
+    /**
157
+     * asyncDeleteObject
158
+     * @param bucketName
159
+     * @param objectKey
160
+     * @param promise
161
+     */
162
+    public void asyncDeleteObject(String bucketName, String objectKey, final Promise promise) {
163
+
164
+        // async delete request
165
+        DeleteObjectRequest delete = new DeleteObjectRequest(bucketName, objectKey);
166
+
167
+        OSSAsyncTask deleteTask = mOSS.asyncDeleteObject(delete, new OSSCompletedCallback<DeleteObjectRequest, DeleteObjectResult>() {
168
+            @Override
169
+            public void onSuccess(DeleteObjectRequest request, DeleteObjectResult result) {
170
+                Log.d("asyncCopyAndDelObject", "success!");
171
+                promise.resolve("delete success!");
172
+            }
173
+
174
+            @Override
175
+            public void onFailure(DeleteObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
176
+                PromiseExceptionManager.resolvePromiseException(clientExcepion,serviceException,promise);
177
+            }
178
+        });
179
+    }
180
+}

+ 410
- 0
android/src/main/java/com/reactlibrary/AliyunUploadManager.java View File

@@ -0,0 +1,410 @@
1
+package com.reactlibrary;
2
+
3
+import android.annotation.SuppressLint;
4
+import android.content.Context;
5
+import android.database.Cursor;
6
+import android.net.Uri;
7
+import android.provider.MediaStore;
8
+import android.util.Log;
9
+
10
+import com.alibaba.sdk.android.oss.ClientException;
11
+import com.alibaba.sdk.android.oss.OSS;
12
+import com.alibaba.sdk.android.oss.ServiceException;
13
+import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
14
+import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
15
+import com.alibaba.sdk.android.oss.common.utils.IOUtils;
16
+import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
17
+import com.alibaba.sdk.android.oss.model.AbortMultipartUploadRequest;
18
+import com.alibaba.sdk.android.oss.model.AppendObjectRequest;
19
+import com.alibaba.sdk.android.oss.model.AppendObjectResult;
20
+import com.alibaba.sdk.android.oss.model.CompleteMultipartUploadRequest;
21
+import com.alibaba.sdk.android.oss.model.CompleteMultipartUploadResult;
22
+import com.alibaba.sdk.android.oss.model.InitiateMultipartUploadRequest;
23
+import com.alibaba.sdk.android.oss.model.InitiateMultipartUploadResult;
24
+import com.alibaba.sdk.android.oss.model.ListPartsRequest;
25
+import com.alibaba.sdk.android.oss.model.ListPartsResult;
26
+import com.alibaba.sdk.android.oss.model.ObjectMetadata;
27
+import com.alibaba.sdk.android.oss.model.PartETag;
28
+import com.alibaba.sdk.android.oss.model.PutObjectRequest;
29
+import com.alibaba.sdk.android.oss.model.PutObjectResult;
30
+import com.alibaba.sdk.android.oss.model.ResumableUploadRequest;
31
+import com.alibaba.sdk.android.oss.model.ResumableUploadResult;
32
+import com.alibaba.sdk.android.oss.model.UploadPartRequest;
33
+import com.alibaba.sdk.android.oss.model.UploadPartResult;
34
+import com.facebook.react.bridge.Arguments;
35
+import com.facebook.react.bridge.Promise;
36
+import com.facebook.react.bridge.ReactContext;
37
+import com.facebook.react.bridge.ReactMethod;
38
+import com.facebook.react.bridge.ReadableMap;
39
+import com.facebook.react.bridge.WritableMap;
40
+import com.facebook.react.modules.core.DeviceEventManagerModule;
41
+import com.reactlibrary.utils.FileUtils;
42
+
43
+import java.io.File;
44
+import java.io.FileInputStream;
45
+import java.io.FileNotFoundException;
46
+import java.io.IOException;
47
+import java.io.InputStream;
48
+import java.util.ArrayList;
49
+import java.util.HashMap;
50
+import java.util.List;
51
+
52
+public class AliyunUploadManager {
53
+
54
+    private OSS mOSS;
55
+
56
+    /**
57
+     * AliyunUploadManager contructor
58
+     * @param oss
59
+     */
60
+    public AliyunUploadManager(OSS oss) {
61
+        mOSS = oss;
62
+    }
63
+
64
+    /**
65
+     * asyncUpload
66
+     * @param context
67
+     * @param bucketName
68
+     * @param ossFile
69
+     * @param sourceFile
70
+     * @param options
71
+     * @param promise
72
+     */
73
+    public void asyncUpload(final ReactContext context, String bucketName, String ossFile, String sourceFile, ReadableMap options, final Promise promise) {
74
+        // Content to file:// start
75
+        Uri selectedVideoUri = Uri.parse(sourceFile);
76
+
77
+        // 1. content uri -> file path
78
+        // 2. inputstream -> temp file path
79
+        Cursor cursor = null;
80
+        try {
81
+            String[] proj = {MediaStore.Images.Media.DATA};
82
+            cursor = context.getCurrentActivity().getContentResolver().query(selectedVideoUri, proj, null, null, null);
83
+            if (cursor == null) sourceFile = selectedVideoUri.getPath();
84
+            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
85
+            cursor.moveToFirst();
86
+            sourceFile = cursor.getString(column_index);
87
+        } catch (Exception e) {
88
+            sourceFile = FileUtils.getFilePathFromURI(context.getCurrentActivity(), selectedVideoUri);
89
+        } finally {
90
+            if (cursor != null) {
91
+                cursor.close();
92
+            }
93
+        }
94
+        // init upload request
95
+        PutObjectRequest put = new PutObjectRequest(bucketName, ossFile, sourceFile);
96
+        ObjectMetadata metadata = new ObjectMetadata();
97
+        metadata.setContentType("application/octet-stream");
98
+        put.setMetadata(metadata);
99
+
100
+        // set callback
101
+        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
102
+            @Override
103
+            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
104
+                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
105
+                String str_currentSize = Long.toString(currentSize);
106
+                String str_totalSize = Long.toString(totalSize);
107
+                WritableMap onProgressValueData = Arguments.createMap();
108
+                onProgressValueData.putString("currentSize", str_currentSize);
109
+                onProgressValueData.putString("totalSize", str_totalSize);
110
+                context.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
111
+                        .emit("uploadProgress", onProgressValueData);
112
+            }
113
+        });
114
+
115
+        OSSAsyncTask task = mOSS.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
116
+            @Override
117
+            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
118
+                Log.d("PutObject", "UploadSuccess");
119
+                Log.d("ETag", result.getETag());
120
+                Log.d("RequestId", result.getRequestId());
121
+                promise.resolve("UploadSuccess");
122
+            }
123
+
124
+            @Override
125
+            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
126
+                PromiseExceptionManager.resolvePromiseException(clientExcepion,serviceException,promise);
127
+            }
128
+        });
129
+        Log.d("AliyunOSS", "OSS uploadObjectAsync ok!");
130
+    }
131
+
132
+    /**
133
+     * asyncAppendObject
134
+     * @param bucketName
135
+     * @param objectKey
136
+     * @param uploadFilePath
137
+     * @param options
138
+     * @param promise
139
+     */
140
+    public void asyncAppendObject(final ReactContext context,String bucketName,String objectKey,String uploadFilePath,ReadableMap options,final Promise promise) {
141
+
142
+        // Content to file:// start
143
+        Uri selectedVideoUri = Uri.parse(uploadFilePath);
144
+
145
+        // 1. content uri -> file path
146
+        // 2. inputstream -> temp file path
147
+        Cursor cursor = null;
148
+        try {
149
+            String[] proj = {MediaStore.Images.Media.DATA};
150
+            cursor = context.getCurrentActivity().getContentResolver().query(selectedVideoUri, proj, null, null, null);
151
+            if (cursor == null) uploadFilePath = selectedVideoUri.getPath();
152
+            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
153
+            cursor.moveToFirst();
154
+            uploadFilePath = cursor.getString(column_index);
155
+        } catch (Exception e) {
156
+            uploadFilePath = FileUtils.getFilePathFromURI(context.getCurrentActivity(), selectedVideoUri);
157
+        } finally {
158
+            if (cursor != null) {
159
+                cursor.close();
160
+            }
161
+        }
162
+
163
+        AppendObjectRequest append = new AppendObjectRequest(bucketName, objectKey, uploadFilePath);
164
+        ObjectMetadata metadata = new ObjectMetadata();
165
+        metadata.setContentType("application/octet-stream");
166
+        append.setMetadata(metadata);
167
+
168
+        //set appendpostions
169
+        int nextPositon = options.getInt("appendPostions");
170
+        append.setPosition(nextPositon);
171
+
172
+        append.setProgressCallback(new OSSProgressCallback<AppendObjectRequest>() {
173
+            @Override
174
+            public void onProgress(AppendObjectRequest request, long currentSize, long totalSize) {
175
+                Log.d("AppendObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
176
+                // add event
177
+                String str_currentSize = Long.toString(currentSize);
178
+                String str_totalSize = Long.toString(totalSize);
179
+                WritableMap onProgressValueData = Arguments.createMap();
180
+                onProgressValueData.putString("currentSize", str_currentSize);
181
+                onProgressValueData.putString("totalSize", str_totalSize);
182
+                context.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
183
+                        .emit("uploadProgress", onProgressValueData);
184
+            }
185
+        });
186
+
187
+        OSSAsyncTask task = mOSS.asyncAppendObject(append, new OSSCompletedCallback<AppendObjectRequest, AppendObjectResult>() {
188
+            @Override
189
+            public void onSuccess(AppendObjectRequest request, AppendObjectResult result) {
190
+                Log.d("AppendObject", "AppendSuccess");
191
+                Log.d("NextPosition", "" + result.getNextPosition());
192
+                WritableMap map = Arguments.createMap();
193
+                map.putString("AppendObject","AppendSuccess");
194
+                map.putDouble("NextPosition", result.getNextPosition());
195
+                promise.resolve(map);
196
+            }
197
+            @Override
198
+            public void onFailure(AppendObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
199
+                PromiseExceptionManager.resolvePromiseException(clientExcepion,serviceException,promise);
200
+            }
201
+        });
202
+    }
203
+
204
+    /**
205
+     * asyncResumableUpload
206
+     *
207
+     * @param bucketName
208
+     * @param objectKey
209
+     * @param uploadFilePath
210
+     * @param options
211
+     * @param promise
212
+     */
213
+    public void asyncResumableUpload(final ReactContext context, String bucketName, String objectKey, String uploadFilePath, ReadableMap options, final Promise promise) {
214
+
215
+        ResumableUploadRequest request = new ResumableUploadRequest(bucketName, objectKey, uploadFilePath);
216
+
217
+        request.setProgressCallback(new OSSProgressCallback<ResumableUploadRequest>() {
218
+            @Override
219
+            public void onProgress(ResumableUploadRequest request, long currentSize, long totalSize) {
220
+                Log.d("resumableUpload", "currentSize: " + currentSize + " totalSize: " + totalSize);
221
+                // add event
222
+                String str_currentSize = Long.toString(currentSize);
223
+                String str_totalSize = Long.toString(totalSize);
224
+                WritableMap onProgressValueData = Arguments.createMap();
225
+                onProgressValueData.putString("currentSize", str_currentSize);
226
+                onProgressValueData.putString("totalSize", str_totalSize);
227
+                context.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
228
+                        .emit("uploadProgress", onProgressValueData);
229
+            }
230
+        });
231
+
232
+        OSSAsyncTask resumableTask = mOSS.asyncResumableUpload(request, new OSSCompletedCallback<ResumableUploadRequest, ResumableUploadResult>() {
233
+            @Override
234
+            public void onSuccess(ResumableUploadRequest request, ResumableUploadResult result) {
235
+                promise.resolve("resumableUpload success");
236
+            }
237
+
238
+            @Override
239
+            public void onFailure(ResumableUploadRequest request, ClientException clientExcepion, ServiceException serviceException) {
240
+                PromiseExceptionManager.resolvePromiseException(clientExcepion, serviceException, promise);
241
+            }
242
+        });
243
+    }
244
+
245
+    /**
246
+     * initMultipartUpload
247
+     * @param bucketName
248
+     * @param objectKey
249
+     * @param promise
250
+     */
251
+    public void initMultipartUpload(String bucketName,String objectKey,final Promise promise) {
252
+        String uploadId;
253
+        InitiateMultipartUploadRequest init = new InitiateMultipartUploadRequest(bucketName, objectKey);
254
+        InitiateMultipartUploadResult initResult = null;
255
+        try {
256
+            initResult = mOSS.initMultipartUpload(init);
257
+            uploadId = initResult.getUploadId();
258
+            promise.resolve(uploadId);
259
+        } catch (ClientException e) {
260
+            e.printStackTrace();
261
+            promise.reject(e);
262
+        } catch (ServiceException e) {
263
+            e.printStackTrace();
264
+            promise.reject(e);
265
+        }
266
+    }
267
+
268
+    /**
269
+     * multipartUpload
270
+     * @param context
271
+     * @param bucketName
272
+     * @param objectKey
273
+     * @param uploadId
274
+     * @param filepath
275
+     * @param options
276
+     * @param promise
277
+     */
278
+    public void multipartUpload(final ReactContext context,String bucketName, String objectKey, String uploadId,String filepath, ReadableMap options,final Promise promise) {
279
+
280
+        Uri selectedVideoUri = Uri.parse(filepath);
281
+        // 1. content uri -> file path
282
+        // 2. inputstream -> temp file path
283
+        Cursor cursor = null;
284
+        try {
285
+            String[] proj = {MediaStore.Images.Media.DATA};
286
+            cursor = context.getCurrentActivity().getContentResolver().query(selectedVideoUri, proj, null, null, null);
287
+            if (cursor == null) filepath = selectedVideoUri.getPath();
288
+            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
289
+            cursor.moveToFirst();
290
+            filepath = cursor.getString(column_index);
291
+        } catch (Exception e) {
292
+            filepath = FileUtils.getFilePathFromURI(context.getCurrentActivity(), selectedVideoUri);
293
+        } finally {
294
+            if (cursor != null) {
295
+                cursor.close();
296
+            }
297
+        }
298
+
299
+        long partSize = options.getInt("partSize"); // 设置分片大小
300
+        int currentIndex = 1; // 上传分片编号,从1开始
301
+        File uploadFile = new File(filepath); // 需要分片上传的文件
302
+        InputStream input = null;
303
+        try {
304
+            input = new FileInputStream(uploadFile);
305
+        } catch (FileNotFoundException e) {
306
+            e.printStackTrace();
307
+        }
308
+        long fileLength = uploadFile.length();
309
+        long uploadedLength = 0;
310
+        List<PartETag> partETags = new ArrayList<PartETag>(); // 保存分片上传的结果
311
+        while (uploadedLength < fileLength) {
312
+            int partLength = (int)Math.min(partSize, fileLength - uploadedLength);
313
+            byte[] partData = new byte[0]; // 按照分片大小读取文件的一段内容
314
+            try {
315
+                partData = IOUtils.readStreamAsBytesArray(input, partLength);
316
+            } catch (IOException e) {
317
+                e.printStackTrace();
318
+                promise.reject(e);
319
+            }
320
+            UploadPartRequest uploadPart = new UploadPartRequest(bucketName, objectKey, uploadId, currentIndex);
321
+            uploadPart.setPartContent(partData); // 设置分片内容
322
+            UploadPartResult uploadPartResult = null;
323
+            try {
324
+                uploadPartResult = mOSS.uploadPart(uploadPart);
325
+            } catch (ClientException e) {
326
+                e.printStackTrace();
327
+                promise.reject(e);
328
+            } catch (ServiceException e) {
329
+                e.printStackTrace();
330
+                promise.reject(e);
331
+            }
332
+            partETags.add(new PartETag(currentIndex, uploadPartResult.getETag())); // 保存分片上传成功后的结果
333
+            uploadedLength += partLength;
334
+            currentIndex++;
335
+        }
336
+
337
+        CompleteMultipartUploadRequest complete = new CompleteMultipartUploadRequest(bucketName, objectKey,uploadId,partETags);
338
+        CompleteMultipartUploadResult completeResult = null;
339
+        try {
340
+            completeResult = mOSS.completeMultipartUpload(complete);
341
+            promise.resolve("mulitpartlaod success!");
342
+        } catch (ClientException e) {
343
+            e.printStackTrace();
344
+        } catch (ServiceException e) {
345
+            e.printStackTrace();
346
+        }
347
+        complete.setCallbackParam(new HashMap<String, String>() {
348
+            {
349
+                put("callbackUrl", "<server address>");
350
+                put("callbackBody", "<test>");
351
+            }
352
+        });
353
+    }
354
+
355
+    /**
356
+     * abortMultipartUpload
357
+     * @param bucketName
358
+     * @param objectKey
359
+     * @param uploadId
360
+     * @param promise
361
+     */
362
+    public void abortMultipartUpload(String bucketName,String objectKey,String uploadId,final Promise promise) {
363
+        AbortMultipartUploadRequest abort = new AbortMultipartUploadRequest(bucketName, objectKey, uploadId);
364
+        try {
365
+            mOSS.abortMultipartUpload(abort);
366
+            promise.resolve("abort multipart upload success!");
367
+        } catch (ClientException e) {
368
+            e.printStackTrace();
369
+            promise.reject(e);
370
+        } catch (ServiceException e) {
371
+            e.printStackTrace();
372
+            promise.reject(e);
373
+        }
374
+    }
375
+
376
+    /**
377
+     * listParts
378
+     * @param bucketName
379
+     * @param objectKey
380
+     * @param uploadId
381
+     * @param promise
382
+     */
383
+    public void listParts (String bucketName,String objectKey,String uploadId,final Promise promise) {
384
+        ListPartsRequest listParts = new ListPartsRequest(bucketName, objectKey, uploadId);
385
+        ListPartsResult result = null;
386
+        try {
387
+            result = mOSS.listParts(listParts);
388
+        } catch (ClientException e) {
389
+            e.printStackTrace();
390
+            promise.reject(e);
391
+        } catch (ServiceException e) {
392
+            e.printStackTrace();
393
+            promise.reject(e);
394
+        }
395
+
396
+        WritableMap listPartsData = Arguments.createMap();
397
+
398
+        for (int i = 0; i < result.getParts().size(); i++) {
399
+            Log.d("listParts", "partNum: " + result.getParts().get(i).getPartNumber());
400
+            Log.d("listParts", "partEtag: " + result.getParts().get(i).getETag());
401
+            Log.d("listParts", "lastModified: " + result.getParts().get(i).getLastModified());
402
+            Log.d("listParts", "partSize: " + result.getParts().get(i).getSize());
403
+            listPartsData.putInt("partNum" + i, result.getParts().get(i).getPartNumber());
404
+            listPartsData.putString("partEtag"+i,result.getParts().get(i).getETag());
405
+//          listPartsData.("lastModified" + i,result.getParts().get(i).getLastModified());
406
+            listPartsData.putDouble("partSize"+i,result.getParts().get(i).getSize());
407
+        }
408
+        promise.resolve(listPartsData);
409
+    }
410
+}

+ 30
- 0
android/src/main/java/com/reactlibrary/PromiseExceptionManager.java View File

@@ -0,0 +1,30 @@
1
+package com.reactlibrary;
2
+
3
+import android.util.Log;
4
+
5
+import com.alibaba.sdk.android.oss.ClientException;
6
+import com.alibaba.sdk.android.oss.ServiceException;
7
+import com.facebook.react.bridge.Promise;
8
+
9
+public class PromiseExceptionManager {
10
+
11
+    /**
12
+     * resolvePromiseException
13
+     * @param clientExcepion
14
+     * @param serviceException
15
+     * @param promise
16
+     */
17
+    public static void resolvePromiseException(ClientException clientExcepion, ServiceException serviceException, final Promise promise) {
18
+        if (clientExcepion != null) {
19
+            clientExcepion.printStackTrace();
20
+            promise.reject(clientExcepion);
21
+        }
22
+        if (serviceException != null) {
23
+            Log.e("ErrorCode", serviceException.getErrorCode());
24
+            Log.e("RequestId", serviceException.getRequestId());
25
+            Log.e("HostId", serviceException.getHostId());
26
+            Log.e("RawMessage", serviceException.getRawMessage());
27
+            promise.reject(serviceException);
28
+        }
29
+    }
30
+}

+ 375
- 0
android/src/main/java/com/reactlibrary/RNAliyunOssModule.java View File

@@ -0,0 +1,375 @@
1
+
2
+package com.reactlibrary;
3
+
4
+import android.annotation.SuppressLint;
5
+import android.database.Cursor;
6
+import android.net.Uri;
7
+import android.os.Environment;
8
+import android.provider.MediaStore;
9
+import android.util.Log;
10
+
11
+import com.alibaba.sdk.android.oss.ClientConfiguration;
12
+import com.alibaba.sdk.android.oss.ClientException;
13
+import com.alibaba.sdk.android.oss.OSS;
14
+import com.alibaba.sdk.android.oss.OSSClient;
15
+import com.alibaba.sdk.android.oss.ServiceException;
16
+import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
17
+import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
18
+import com.alibaba.sdk.android.oss.common.OSSConstants;
19
+import com.alibaba.sdk.android.oss.common.OSSLog;
20
+import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
21
+import com.alibaba.sdk.android.oss.common.auth.OSSCustomSignerCredentialProvider;
22
+import com.alibaba.sdk.android.oss.common.auth.OSSFederationCredentialProvider;
23
+import com.alibaba.sdk.android.oss.common.auth.OSSFederationToken;
24
+import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
25
+import com.alibaba.sdk.android.oss.common.utils.IOUtils;
26
+import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
27
+import com.alibaba.sdk.android.oss.model.AbortMultipartUploadRequest;
28
+import com.alibaba.sdk.android.oss.model.AppendObjectRequest;
29
+import com.alibaba.sdk.android.oss.model.AppendObjectResult;
30
+import com.alibaba.sdk.android.oss.model.CompleteMultipartUploadRequest;
31
+import com.alibaba.sdk.android.oss.model.CompleteMultipartUploadResult;
32
+import com.alibaba.sdk.android.oss.model.CopyObjectRequest;
33
+import com.alibaba.sdk.android.oss.model.CopyObjectResult;
34
+import com.alibaba.sdk.android.oss.model.DeleteBucketRequest;
35
+import com.alibaba.sdk.android.oss.model.DeleteBucketResult;
36
+import com.alibaba.sdk.android.oss.model.DeleteObjectRequest;
37
+import com.alibaba.sdk.android.oss.model.DeleteObjectResult;
38
+import com.alibaba.sdk.android.oss.model.GetObjectRequest;
39
+import com.alibaba.sdk.android.oss.model.GetObjectResult;
40
+import com.alibaba.sdk.android.oss.model.HeadObjectRequest;
41
+import com.alibaba.sdk.android.oss.model.HeadObjectResult;
42
+import com.alibaba.sdk.android.oss.model.InitiateMultipartUploadRequest;
43
+import com.alibaba.sdk.android.oss.model.InitiateMultipartUploadResult;
44
+import com.alibaba.sdk.android.oss.model.ListBucketsRequest;
45
+import com.alibaba.sdk.android.oss.model.ListBucketsResult;
46
+import com.alibaba.sdk.android.oss.model.ListObjectsRequest;
47
+import com.alibaba.sdk.android.oss.model.ListObjectsResult;
48
+import com.alibaba.sdk.android.oss.model.ListPartsRequest;
49
+import com.alibaba.sdk.android.oss.model.ListPartsResult;
50
+import com.alibaba.sdk.android.oss.model.ObjectMetadata;
51
+import com.alibaba.sdk.android.oss.model.PartETag;
52
+import com.alibaba.sdk.android.oss.model.PutObjectRequest;
53
+import com.alibaba.sdk.android.oss.model.PutObjectResult;
54
+import com.alibaba.sdk.android.oss.model.ResumableUploadRequest;
55
+import com.alibaba.sdk.android.oss.model.ResumableUploadResult;
56
+import com.alibaba.sdk.android.oss.model.UploadPartRequest;
57
+import com.alibaba.sdk.android.oss.model.UploadPartResult;
58
+import com.facebook.react.bridge.Arguments;
59
+import com.facebook.react.bridge.Promise;
60
+import com.facebook.react.bridge.ReactApplicationContext;
61
+import com.facebook.react.bridge.ReactContext;
62
+import com.facebook.react.bridge.ReactContextBaseJavaModule;
63
+import com.facebook.react.bridge.ReactMethod;
64
+import com.facebook.react.bridge.ReadableMap;
65
+import com.facebook.react.bridge.WritableMap;
66
+import com.facebook.react.modules.core.DeviceEventManagerModule;
67
+import com.reactlibrary.utils.FileUtils;
68
+
69
+import org.json.JSONObject;
70
+
71
+import java.io.File;
72
+import java.io.FileInputStream;
73
+import java.io.FileNotFoundException;
74
+import java.io.FileOutputStream;
75
+import java.io.IOException;
76
+import java.io.InputStream;
77
+import java.net.HttpURLConnection;
78
+import java.net.URL;
79
+import java.util.ArrayList;
80
+import java.util.HashMap;
81
+import java.util.List;
82
+
83
+public class RNAliyunOssModule extends ReactContextBaseJavaModule {
84
+
85
+    private OSS mOSS;
86
+    private AliyunBucketManager mBucketManager;
87
+    private AliyunObjectManager mObjectManager;
88
+    private AliyunUploadManager mUploadManager;
89
+    private AliyunDownloadManager mDownloadManager;
90
+    private AliyunAuthManager mAuth;
91
+
92
+    /**
93
+     * RNAliyunOssModule constructor
94
+     * @param reactContext
95
+     */
96
+    public RNAliyunOssModule(ReactApplicationContext reactContext) {
97
+        super(reactContext);
98
+        mAuth = new AliyunAuthManager(reactContext.getApplicationContext(), new AliyunAuthManager.AuthListener() {
99
+            @Override
100
+            public void onAuthFinished(OSS oss) {
101
+                init(oss);
102
+            }
103
+        });
104
+    }
105
+
106
+    @Override
107
+    public String getName() {
108
+        return "RNAliyunOSS";
109
+    }
110
+
111
+    /**
112
+     * enable dev log
113
+     */
114
+    @ReactMethod
115
+    public void enableDevMode() {
116
+        OSSLog.enableLog();
117
+    }
118
+
119
+    /**
120
+     * init oss ReactMethod
121
+     * @param oss
122
+     */
123
+    private void init(OSS oss) {
124
+        mOSS = oss;
125
+        mBucketManager = new AliyunBucketManager(mOSS);
126
+        mObjectManager = new AliyunObjectManager(mOSS);
127
+        mUploadManager = new AliyunUploadManager(mOSS);
128
+        mDownloadManager = new AliyunDownloadManager(mOSS);
129
+    }
130
+
131
+    /**
132
+     * initWithSigner ReactMethod
133
+     * @param signature
134
+     * @param accessKey
135
+     * @param endPoint
136
+     * @param configuration
137
+     */
138
+    @ReactMethod
139
+    public void initWithSigner(final String signature, final String accessKey, String endPoint, ReadableMap configuration) {
140
+        mAuth.initWithSigner(signature, accessKey, endPoint, configuration);
141
+    }
142
+
143
+    /**
144
+     * initWithPlainTextAccessKey ReactMethod
145
+     * @param accessKeyId
146
+     * @param accessKeySecret
147
+     * @param endPoint
148
+     * @param configuration
149
+     */
150
+    @ReactMethod
151
+    public void initWithPlainTextAccessKey(String accessKeyId, String accessKeySecret, String endPoint, ReadableMap configuration) {
152
+        mAuth.initWithPlainTextAccessKey(accessKeyId, accessKeySecret, endPoint, configuration);
153
+    }
154
+
155
+    /**
156
+     * initWithSecurityToken ReactMethod
157
+     * @param securityToken
158
+     * @param accessKeyId
159
+     * @param accessKeySecret
160
+     * @param endPoint
161
+     * @param configuration
162
+     */
163
+    @ReactMethod
164
+    public void initWithSecurityToken(String securityToken, String accessKeyId, String accessKeySecret, String endPoint, ReadableMap configuration) {
165
+        mAuth.initWithSecurityToken(securityToken, accessKeyId, accessKeySecret, endPoint, configuration);
166
+    }
167
+
168
+    /**
169
+     * initWithServerSTS ReactMethod
170
+     * @param server
171
+     * @param endPoint
172
+     * @param configuration
173
+     */
174
+    @ReactMethod
175
+    public void initWithServerSTS(final String server, String endPoint, ReadableMap configuration) {
176
+        mAuth.initWithServerSTS(server, endPoint, configuration);
177
+    }
178
+
179
+    /**
180
+     * async Upload ReactMethod
181
+     * @param bucketName
182
+     * @param ossFile
183
+     * @param sourceFile
184
+     * @param promise
185
+     */
186
+    @ReactMethod
187
+    public void asyncUpload(String bucketName, String ossFile, String sourceFile,ReadableMap options, final Promise promise) {
188
+        mUploadManager.asyncUpload(getReactApplicationContext(), bucketName, ossFile, sourceFile, options, promise);
189
+    }
190
+
191
+    /**
192
+     * asyncAppendObject ReactMethod
193
+     * @param bucketName
194
+     * @param objectKey
195
+     * @param uploadFilePath
196
+     * @param options
197
+     * @param promise
198
+     */
199
+    @ReactMethod
200
+    public void asyncAppendObject(String bucketName,String objectKey,String uploadFilePath,ReadableMap options,final Promise promise) {
201
+        mUploadManager.asyncAppendObject(getReactApplicationContext(),bucketName, objectKey, uploadFilePath, options, promise);
202
+    }
203
+
204
+    /**
205
+     * asyncResumableUpload ReactMethod
206
+     * @param bucketName
207
+     * @param objectKey
208
+     * @param uploadFilePath
209
+     * @param options
210
+     * @param promise
211
+     */
212
+    @ReactMethod
213
+    public void asyncResumableUpload(String bucketName,String objectKey,String uploadFilePath,ReadableMap options,final Promise promise) {
214
+        mUploadManager.asyncResumableUpload(getReactApplicationContext(), bucketName, objectKey, uploadFilePath, options, promise);
215
+    }
216
+
217
+    /**
218
+     * initMultipartUpload ReactMethod
219
+     * @param bucketName
220
+     * @param objectKey
221
+     * @param promise
222
+     */
223
+    @ReactMethod
224
+    public void initMultipartUpload(String bucketName,String objectKey,final Promise promise) {
225
+        mUploadManager.initMultipartUpload(bucketName, objectKey, promise);
226
+    }
227
+
228
+    /**
229
+     * multipartUpload ReactMethod
230
+     * @param bucketName
231
+     * @param objectKey
232
+     * @param filepath
233
+     * @param options
234
+     * @param promise
235
+     */
236
+//    @SuppressLint("LongLogTag")
237
+    @ReactMethod
238
+    public void multipartUpload(String bucketName, String objectKey, String uploadId, String filepath, ReadableMap options,final Promise promise) {
239
+        mUploadManager.multipartUpload(getReactApplicationContext(), bucketName, objectKey, uploadId, filepath, options, promise);
240
+    }
241
+
242
+    /**
243
+     * AbortMultipartUploadRequest ReactMethod
244
+     * @param bucketName
245
+     * @param objectKey
246
+     * @param uploadId
247
+     */
248
+    @ReactMethod
249
+    public void abortMultipartUpload(String bucketName,String objectKey,String uploadId,final Promise promise) {
250
+        mUploadManager.abortMultipartUpload(bucketName, objectKey, uploadId, promise);
251
+    }
252
+
253
+    /**
254
+     * listParts ReactMethod
255
+     * @param bucketName
256
+     * @param objectKey
257
+     * @param uploadId
258
+     * @param promise
259
+     */
260
+    @ReactMethod
261
+    public void listParts (String bucketName,String objectKey,String uploadId,final Promise promise) {
262
+        mUploadManager.listParts(bucketName, objectKey, uploadId, promise);
263
+    }
264
+
265
+    /**
266
+     * asyncDownload and image process ReactMethod
267
+     * @param bucketName
268
+     * @param ossFile
269
+     * @param updateDate
270
+     * @param options
271
+     * @param promise
272
+     */
273
+    @ReactMethod
274
+    public void asyncDownload(String bucketName, String ossFile, String updateDate,ReadableMap options, final Promise promise) {
275
+        mDownloadManager.asyncDownload(getReactApplicationContext(), bucketName, ossFile, updateDate, options, promise);
276
+    }
277
+    /**
278
+     * createBucket ReactMethod
279
+     * @param bucketName
280
+     * @param acl
281
+     * @param region
282
+     * @param promise
283
+     */
284
+    @ReactMethod
285
+    public void asyncCreateBucket (String bucketName,String acl,String region,final Promise promise) {
286
+        mBucketManager.asyncCreateBucket(bucketName, acl, region, promise);
287
+    }
288
+
289
+    /**
290
+     * async getBucketName ReactMethod
291
+     * @param bucketName
292
+     * @param promise
293
+     */
294
+    @ReactMethod
295
+    public void asyncGetBucketACL (String bucketName,final Promise promise) {
296
+        mBucketManager.asyncGetBucketACL(bucketName,promise);
297
+    }
298
+
299
+    /**
300
+     * list buckets ReactMethod
301
+     * @param promise
302
+     */
303
+    @ReactMethod
304
+    public void asyncListBuckets(final Promise promise) {
305
+        mBucketManager.asyncListBuckets(promise);
306
+    }
307
+    /**
308
+     * async delet bucket ReactMethod
309
+     * @param bucketName
310
+     * @param promise
311
+     */
312
+    @ReactMethod
313
+    public void asyncDeleteBucket(String bucketName,final Promise promise) {
314
+        mBucketManager.asyncDeleteBucket(bucketName,promise);
315
+    }
316
+
317
+    /**
318
+     * asyncHeadObject ReactMethod
319
+     * @param bucketName
320
+     * @param objectKey
321
+     * @param promise
322
+     */
323
+    @ReactMethod
324
+    public void asyncHeadObject(String bucketName,String objectKey,final Promise promise) {
325
+       mObjectManager.asyncHeadObject(bucketName,objectKey,promise);
326
+    }
327
+
328
+    /**
329
+     * asyncListObjects ReactMethod
330
+     * @param bucketName
331
+     * @param prefix
332
+     * @param promise
333
+     */
334
+    @ReactMethod
335
+    public void asyncListObjects(String bucketName,String prefix,final Promise promise) {
336
+        mObjectManager.asyncListObjects(bucketName, prefix, promise);
337
+    }
338
+
339
+    /**
340
+     * copy objects ReactMethod
341
+     * @param srcBucketName
342
+     * @param srcObjectKey
343
+     * @param desBucketName
344
+     * @param destObjectKey
345
+     * @param options set object metadata
346
+     * @param promise
347
+     */
348
+
349
+    @ReactMethod
350
+    public void asyncCopyObject (String srcBucketName,String srcObjectKey, String desBucketName, String destObjectKey,ReadableMap options ,final Promise promise ) {
351
+        mObjectManager.asyncCopyObject(srcBucketName,srcObjectKey,desBucketName,destObjectKey,options,promise);
352
+    }
353
+
354
+    /**
355
+     * does object exist ReactMethod
356
+     * @param bucketName
357
+     * @param objectKey
358
+     * @param promise
359
+     */
360
+    @ReactMethod
361
+    public void doesObjectExist(String bucketName,String objectKey,final Promise promise) {
362
+        mObjectManager.doesObjectExist(bucketName,objectKey,promise);
363
+    }
364
+
365
+    /**
366
+     * asyncDeleteObject ReactMethod
367
+     * @param bucketName
368
+     * @param objectKey
369
+     * @param promise
370
+     */
371
+    @ReactMethod
372
+    public void asyncDeleteObject(String bucketName, String objectKey,final Promise promise) {
373
+        mObjectManager.asyncDeleteObject(bucketName, objectKey, promise);
374
+    }
375
+}

+ 27
- 0
android/src/main/java/com/reactlibrary/RNAliyunOssPackage.java View File

@@ -0,0 +1,27 @@
1
+
2
+package com.reactlibrary;
3
+
4
+import java.util.Arrays;
5
+import java.util.Collections;
6
+import java.util.List;
7
+
8
+import com.facebook.react.ReactPackage;
9
+import com.facebook.react.bridge.NativeModule;
10
+import com.facebook.react.bridge.ReactApplicationContext;
11
+import com.facebook.react.uimanager.ViewManager;
12
+import com.facebook.react.bridge.JavaScriptModule;
13
+public class RNAliyunOssPackage implements ReactPackage {
14
+    @Override
15
+    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
16
+      return Arrays.<NativeModule>asList(new RNAliyunOssModule(reactContext));
17
+    }
18
+
19
+    public List<Class<? extends JavaScriptModule>> createJSModules() {
20
+      return Collections.emptyList();
21
+    }
22
+
23
+    @Override
24
+    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
25
+      return Collections.emptyList();
26
+    }
27
+}

+ 21
- 0
android/src/main/java/com/reactlibrary/utils/ConfigUtils.java View File

@@ -0,0 +1,21 @@
1
+package com.reactlibrary.utils;
2
+
3
+import com.alibaba.sdk.android.oss.ClientConfiguration;
4
+import com.facebook.react.bridge.ReadableMap;
5
+
6
+public class ConfigUtils {
7
+
8
+    /**
9
+     * Auth initAuthConfig
10
+     * @param configuration
11
+     * @return
12
+     */
13
+    public static ClientConfiguration initAuthConfig(ReadableMap configuration) {
14
+       ClientConfiguration conf = new ClientConfiguration();
15
+       conf.setConnectionTimeout(configuration.getInt("timeoutIntervalForRequest") * 1000);
16
+       conf.setSocketTimeout(configuration.getInt("timeoutIntervalForRequest") * 1000);
17
+       conf.setMaxConcurrentRequest(configuration.getInt("maxRetryCount"));
18
+       conf.setMaxErrorRetry(configuration.getInt("maxRetryCount"));
19
+       return conf;
20
+   }
21
+}

+ 76
- 0
android/src/main/java/com/reactlibrary/utils/FileUtils.java View File

@@ -0,0 +1,76 @@
1
+package com.reactlibrary.utils;
2
+
3
+import android.content.Context;
4
+import android.net.Uri;
5
+import android.os.Environment;
6
+import android.text.TextUtils;
7
+
8
+import java.io.File;
9
+import java.io.FileOutputStream;
10
+import java.io.IOException;
11
+import java.io.InputStream;
12
+import java.io.OutputStream;
13
+
14
+public class FileUtils {
15
+
16
+    /**
17
+     * copy file
18
+     * @param context
19
+     * @param srcUri
20
+     * @param dstFile
21
+     */
22
+    public static void copy(Context context, Uri srcUri, File dstFile) {
23
+        try {
24
+            InputStream is = context.getContentResolver().openInputStream(srcUri);
25
+            if (is == null) return;
26
+            OutputStream fos = new FileOutputStream(dstFile);
27
+            int ch = 0;
28
+            try {
29
+                while((ch=is.read()) != -1){
30
+                    fos.write(ch);
31
+                }
32
+            } catch (IOException e1) {
33
+                e1.printStackTrace();
34
+            } finally{
35
+                // close inputstream
36
+                fos.close();
37
+                is.close();
38
+            }
39
+        } catch (IOException e) {
40
+            e.printStackTrace();
41
+        }
42
+    }
43
+
44
+    /**
45
+     * getFileName
46
+     * @param uri
47
+     * @return
48
+     */
49
+    public static String getFileName(Uri uri) {
50
+        if (uri == null) return null;
51
+        String fileName = null;
52
+        String path = uri.getPath();
53
+        int cut = path.lastIndexOf('/');
54
+        if (cut != -1) {
55
+            fileName = path.substring(cut + 1);
56
+        }
57
+        return fileName;
58
+    }
59
+
60
+    /**
61
+     * getFilePathFromURI
62
+     * @param context
63
+     * @param contentUri
64
+     * @return
65
+     */
66
+    public static String getFilePathFromURI(Context context, Uri contentUri) {
67
+        //copy file and send new file path
68
+        String fileName = getFileName(contentUri);
69
+        if (!TextUtils.isEmpty(fileName)) {
70
+            File copyFile = new File( Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + fileName);
71
+            FileUtils.copy(context, contentUri, copyFile);
72
+            return copyFile.getAbsolutePath();
73
+        }
74
+        return null;
75
+    }
76
+}

+ 244
- 0
index.js View File

@@ -0,0 +1,244 @@
1
+import {DeviceEventEmitter, NativeEventEmitter, NativeModules, Platform} from "react-native";
2
+const {RNAliyunOSS} = NativeModules;
3
+
4
+let subscription;
5
+
6
+//default configuration for OSS Client
7
+const conf = {
8
+    maxRetryCount: 3,
9
+    timeoutIntervalForRequest: 30,
10
+    timeoutIntervalForResource: 24 * 60 * 60
11
+};
12
+
13
+const imageXOssProcess = {
14
+    "x-oss-process":''
15
+}
16
+
17
+let partSize = 128 * 1024
18
+const mulitpartUploadConfig = {
19
+    "partSize":partSize
20
+}
21
+
22
+//appendObject
23
+const appendOptions = {
24
+    "appendPosition":0,
25
+    "contentType":'',
26
+    "contentMd5":'',
27
+    "contentEncoding":'',
28
+    "contentDisposition":''
29
+}
30
+
31
+export default AliyunOSS = {
32
+
33
+    //Enable dev mode
34
+    enableDevMode() {
35
+        RNAliyunOSS.enableDevMode();
36
+    },
37
+    
38
+    /**
39
+     * Initialize the OSS Client
40
+     * Mode: PlainTextAKSK
41
+     */
42
+    initWithPlainTextAccessKey(accessKey, secretKey, endPoint, configuration = conf) {
43
+        RNAliyunOSS.initWithPlainTextAccessKey(accessKey, secretKey, endPoint, configuration);
44
+    },
45
+
46
+    /**
47
+     * Initialize the OSS Client
48
+     * Mode: ImplementedSigner
49
+     */
50
+    initWithImplementedSigner(signature, accessKey, endPoint, configuration = conf) {
51
+        RNAliyunOSS.initWithImplementedSigner(signature, accessKey, endPoint, configuration);
52
+    },
53
+
54
+    /**
55
+     * Initialize the OSS Client
56
+     * Mode: SecurityToken (STS)
57
+     */
58
+    initWithSecurityToken(securityToken, accessKey, secretKey, endPoint, configuration = conf) {
59
+        RNAliyunOSS.initWithSecurityToken(securityToken, accessKey, secretKey, endPoint, configuration);
60
+    },
61
+
62
+    /**
63
+     * Initialize the OSS Client
64
+     * Server STS
65
+     */
66
+    initWithServerSTS(server, endPoint, configuration = conf) {
67
+        RNAliyunOSS.initWithServerSTS(server, endPoint, configuration);
68
+    },    
69
+
70
+    /**
71
+     * Asynchronously uploading
72
+     */
73
+    asyncUpload(bucketName, objectKey, filepath,options) {
74
+        return RNAliyunOSS.asyncUpload(bucketName, objectKey, filepath,options);
75
+    },
76
+
77
+     /**
78
+     * Asynchronously 
79
+     */
80
+    asyncResumableUpload(bucketName, objectKey, filepath='',options={}) {
81
+        return RNAliyunOSS.asyncResumableUpload(bucketName, objectKey, filepath,options);
82
+    },
83
+
84
+     /**
85
+     * Asynchronously asyncAppendObject
86
+     */
87
+    asyncAppendObject(bucketName,objectKey,filepath,options = appendOptions) {
88
+        return RNAliyunOSS.asyncAppendObject(bucketName, objectKey, filepath,options);
89
+    },
90
+
91
+    /**
92
+     * Asynchronously 
93
+     */
94
+    initMultipartUpload(bucketName,objectKey) {
95
+        return RNAliyunOSS.initMultipartUpload(bucketName, objectKey);
96
+    },
97
+
98
+    /**
99
+     * Asynchronously multipartUpload
100
+     */
101
+    multipartUpload(bucketName,objectKey,uploadId,filepath ='',options = mulitpartUploadConfig) {
102
+        return RNAliyunOSS.multipartUpload(bucketName, objectKey, uploadId,filepath, options);
103
+    },
104
+
105
+     /**
106
+     * Asynchronously listParts
107
+     */
108
+    listParts (bucketName,objectKey,uploadId) {
109
+        return RNAliyunOSS.listParts(bucketName, objectKey, uploadId)
110
+    },
111
+     /**
112
+     * Asynchronously abortMultipartUpload
113
+     */
114
+    abortMultipartUpload(bucketName,objectKey,uploadId) {
115
+        return RNAliyunOSS.abortMultipartUpload(bucketName, objectKey, uploadId);
116
+    },
117
+
118
+    /**
119
+     * Asynchronously downloading
120
+     */
121
+    asyncDownload(bucketName, objectKey, filepath='',options = imageXOssProcess) {
122
+        return RNAliyunOSS.asyncDownload(bucketName, objectKey, filepath,options);
123
+    },
124
+    
125
+    /*
126
+    asyncListBuckets
127
+    */
128
+
129
+    asyncListBuckets () {
130
+        return RNAliyunOSS.asyncListBuckets()
131
+    },
132
+
133
+     /**
134
+     * Asynchronously getHeadObject
135
+     */
136
+
137
+    asyncHeadObject (bucketName, objectKey) {
138
+        return RNAliyunOSS.asyncHeadObject(bucketName,objectKey)
139
+    }, 
140
+
141
+    
142
+    /**
143
+     * Asynchronously getAsyncObjects
144
+     */
145
+
146
+    asyncListObjects (bucketName,prefix='') {
147
+        return RNAliyunOSS.asyncListObjects(bucketName,prefix,)
148
+    },
149
+
150
+
151
+    /**
152
+     * Asynchronously asyncCopyObject
153
+     */
154
+
155
+    asyncCopyObject (srcBucketName, srcObjectKey, desBucketName,destObjectKey, options) {
156
+        return RNAliyunOSS.asyncCopyObject (srcBucketName, srcObjectKey, desBucketName,destObjectKey, options)
157
+    },
158
+
159
+    /**
160
+     * Asynchronously doesObjectExist
161
+     */
162
+
163
+     doesObjectExist (bucketName, objectKey) {
164
+        return RNAliyunOSS.doesObjectExist(bucketName, objectKey)
165
+     },
166
+
167
+     /**
168
+     * Asynchronously asyncDeleteObject
169
+     */
170
+
171
+     asyncDeleteObject (bucketName, objectKey) {
172
+        return RNAliyunOSS.asyncDeleteObject(bucketName, objectKey)
173
+     },
174
+
175
+     /**
176
+     * Asynchronously createBucket
177
+     */
178
+    asyncCreateBucket (bucketName,acl="private",region) {
179
+        return RNAliyunOSS.asyncCreateBucket(bucketName,acl,region)
180
+    }, 
181
+
182
+    /**
183
+     * Asynchronously getBucketACL
184
+     */
185
+    asyncGetBucketACL (bucketName) {
186
+        return RNAliyunOSS.asyncGetBucketACL(bucketName)
187
+    },
188
+
189
+    /**
190
+     * Asynchronously getBucketACL
191
+     */
192
+    asyncGetBucketACL(bucketName) {
193
+        return RNAliyunOSS.asyncGetBucketACL(bucketName)
194
+    },
195
+
196
+    /**
197
+     * Asynchronously deleteBucket
198
+     */
199
+    asyncDeleteBucket (bucketName) {
200
+        return RNAliyunOSS.asyncDeleteBucket(bucketName)
201
+    },   
202
+
203
+    /**
204
+     * event listener for native upload/download event
205
+     * @param event one of 'uploadProgress' or 'downloadProgress'
206
+     * @param callback a callback function accepts one params: event
207
+     */
208
+    addEventListener(event, callback) {
209
+        const RNAliyunEmitter = Platform.OS === 'ios' ? new NativeEventEmitter(RNAliyunOSS) : DeviceEventEmitter;
210
+        switch (event) {
211
+            case 'uploadProgress':
212
+                subscription = RNAliyunEmitter.addListener(
213
+                    'uploadProgress',
214
+                    e => callback(e)
215
+                );
216
+                break;
217
+            case 'downloadProgress':
218
+                subscription = RNAliyunEmitter.addListener(
219
+                    'downloadProgress',
220
+                    e => callback(e)
221
+                );
222
+                break;
223
+            default:
224
+                break;
225
+        }
226
+    },
227
+
228
+    /**
229
+     * remove event listener for native upload/download event
230
+     * @param event one of 'uploadProgress' or 'downloadProgress'
231
+     */
232
+    removeEventListener(event) {
233
+        switch (event) {
234
+            case 'uploadProgress':
235
+                subscription.remove();
236
+                break;
237
+            case 'downloadProgress':
238
+                subscription.remove();
239
+                break;
240
+            default:
241
+                break;
242
+        }
243
+    }
244
+};

BIN
ios/AliyunSDK/AliyunOSSiOS.framework/AliyunOSSiOS View File


+ 20
- 0
ios/AliyunSDK/AliyunOSSiOS.framework/Headers/AliyunOSSiOS.h View File

@@ -0,0 +1,20 @@
1
+//
2
+//  AliyunOSSiOS.h
3
+//  AliyunOSSiOS
4
+//
5
+//  Created by xuyecan on 28/11/2016.
6
+//  Copyright © 2016 xuyecan. All rights reserved.
7
+//
8
+
9
+#import <UIKit/UIKit.h>
10
+
11
+//! Project version number for AliyunOSSiOS.
12
+FOUNDATION_EXPORT double AliyunOSSiOSVersionNumber;
13
+
14
+//! Project version string for AliyunOSSiOS.
15
+FOUNDATION_EXPORT const unsigned char AliyunOSSiOSVersionString[];
16
+
17
+// In this header, you should import all the public headers of your framework using statements like #import <AliyunOSSiOS/PublicHeader.h>
18
+
19
+#import "OSSService.h"
20
+#import "OSSCompat.h"

+ 26
- 0
ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSBolts.h View File

@@ -0,0 +1,26 @@
1
+/*
2
+ *  Copyright (c) 2014, 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
+
11
+#import "OSSCancellationToken.h"
12
+#import "OSSCancellationTokenRegistration.h"
13
+#import "OSSCancellationTokenSource.h"
14
+#import "OSSExecutor.h"
15
+#import "OSSTask.h"
16
+#import "OSSTaskCompletionSource.h"
17
+
18
+
19
+NS_ASSUME_NONNULL_BEGIN
20
+
21
+/**
22
+ A string containing the version of the Bolts Framework used by the current application.
23
+ */
24
+extern NSString *const OSSBoltsFrameworkVersionString;
25
+
26
+NS_ASSUME_NONNULL_END

+ 42
- 0
ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSCancellationToken.h View File

@@ -0,0 +1,42 @@
1
+/*
2
+ *  Copyright (c) 2014, 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
+
11
+#import <Foundation/Foundation.h>
12
+
13
+#import "OSSCancellationTokenRegistration.h"
14
+
15
+NS_ASSUME_NONNULL_BEGIN
16
+
17
+/*!
18
+ A block that will be called when a token is cancelled.
19
+ */
20
+typedef void(^OSSCancellationBlock)();
21
+
22
+/*!
23
+ The consumer view of a CancellationToken.
24
+ Propagates notification that operations should be canceled.
25
+ A OSSCancellationToken has methods to inspect whether the token has been cancelled.
26
+ */
27
+@interface OSSCancellationToken : NSObject
28
+
29
+/*!
30
+ Whether cancellation has been requested for this token source.
31
+ */
32
+@property (nonatomic, assign, readonly, getter=isCancellationRequested) BOOL cancellationRequested;
33
+
34
+/*!
35
+ Register a block to be notified when the token is cancelled.
36
+ If the token is already cancelled the delegate will be notified immediately.
37
+ */
38
+- (OSSCancellationTokenRegistration *)registerCancellationObserverWithBlock:(OSSCancellationBlock)block;
39
+
40
+@end
41
+
42
+NS_ASSUME_NONNULL_END

+ 29
- 0
ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSCancellationTokenRegistration.h View File

@@ -0,0 +1,29 @@
1
+/*
2
+ *  Copyright (c) 2014, 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
+
11
+#import <Foundation/Foundation.h>
12
+
13
+NS_ASSUME_NONNULL_BEGIN
14
+
15
+/*!
16
+ Represents the registration of a cancellation observer with a cancellation token.
17
+ Can be used to unregister the observer at a later time.
18
+ */
19
+@interface OSSCancellationTokenRegistration : NSObject
20
+
21
+/*!
22
+ Removes the cancellation observer registered with the token
23
+ and releases all resources associated with this registration.
24
+ */
25
+- (void)dispose;
26
+
27
+@end
28
+
29
+NS_ASSUME_NONNULL_END

+ 60
- 0
ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSCancellationTokenSource.h View File

@@ -0,0 +1,60 @@
1
+/*
2
+ *  Copyright (c) 2014, 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
+
11
+#import <Foundation/Foundation.h>
12
+
13
+NS_ASSUME_NONNULL_BEGIN
14
+
15
+@class OSSCancellationToken;
16
+
17
+/*!
18
+ OSSCancellationTokenSource represents the producer side of a CancellationToken.
19
+ Signals to a CancellationToken that it should be canceled.
20
+ It is a cancellation token that also has methods
21
+ for changing the state of a token by cancelling it.
22
+ */
23
+@interface OSSCancellationTokenSource : NSObject
24
+
25
+/*!
26
+ Creates a new cancellation token source.
27
+ */
28
++ (instancetype)cancellationTokenSource;
29
+
30
+/*!
31
+ The cancellation token associated with this CancellationTokenSource.
32
+ */
33
+@property (nonatomic, strong, readonly) OSSCancellationToken *token;
34
+
35
+/*!
36
+ Whether cancellation has been requested for this token source.
37
+ */
38
+@property (nonatomic, assign, readonly, getter=isCancellationRequested) BOOL cancellationRequested;
39
+
40
+/*!
41
+ Cancels the token if it has not already been cancelled.
42
+ */
43
+- (void)cancel;
44
+
45
+/*!
46
+ Schedules a cancel operation on this CancellationTokenSource after the specified number of milliseconds.
47
+ @param millis The number of milliseconds to wait before completing the returned task.
48
+ If delay is `0` the cancel is executed immediately. If delay is `-1` any scheduled cancellation is stopped.
49
+ */
50
+- (void)cancelAfterDelay:(int)millis;
51
+
52
+/*!
53
+ Releases all resources associated with this token source,
54
+ including disposing of all registrations.
55
+ */
56
+- (void)dispose;
57
+
58
+@end
59
+
60
+NS_ASSUME_NONNULL_END

+ 273
- 0
ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSClient.h View File

@@ -0,0 +1,273 @@
1
+//
2
+//  OSSClient.h
3
+//  oss_ios_sdk
4
+//
5
+//  Created by zhouzhuo on 8/16/15.
6
+//  Copyright (c) 2015 aliyun.com. All rights reserved.
7
+//
8
+
9
+#import <Foundation/Foundation.h>
10
+@class OSSGetServiceRequest;
11
+@class OSSCreateBucketRequest;
12
+@class OSSDeleteBucketRequest;
13
+@class OSSHeadObjectRequest;
14
+@class OSSGetBucketRequest;
15
+@class OSSGetBucketACLRequest;
16
+@class OSSGetObjectRequest;
17
+@class OSSPutObjectRequest;
18
+@class OSSPutObjectACLRequest;
19
+@class OSSDeleteObjectRequest;
20
+@class OSSCopyObjectRequest;
21
+@class OSSInitMultipartUploadRequest;
22
+@class OSSUploadPartRequest;
23
+@class OSSCompleteMultipartUploadRequest;
24
+@class OSSListPartsRequest;
25
+@class OSSAbortMultipartUploadRequest;
26
+@class OSSAppendObjectRequest;
27
+@class OSSResumableUploadRequest;
28
+@class OSSTask;
29
+@class OSSExecutor;
30
+
31
+@class OSSNetworking;
32
+@class OSSClientConfiguration;
33
+@protocol OSSCredentialProvider;
34
+
35
+NS_ASSUME_NONNULL_BEGIN
36
+
37
+/**
38
+ OSSClient是OSS服务的iOS客户端,它为调用者提供了一系列的方法,用于和OSS服务进行交互。
39
+ 一般来说,全局内只需要保持一个OSSClient,用来调用各种操作。
40
+ */
41
+@interface OSSClient : NSObject
42
+
43
+/**
44
+ OSS访问域名
45
+ */
46
+@property (nonatomic, strong) NSString * endpoint;
47
+
48
+/**
49
+ 用以收发网络请求
50
+ */
51
+@property (nonatomic, strong) OSSNetworking * networking;
52
+
53
+/**
54
+ 提供访问所需凭证
55
+ */
56
+@property (nonatomic, strong) id<OSSCredentialProvider> credentialProvider;
57
+
58
+/**
59
+ 客户端设置
60
+ */
61
+@property (nonatomic, strong) OSSClientConfiguration * clientConfiguration;
62
+
63
+/**
64
+ 任务队列
65
+ */
66
+@property (nonatomic, strong, readonly) OSSExecutor * ossOperationExecutor;
67
+
68
+/**
69
+ 初始化OSSClient,使用默认的本地设置
70
+ @endpoint 指明Bucket所在的Region域名,2017年以后苹果要求APP符合ATS政策,这里要写https的endpoint,如 "https://oss-cn-hangzhou.aliyuncs.com"
71
+ @credentialProvider 需要实现的签名器
72
+ */
73
+- (instancetype)initWithEndpoint:(NSString *)endpoint
74
+              credentialProvider:(id<OSSCredentialProvider>) credentialProvider;
75
+
76
+/**
77
+ 初始化OSSClient,使用自定义设置
78
+ @endpoint 指明Bucket所在的Region域名,2017年以后苹果要求APP符合ATS政策,这里要写https的endpoint,如 "https://oss-cn-hangzhou.aliyuncs.com"
79
+ @credentialProvider 需要实现的签名器
80
+ @conf 可以设置一些本地参数如重试次数、超时时间等
81
+ */
82
+- (instancetype)initWithEndpoint:(NSString *)endpoint
83
+              credentialProvider:(id<OSSCredentialProvider>)credentialProvider
84
+             clientConfiguration:(OSSClientConfiguration *)conf;
85
+
86
+#pragma mark restful-api
87
+
88
+/**
89
+ 对应RESTFul API:GetService
90
+ 获取请求者当前拥有的全部Bucket。
91
+ 注意:
92
+ 1. 尚不支持STS;
93
+ 2. 当所有的bucket都返回时,返回的xml中不包含Prefix、Marker、MaxKeys、IsTruncated、NextMarker节点,如果还有部分结果未返回,则增加上述节点,其中NextMarker用于继续查询时给marker赋值。
94
+ */
95
+- (OSSTask *)getService:(OSSGetServiceRequest *)request;
96
+
97
+/**
98
+ 对应RESTFul API:PutBucket
99
+ 用于创建Bucket(不支持匿名访问)。默认情况下,创建的Bucket位于默认的数据中心:oss-cn-hangzhou。
100
+ 用户可以显式指定Bucket位于的数据中心,从而最优化延迟,最小化费用或者满足监管要求等。
101
+ 注意:
102
+ 1. 尚不支持STS。
103
+ */
104
+- (OSSTask *)createBucket:(OSSCreateBucketRequest *)request;
105
+
106
+/**
107
+ 对应RESTFul API:DeleteBucket
108
+ 用于删除某个Bucket。
109
+ */
110
+- (OSSTask *)deleteBucket:(OSSDeleteBucketRequest *)request;
111
+
112
+/**
113
+ 对应RESTFul API:GetBucket
114
+ 用来list Bucket中所有Object的信息,可以通过prefix,marker,delimiter和max-keys对list做限定,返回部分结果。
115
+ */
116
+- (OSSTask *)getBucket:(OSSGetBucketRequest *)request;
117
+
118
+/**
119
+ 对应RESTFul API:GetBucketACL
120
+ 用来获取某个Bucket的访问权限。
121
+ */
122
+- (OSSTask *)getBucketACL:(OSSGetBucketACLRequest *)request;
123
+
124
+/**
125
+ 对应RESTFul API:HeadObject
126
+ 只返回某个Object的meta信息,不返回文件内容。
127
+ */
128
+- (OSSTask *)headObject:(OSSHeadObjectRequest *)request;
129
+
130
+/**
131
+ 对应RESTFul API:GetObject
132
+ 用于获取某个Object,此操作要求用户对该Object有读权限。
133
+ */
134
+- (OSSTask *)getObject:(OSSGetObjectRequest *)request;
135
+
136
+/**
137
+ 对应RESTFul API:PutObject
138
+ 用于上传文件。
139
+ */
140
+- (OSSTask *)putObject:(OSSPutObjectRequest *)request;
141
+
142
+/**
143
+ Put Object ACL接口用于修改Object的访问权限。目前Object有三种访问权限:private, public-read, public-read-write。
144
+ Put Object ACL操作通过Put请求中的“x-oss-object-acl”头来设置,这个操作只有Bucket Owner有权限执行。如果操作成功,则返回200;否则返回相应的错误码和提示信息。
145
+ */
146
+- (OSSTask *)putObjectACL:(OSSPutObjectACLRequest *)request;
147
+
148
+/**
149
+ 对应RESTFul API:AppendObject
150
+ 以追加写的方式上传文件。通过Append Object操作创建的Object类型为Appendable Object,而通过Put Object上传的Object是Normal Object。
151
+ */
152
+- (OSSTask *)appendObject:(OSSAppendObjectRequest *)request;
153
+
154
+/**
155
+ 对应RESTFul API:copyObject
156
+ 拷贝一个在OSS上已经存在的object成另外一个object,可以发送一个PUT请求给OSS,并在PUT请求头中添加元素“x-oss-copy-source”来指定拷贝源。
157
+ OSS会自动判断出这是一个Copy操作,并直接在服务器端执行该操作。如果拷贝成功,则返回新的object信息给用户。
158
+ 该操作适用于拷贝小于1GB的文件。
159
+ */
160
+- (OSSTask *)copyObject:(OSSCopyObjectRequest *)request;
161
+
162
+/**
163
+ 对应RESTFul API:DeleteObject
164
+ 用于删除某个Object。
165
+ */
166
+- (OSSTask *)deleteObject:(OSSDeleteObjectRequest *)request;
167
+
168
+/**
169
+ 对应RESTFul API:InitiateMultipartUpload
170
+ 使用Multipart Upload模式传输数据前,必须先调用该接口来通知OSS初始化一个Multipart Upload事件。该接口会返回一个OSS服务器创建的全局唯一的Upload ID,用于标识本次Multipart Upload事件。
171
+ 用户可以根据这个ID来发起相关的操作,如中止Multipart Upload、查询Multipart Upload等。
172
+ */
173
+- (OSSTask *)multipartUploadInit:(OSSInitMultipartUploadRequest *)request;
174
+
175
+/**
176
+ 对应RESTFul API:UploadPart
177
+ 初始化一个Multipart Upload之后,可以根据指定的Object名和Upload ID来分块(Part)上传数据。
178
+ 每一个上传的Part都有一个标识它的号码(part number,范围是1~10,000)。
179
+ 对于同一个Upload ID,该号码不但唯一标识这一块数据,也标识了这块数据在整个文件内的相对位置。
180
+ 如果你用同一个part号码,上传了新的数据,那么OSS上已有的这个号码的Part数据将被覆盖。除了最后一块Part以外,其他的part最小为100KB;
181
+ 最后一块Part没有大小限制。
182
+ */
183
+- (OSSTask *)uploadPart:(OSSUploadPartRequest *)request;
184
+
185
+/**
186
+ 对应RESTFul API:CompleteMultipartUpload
187
+ 在将所有数据Part都上传完成后,必须调用Complete Multipart Upload API来完成整个文件的Multipart Upload。
188
+ 在执行该操作时,用户必须提供所有有效的数据Part的列表(包括part号码和ETAG);OSS收到用户提交的Part列表后,会逐一验证每个数据Part的有效性。
189
+ 当所有的数据Part验证通过后,OSS将把这些数据part组合成一个完整的Object。
190
+ */
191
+- (OSSTask *)completeMultipartUpload:(OSSCompleteMultipartUploadRequest *)request;
192
+
193
+/**
194
+ 对应RESTFul API:ListParts
195
+ 可以罗列出指定Upload ID所属的所有已经上传成功Part。
196
+ */
197
+- (OSSTask *)listParts:(OSSListPartsRequest *)request;
198
+
199
+/**
200
+ 对应RESTFul API:AbortMultipartUpload
201
+ 该接口可以根据用户提供的Upload ID中止其对应的Multipart Upload事件。
202
+ 当一个Multipart Upload事件被中止后,就不能再使用这个Upload ID做任何操作,已经上传的Part数据也会被删除。
203
+ */
204
+- (OSSTask *)abortMultipartUpload:(OSSAbortMultipartUploadRequest *)request;
205
+
206
+#pragma mark extention method
207
+
208
+/**
209
+ 对一个Object签名出一个URL,可以把该URL转给第三方实现授权访问。
210
+ @bucketName Object所在的Bucket名称
211
+ @objectKey Object名称
212
+ @interval 签名URL时,可以指定这个URL的有效时长是多久,单位是秒,比如说需要有效时长为1小时的URL,这里传入3600
213
+ */
214
+- (OSSTask *)presignConstrainURLWithBucketName:(NSString *)bucketName
215
+                                withObjectKey:(NSString *)objectKey
216
+                       withExpirationInterval:(NSTimeInterval)interval;
217
+
218
+/**
219
+ 对一个Object签名出一个URL,可以把该URL转给第三方实现授权访问。
220
+ @bucketName Object所在的Bucket名称
221
+ @objectKey Object名称
222
+ @interval 签名URL时,可以指定这个URL的有效时长是多久,单位是秒,比如说需要有效时长为1小时的URL,这里传入3600
223
+ @parameter 参数
224
+ */
225
+- (OSSTask *)presignConstrainURLWithBucketName:(NSString *)bucketName
226
+                                 withObjectKey:(NSString *)objectKey
227
+                        withExpirationInterval:(NSTimeInterval)interval
228
+                                withParameters:(NSDictionary *)parameters;
229
+
230
+/**
231
+ 如果Object的权限是公共读或者公共读写,调用这个接口对该Object签名出一个URL,可以把该URL转给第三方实现授权访问。
232
+ @bucketName Object所在的Bucket名称
233
+ @objectKey Object名称
234
+ */
235
+- (OSSTask *)presignPublicURLWithBucketName:(NSString *)bucketName
236
+                            withObjectKey:(NSString *)objectKey;
237
+
238
+/**
239
+ 如果Object的权限是公共读或者公共读写,调用这个接口对该Object签名出一个URL,可以把该URL转给第三方实现授权访问。
240
+ @bucketName Object所在的Bucket名称
241
+ @objectKey Object名称
242
+ @parameter 参数
243
+ */
244
+- (OSSTask *)presignPublicURLWithBucketName:(NSString *)bucketName
245
+                             withObjectKey:(NSString *)objectKey
246
+                             withParameters:(NSDictionary *)parameters;
247
+
248
+/**
249
+ 断点上传接口
250
+ 这个接口封装了分块上传的若干接口以实现断点上传,但是需要用户自行保存UploadId。
251
+ 对一个新文件,用户需要首先调用multipartUploadInit接口获得一个UploadId,然后调用此接口上传这个文件。
252
+ 如果上传失败,首先需要检查一下失败原因:
253
+     如果非不可恢复的失败,那么可以用同一个UploadId和同一文件继续调用这个接口续传
254
+     否则,需要重新获取UploadId,重新上传这个文件。
255
+ 详细参考demo。
256
+ */
257
+- (OSSTask *)resumableUpload:(OSSResumableUploadRequest *)request;
258
+
259
+/**
260
+ 查看某个Object是否存在
261
+ @bucketName Object所在的Bucket名称
262
+ @objectKey Object名称
263
+ 
264
+ return YES                     Object存在
265
+ return NO && *error = nil      Object不存在
266
+ return NO && *error != nil     发生错误
267
+ */
268
+- (BOOL)doesObjectExistInBucket:(NSString *)bucketName
269
+                      objectKey:(NSString *)objectKey
270
+                          error:(const NSError **)error;
271
+@end
272
+
273
+NS_ASSUME_NONNULL_END

+ 81
- 0
ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSCompat.h View File

@@ -0,0 +1,81 @@
1
+//
2
+//  OSSCompat.h
3
+//  oss_ios_sdk_new
4
+//
5
+//  Created by zhouzhuo on 9/10/15.
6
+//  Copyright (c) 2015 aliyun.com. All rights reserved.
7
+//
8
+
9
+#import <Foundation/Foundation.h>
10
+#import "OSSService.h"
11
+
12
+@class OSSCancellationTokenSource;
13
+
14
+typedef OSSCancellationTokenSource OSSTaskHandler;
15
+
16
+@interface OSSClient (Compat)
17
+
18
+/**
19
+ 兼容老版本用法的上传数据接口
20
+ 建议更换使用:putObject
21
+ */
22
+- (OSSTaskHandler *)uploadData:(NSData *)data
23
+               withContentType:(NSString *)contentType
24
+                withObjectMeta:(NSDictionary *)meta
25
+                  toBucketName:(NSString *)bucketName
26
+                   toObjectKey:(NSString *)objectKey
27
+                   onCompleted:(void(^)(BOOL, NSError *))onCompleted
28
+                    onProgress:(void(^)(float progress))onProgress;
29
+
30
+/**
31
+ 兼容老版本用法的下载数据接口
32
+ 建议更换使用:getObject
33
+ */
34
+- (OSSTaskHandler *)downloadToDataFromBucket:(NSString *)bucketName
35
+                   objectKey:(NSString *)objectKey
36
+                 onCompleted:(void(^)(NSData *, NSError *))onCompleted
37
+                  onProgress:(void(^)(float progress))onProgress;
38
+
39
+/**
40
+ 兼容老版本用法的上传文件接口
41
+ 建议更换使用:putObject
42
+ */
43
+- (OSSTaskHandler *)uploadFile:(NSString *)filePath
44
+                withContentType:(NSString *)contentType
45
+                 withObjectMeta:(NSDictionary *)meta
46
+                   toBucketName:(NSString *)bucketName
47
+                    toObjectKey:(NSString *)objectKey
48
+                    onCompleted:(void(^)(BOOL, NSError *))onCompleted
49
+                     onProgress:(void(^)(float progress))onProgress;
50
+
51
+/**
52
+ 兼容老版本用法的下载文件接口
53
+ 建议更换使用:getObject
54
+ */
55
+- (OSSTaskHandler *)downloadToFileFromBucket:(NSString *)bucketName
56
+                  objectKey:(NSString *)objectKey
57
+                     toFile:(NSString *)filePath
58
+                onCompleted:(void(^)(BOOL, NSError *))onCompleted
59
+                 onProgress:(void(^)(float progress))onProgress;
60
+
61
+
62
+/**
63
+ 兼容老版本用法的断点上传文件接口
64
+ 建议更换使用:resumableUpload
65
+ */
66
+- (OSSTaskHandler *)resumableUploadFile:(NSString *)filePath
67
+          withContentType:(NSString *)contentType
68
+           withObjectMeta:(NSDictionary *)meta
69
+             toBucketName:(NSString *)bucketName
70
+              toObjectKey:(NSString *)objectKey
71
+              onCompleted:(void(^)(BOOL, NSError *))onCompleted
72
+               onProgress:(void(^)(float progress))onProgress;
73
+
74
+/**
75
+ 兼容老版本用法的删除Object接口
76
+ 建议更换使用:deleteObject
77
+ */
78
+- (void)deleteObjectInBucket:(NSString *)bucketName
79
+                   objectKey:(NSString *)objectKey
80
+                 onCompleted:(void(^)(BOOL, NSError *))onCompleted;
81
+@end

+ 67
- 0
ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSDefine.h View File

@@ -0,0 +1,67 @@
1
+//
2
+//  OSSDefine.h
3
+//  AliyunOSSiOS
4
+//
5
+//  Created by zhouzhuo on 5/1/16.
6
+//  Copyright © 2016 zhouzhuo. All rights reserved.
7
+//
8
+
9
+#import <Foundation/Foundation.h>
10
+
11
+#ifndef OSSDefine_h
12
+#define OSSDefine_h
13
+
14
+#define OSSUAPrefix                             @"aliyun-sdk-ios"
15
+#define OSSSDKVersion                           @"2.6.1"
16
+
17
+#define OSSListBucketResultXMLTOKEN             @"ListBucketResult"
18
+#define OSSNameXMLTOKEN                         @"Name"
19
+#define OSSDelimiterXMLTOKEN                    @"Delimiter"
20
+#define OSSMarkerXMLTOKEN                       @"Marker"
21
+#define OSSNextMarkerXMLTOKEN                   @"NextMarker"
22
+#define OSSMaxKeysXMLTOKEN                      @"MaxKeys"
23
+#define OSSIsTruncatedXMLTOKEN                  @"IsTruncated"
24
+#define OSSContentsXMLTOKEN                     @"Contents"
25
+#define OSSKeyXMLTOKEN                          @"Key"
26
+#define OSSLastModifiedXMLTOKEN                 @"LastModified"
27
+#define OSSETagXMLTOKEN                         @"ETag"
28
+#define OSSTypeXMLTOKEN                         @"Type"
29
+#define OSSSizeXMLTOKEN                         @"Size"
30
+#define OSSStorageClassXMLTOKEN                 @"StorageClass"
31
+#define OSSCommonPrefixesXMLTOKEN               @"CommonPrefixes"
32
+#define OSSOwnerXMLTOKEN                        @"Owner"
33
+#define OSSAccessControlListXMLTOKEN            @"AccessControlList"
34
+#define OSSGrantXMLTOKEN                        @"Grant"
35
+#define OSSIDXMLTOKEN                           @"ID"
36
+#define OSSDisplayNameXMLTOKEN                  @"DisplayName"
37
+#define OSSBucketsXMLTOKEN                      @"Buckets"
38
+#define OSSBucketXMLTOKEN                       @"Bucket"
39
+#define OSSCreationDate                         @"CreationDate"
40
+#define OSSPrefixXMLTOKEN                       @"Prefix"
41
+#define OSSUploadIdXMLTOKEN                     @"UploadId"
42
+#define OSSLocationXMLTOKEN                     @"Location"
43
+#define OSSNextPartNumberMarkerXMLTOKEN         @"NextPartNumberMarker"
44
+#define OSSMaxPartsXMLTOKEN                     @"MaxParts"
45
+#define OSSPartXMLTOKEN                         @"Part"
46
+#define OSSPartNumberXMLTOKEN                   @"PartNumber"
47
+
48
+#define OSSClientErrorDomain                    @"com.aliyun.oss.clientError"
49
+#define OSSServerErrorDomain                    @"com.aliyun.oss.serverError"
50
+
51
+#define OSSErrorMessageTOKEN                    @"ErrorMessage"
52
+
53
+#define OSSHttpHeaderContentDisposition         @"Content-Disposition"
54
+#define OSSHttpHeaderXOSSCallback               @"x-oss-callback"
55
+#define OSSHttpHeaderXOSSCallbackVar            @"x-oss-callback-var"
56
+#define OSSHttpHeaderContentEncoding            @"Content-Encoding"
57
+#define OSSHttpHeaderContentType                @"Content-Type"
58
+#define OSSHttpHeaderContentMD5                 @"Content-MD5"
59
+#define OSSHttpHeaderCacheControl               @"Cache-Control"
60
+#define OSSHttpHeaderExpires                    @"Expires"
61
+
62
+#define OSSDefaultRetryCount                    3
63
+#define OSSDefaultMaxConcurrentNum              5
64
+#define OSSDefaultTimeoutForRequestInSecond     15
65
+#define OSSDefaultTimeoutForResourceInSecond    7 * 24 * 60 * 60
66
+
67
+#endif /* OSSDefine_h */

+ 62
- 0
ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSExecutor.h View File

@@ -0,0 +1,62 @@
1
+/*
2
+ *  Copyright (c) 2014, 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
+
11
+#import <Foundation/Foundation.h>
12
+
13
+NS_ASSUME_NONNULL_BEGIN
14
+
15
+/*!
16
+ An object that can run a given block.
17
+ */
18
+@interface OSSExecutor : NSObject
19
+
20
+/*!
21
+ Returns a default executor, which runs continuations immediately until the call stack gets too
22
+ deep, then dispatches to a new GCD queue.
23
+ */
24
++ (instancetype)defaultExecutor;
25
+
26
+/*!
27
+ Returns an executor that runs continuations on the thread where the previous task was completed.
28
+ */
29
++ (instancetype)immediateExecutor;
30
+
31
+/*!
32
+ Returns an executor that runs continuations on the main thread.
33
+ */
34
++ (instancetype)mainThreadExecutor;
35
+
36
+/*!
37
+ Returns a new executor that uses the given block to execute continuations.
38
+ @param block The block to use.
39
+ */
40
++ (instancetype)executorWithBlock:(void(^)(void(^block)()))block;
41
+
42
+/*!
43
+ Returns a new executor that runs continuations on the given queue.
44
+ @param queue The instance of `dispatch_queue_t` to dispatch all continuations onto.
45
+ */
46
++ (instancetype)executorWithDispatchQueue:(dispatch_queue_t)queue;
47
+
48
+/*!
49
+ Returns a new executor that runs continuations on the given queue.
50
+ @param queue The instance of `NSOperationQueue` to run all continuations on.
51
+ */
52
++ (instancetype)executorWithOperationQueue:(NSOperationQueue *)queue;
53
+
54
+/*!
55
+ Runs the given block using this executor's particular strategy.
56
+ @param block The block to execute.
57
+ */
58
+- (void)execute:(void(^)())block;
59
+
60
+@end
61
+
62
+NS_ASSUME_NONNULL_END

+ 40
- 0
ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSLog.h View File

@@ -0,0 +1,40 @@
1
+//
2
+//  OSSLog.h
3
+//  oss_ios_sdk
4
+//
5
+//  Created by zhouzhuo on 8/16/15.
6
+//  Copyright (c) 2015 aliyun.com. All rights reserved.
7
+//
8
+
9
+#import <Foundation/Foundation.h>
10
+
11
+// colorful log configuration
12
+// see https://github.com/robbiehanson/XcodeColors
13
+
14
+#define XCODE_COLORS_ESCAPE @"\033["
15
+
16
+#define XCODE_COLORS_RESET_FG  XCODE_COLORS_ESCAPE @"fg;" // Clear any foreground color
17
+#define XCODE_COLORS_RESET_BG  XCODE_COLORS_ESCAPE @"bg;" // Clear any background color
18
+#define XCODE_COLORS_RESET     XCODE_COLORS_ESCAPE @";"   // Clear any foreground or background color
19
+
20
+#define OSSLogVerbose(frmt, ...)\
21
+if ([OSSLog isLogEnable]) {\
22
+NSLog(@"[Verbose]: %@", [NSString stringWithFormat:(frmt), ##__VA_ARGS__]);\
23
+}
24
+
25
+#define OSSLogDebug(frmt, ...)\
26
+if ([OSSLog isLogEnable]) {\
27
+NSLog(@"[Debug]: %@", [NSString stringWithFormat:(frmt), ##__VA_ARGS__]);\
28
+}
29
+
30
+#define OSSLogError(frmt, ...)\
31
+if ([OSSLog isLogEnable]) {\
32
+NSLog(@"[Error]: %@", [NSString stringWithFormat:(frmt), ##__VA_ARGS__]);\
33
+}
34
+static BOOL isEnable;
35
+
36
+@interface OSSLog : NSObject
37
++ (void)enableLog;
38
++ (void)disableLog;
39
++ (BOOL)isLogEnable;
40
+@end

+ 1303
- 0
ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSModel.h
File diff suppressed because it is too large
View File


+ 143
- 0
ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSNetworking.h View File

@@ -0,0 +1,143 @@
1
+//
2
+//  OSSNetworking.h
3
+//  oss_ios_sdk
4
+//
5
+//  Created by zhouzhuo on 8/16/15.
6
+//  Copyright (c) 2015 aliyun.com. All rights reserved.
7
+//
8
+
9
+#import <Foundation/Foundation.h>
10
+#import "OSSModel.h"
11
+
12
+@class OSSSyncMutableDictionary;
13
+@class OSSNetworkingRequestDelegate;
14
+@class OSSExecutor;
15
+
16
+/**
17
+ 定义重试类型
18
+ */
19
+typedef NS_ENUM(NSInteger, OSSNetworkingRetryType) {
20
+    OSSNetworkingRetryTypeUnknown,
21
+    OSSNetworkingRetryTypeShouldRetry,
22
+    OSSNetworkingRetryTypeShouldNotRetry,
23
+    OSSNetworkingRetryTypeShouldRefreshCredentialsAndRetry,
24
+    OSSNetworkingRetryTypeShouldCorrectClockSkewAndRetry
25
+};
26
+
27
+/**
28
+ 重试处理器
29
+ */
30
+@interface OSSURLRequestRetryHandler : NSObject
31
+@property (nonatomic, assign) uint32_t maxRetryCount;
32
+
33
+- (OSSNetworkingRetryType)shouldRetry:(uint32_t)currentRetryCount
34
+                      requestDelegate:(OSSNetworkingRequestDelegate *)delegate
35
+                             response:(NSHTTPURLResponse *)response
36
+                                error:(NSError *)error;
37
+
38
+- (NSTimeInterval)timeIntervalForRetry:(uint32_t)currentRetryCount
39
+                             retryType:(OSSNetworkingRetryType)retryType;
40
+
41
++ (instancetype)defaultRetryHandler;
42
+@end
43
+
44
+/**
45
+ 网络参数设置
46
+ */
47
+@interface OSSNetworkingConfiguration : NSObject
48
+@property (nonatomic, assign) uint32_t maxRetryCount;
49
+@property (nonatomic, assign) uint32_t maxConcurrentRequestCount;
50
+@property (nonatomic, assign) BOOL enableBackgroundTransmitService;
51
+@property (nonatomic, strong) NSString * backgroundSessionIdentifier;
52
+@property (nonatomic, assign) NSTimeInterval timeoutIntervalForRequest;
53
+@property (nonatomic, assign) NSTimeInterval timeoutIntervalForResource;
54
+@property (nonatomic, strong) NSString * proxyHost;
55
+@property (nonatomic, strong) NSNumber * proxyPort;
56
+@end
57
+
58
+/**
59
+ 对操作发起的每一次请求构造一个信息代理
60
+ */
61
+@interface OSSNetworkingRequestDelegate : NSObject
62
+
63
+@property (nonatomic, strong) NSMutableArray * interceptors;
64
+@property (nonatomic, strong) OSSAllRequestNeededMessage * allNeededMessage;
65
+@property (nonatomic, strong) NSMutableURLRequest * internalRequest;
66
+@property (nonatomic, assign) OSSOperationType operType;
67
+@property (nonatomic, assign) BOOL isAccessViaProxy;
68
+
69
+@property (nonatomic, assign) BOOL isRequestCancelled;
70
+
71
+@property (nonatomic, strong) OSSHttpResponseParser * responseParser;
72
+
73
+@property (nonatomic, strong) NSData * uploadingData;
74
+@property (nonatomic, strong) NSURL * uploadingFileURL;
75
+
76
+@property (nonatomic, assign) int64_t payloadTotalBytesWritten;
77
+
78
+@property (nonatomic, assign) BOOL isBackgroundUploadFileTask;
79
+@property (nonatomic, assign) BOOL isHttpdnsEnable;
80
+
81
+@property (nonatomic, strong) OSSURLRequestRetryHandler * retryHandler;
82
+@property (nonatomic, assign) uint32_t currentRetryCount;
83
+@property (nonatomic, strong) NSError * error;
84
+@property (nonatomic, assign) BOOL isHttpRequestNotSuccessResponse;
85
+@property (nonatomic, strong) NSMutableData * httpRequestNotSuccessResponseBody;
86
+
87
+@property (atomic, strong) NSURLSessionDataTask * currentSessionTask;
88
+
89
+@property (nonatomic, copy) OSSNetworkingUploadProgressBlock uploadProgress;
90
+@property (nonatomic, copy) OSSNetworkingDownloadProgressBlock downloadProgress;
91
+@property (nonatomic, copy) OSSNetworkingCompletionHandlerBlock completionHandler;
92
+@property (nonatomic, copy) OSSNetworkingOnRecieveDataBlock onRecieveData;
93
+
94
+- (OSSTask *)buildInternalHttpRequest;
95
+- (void)reset;
96
+- (void)cancel;
97
+@end
98
+
99
+/**
100
+ 包含一次网络请求所需的所有信息
101
+ */
102
+@interface OSSAllRequestNeededMessage : NSObject
103
+@property (nonatomic, strong) NSString * endpoint;
104
+@property (nonatomic, strong) NSString * httpMethod;
105
+@property (nonatomic, strong) NSString * bucketName;
106
+@property (nonatomic, strong) NSString * objectKey;
107
+@property (nonatomic, strong) NSString * contentType;
108
+@property (nonatomic, strong) NSString * contentMd5;
109
+@property (nonatomic, strong) NSString * range;
110
+@property (nonatomic, strong) NSString * date;
111
+@property (nonatomic, strong) NSMutableDictionary * headerParams;
112
+@property (nonatomic, strong) NSMutableDictionary * querys;
113
+
114
+@property (nonatomic, assign) BOOL isHostInCnameExcludeList;
115
+
116
+- (instancetype)initWithEndpoint:(NSString *)endpoint
117
+                      httpMethod:(NSString *)httpMethod
118
+                      bucketName:(NSString *)bucketName
119
+                       objectKey:(NSString *)objectKey
120
+                            type:(NSString *)contentType
121
+                             md5:(NSString *)contentMd5
122
+                           range:(NSString *)range
123
+                            date:(NSString *)date
124
+                    headerParams:(NSMutableDictionary *)headerParams
125
+                          querys:(NSMutableDictionary *)querys;
126
+
127
+- (OSSTask *)validateRequestParamsInOperationType:(OSSOperationType)operType;
128
+@end
129
+
130
+/**
131
+ 每个OSSClient持有一个OSSNetworking用以收发网络请求
132
+ */
133
+@interface OSSNetworking : NSObject <NSURLSessionDelegate>
134
+@property (nonatomic, strong) NSURLSession * dataSession;
135
+@property (nonatomic, strong) NSURLSession * uploadFileSession;
136
+@property (nonatomic, assign) BOOL isUsingBackgroundSession;
137
+@property (nonatomic, strong) OSSSyncMutableDictionary * sessionDelagateManager;
138
+@property (nonatomic, strong) OSSNetworkingConfiguration * configuration;
139
+@property (nonatomic, strong) OSSExecutor * taskExecutor;
140
+
141
+- (instancetype)initWithConfiguration:(OSSNetworkingConfiguration *)configuration;
142
+- (OSSTask *)sendRequest:(OSSNetworkingRequestDelegate *)request;
143
+@end

+ 20
- 0
ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSService.h View File

@@ -0,0 +1,20 @@
1
+//
2
+//  OSSService.h
3
+//  oss_ios_sdk
4
+//
5
+//  Created by zhouzhuo on 8/20/15.
6
+//  Copyright (c) 2015 aliyun.com. All rights reserved.
7
+//
8
+
9
+#import <Foundation/Foundation.h>
10
+
11
+#define OSS_IOS_SDK_VERSION OSSSDKVersion
12
+
13
+#import "OSSDefine.h"
14
+#import "OSSNetworking.h"
15
+#import "OSSClient.h"
16
+#import "OSSModel.h"
17
+#import "OSSUtil.h"
18
+#import "OSSLog.h"
19
+
20
+#import "OSSBolts.h"

+ 281
- 0
ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSTask.h View File

@@ -0,0 +1,281 @@
1
+/*
2
+ *  Copyright (c) 2014, 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
+
11
+#import <Foundation/Foundation.h>
12
+
13
+#import "OSSCancellationToken.h"
14
+
15
+NS_ASSUME_NONNULL_BEGIN
16
+
17
+/*!
18
+ Error domain used if there was multiple errors on <OSSTask taskForCompletionOfAllTasks:>.
19
+ */
20
+extern NSString *const OSSTaskErrorDomain;
21
+
22
+/*!
23
+ An error code used for <OSSTask taskForCompletionOfAllTasks:>, if there were multiple errors.
24
+ */
25
+extern NSInteger const kOSSMultipleErrorsError;
26
+
27
+/*!
28
+ An exception that is thrown if there was multiple exceptions on <OSSTask taskForCompletionOfAllTasks:>.
29
+ */
30
+extern NSString *const OSSTaskMultipleExceptionsException;
31
+
32
+/*!
33
+ An error userInfo key used if there were multiple errors on <OSSTask taskForCompletionOfAllTasks:>.
34
+ Value type is `NSArray<NSError *> *`.
35
+ */
36
+extern NSString *const OSSTaskMultipleErrorsUserInfoKey;
37
+
38
+/*!
39
+ An error userInfo key used if there were multiple exceptions on <OSSTask taskForCompletionOfAllTasks:>.
40
+ Value type is `NSArray<NSException *> *`.
41
+ */
42
+extern NSString *const OSSTaskMultipleExceptionsUserInfoKey;
43
+
44
+@class OSSExecutor;
45
+@class OSSTask;
46
+
47
+/*!
48
+ The consumer view of a Task. A OSSTask has methods to
49
+ inspect the state of the task, and to add continuations to
50
+ be run once the task is complete.
51
+ */
52
+@interface OSSTask<__covariant ResultType> : NSObject
53
+
54
+/*!
55
+ A block that can act as a continuation for a task.
56
+ */
57
+typedef __nullable id(^OSSContinuationBlock)(OSSTask<ResultType> *task);
58
+
59
+/*!
60
+ Creates a task that is already completed with the given result.
61
+ @param result The result for the task.
62
+ */
63
++ (instancetype)taskWithResult:(nullable ResultType)result;
64
+
65
+/*!
66
+ Creates a task that is already completed with the given error.
67
+ @param error The error for the task.
68
+ */
69
++ (instancetype)taskWithError:(NSError *)error;
70
+
71
+/*!
72
+ Creates a task that is already completed with the given exception.
73
+ @param exception The exception for the task.
74
+ */
75
++ (instancetype)taskWithException:(NSException *)exception;
76
+
77
+/*!
78
+ Creates a task that is already cancelled.
79
+ */
80
++ (instancetype)cancelledTask;
81
+
82
+/*!
83
+ Returns a task that will be completed (with result == nil) once
84
+ all of the input tasks have completed.
85
+ @param tasks An `NSArray` of the tasks to use as an input.
86
+ */
87
++ (instancetype)taskForCompletionOfAllTasks:(nullable NSArray<OSSTask *> *)tasks;
88
+
89
+/*!
90
+ Returns a task that will be completed once all of the input tasks have completed.
91
+ If all tasks complete successfully without being faulted or cancelled the result will be
92
+ an `NSArray` of all task results in the order they were provided.
93
+ @param tasks An `NSArray` of the tasks to use as an input.
94
+ */
95
++ (instancetype)taskForCompletionOfAllTasksWithResults:(nullable NSArray<OSSTask *> *)tasks;
96
+
97
+/*!
98
+ Returns a task that will be completed once there is at least one successful task.
99
+ The first task to successuly complete will set the result, all other tasks results are 
100
+ ignored.
101
+ @param tasks An `NSArray` of the tasks to use as an input.
102
+ */
103
++ (instancetype)taskForCompletionOfAnyTask:(nullable NSArray<OSSTask *> *)tasks;
104
+
105
+/*!
106
+ Returns a task that will be completed a certain amount of time in the future.
107
+ @param millis The approximate number of milliseconds to wait before the
108
+ task will be finished (with result == nil).
109
+ */
110
++ (instancetype)taskWithDelay:(int)millis;
111
+
112
+/*!
113
+ Returns a task that will be completed a certain amount of time in the future.
114
+ @param millis The approximate number of milliseconds to wait before the
115
+ task will be finished (with result == nil).
116
+ @param token The cancellation token (optional).
117
+ */
118
++ (instancetype)taskWithDelay:(int)millis cancellationToken:(nullable OSSCancellationToken *)token;
119
+
120
+/*!
121
+ Returns a task that will be completed after the given block completes with
122
+ the specified executor.
123
+ @param executor A OSSExecutor responsible for determining how the
124
+ continuation block will be run.
125
+ @param block The block to immediately schedule to run with the given executor.
126
+ @returns A task that will be completed after block has run.
127
+ If block returns a OSSTask, then the task returned from
128
+ this method will not be completed until that task is completed.
129
+ */
130
++ (instancetype)taskFromExecutor:(OSSExecutor *)executor withBlock:(nullable id (^)())block;
131
+
132
+// Properties that will be set on the task once it is completed.
133
+
134
+/*!
135
+ The result of a successful task.
136
+ */
137
+@property (nullable, nonatomic, strong, readonly) ResultType result;
138
+
139
+/*!
140
+ The error of a failed task.
141
+ */
142
+@property (nullable, nonatomic, strong, readonly) NSError *error;
143
+
144
+/*!
145
+ The exception of a failed task.
146
+ */
147
+@property (nullable, nonatomic, strong, readonly) NSException *exception;
148
+
149
+/*!
150
+ Whether this task has been cancelled.
151
+ */
152
+@property (nonatomic, assign, readonly, getter=isCancelled) BOOL cancelled;
153
+
154
+/*!
155
+ Whether this task has completed due to an error or exception.
156
+ */
157
+@property (nonatomic, assign, readonly, getter=isFaulted) BOOL faulted;
158
+
159
+/*!
160
+ Whether this task has completed.
161
+ */
162
+@property (nonatomic, assign, readonly, getter=isCompleted) BOOL completed;
163
+
164
+/*!
165
+ Enqueues the given block to be run once this task is complete.
166
+ This method uses a default execution strategy. The block will be
167
+ run on the thread where the previous task completes, unless the
168
+ the stack depth is too deep, in which case it will be run on a
169
+ dispatch queue with default priority.
170
+ @param block The block to be run once this task is complete.
171
+ @returns A task that will be completed after block has run.
172
+ If block returns a OSSTask, then the task returned from
173
+ this method will not be completed until that task is completed.
174
+ */
175
+- (OSSTask *)continueWithBlock:(OSSContinuationBlock)block;
176
+
177
+/*!
178
+ Enqueues the given block to be run once this task is complete.
179
+ This method uses a default execution strategy. The block will be
180
+ run on the thread where the previous task completes, unless the
181
+ the stack depth is too deep, in which case it will be run on a
182
+ dispatch queue with default priority.
183
+ @param block The block to be run once this task is complete.
184
+ @param cancellationToken The cancellation token (optional).
185
+ @returns A task that will be completed after block has run.
186
+ If block returns a OSSTask, then the task returned from
187
+ this method will not be completed until that task is completed.
188
+ */
189
+- (OSSTask *)continueWithBlock:(OSSContinuationBlock)block cancellationToken:(nullable OSSCancellationToken *)cancellationToken;
190
+
191
+/*!
192
+ Enqueues the given block to be run once this task is complete.
193
+ @param executor A OSSExecutor responsible for determining how the
194
+ continuation block will be run.
195
+ @param block The block to be run once this task is complete.
196
+ @returns A task that will be completed after block has run.
197
+ If block returns a OSSTask, then the task returned from
198
+ this method will not be completed until that task is completed.
199
+ */
200
+- (OSSTask *)continueWithExecutor:(OSSExecutor *)executor withBlock:(OSSContinuationBlock)block;
201
+/*!
202
+ Enqueues the given block to be run once this task is complete.
203
+ @param executor A OSSExecutor responsible for determining how the
204
+ continuation block will be run.
205
+ @param block The block to be run once this task is complete.
206
+ @param cancellationToken The cancellation token (optional).
207
+ @returns A task that will be completed after block has run.
208
+ If block returns a OSSTask, then the task returned from
209
+ his method will not be completed until that task is completed.
210
+ */
211
+- (OSSTask *)continueWithExecutor:(OSSExecutor *)executor
212
+                           block:(OSSContinuationBlock)block
213
+               cancellationToken:(nullable OSSCancellationToken *)cancellationToken;
214
+
215
+/*!
216
+ Identical to continueWithBlock:, except that the block is only run
217
+ if this task did not produce a cancellation, error, or exception.
218
+ If it did, then the failure will be propagated to the returned
219
+ task.
220
+ @param block The block to be run once this task is complete.
221
+ @returns A task that will be completed after block has run.
222
+ If block returns a OSSTask, then the task returned from
223
+ this method will not be completed until that task is completed.
224
+ */
225
+- (OSSTask *)continueWithSuccessBlock:(OSSContinuationBlock)block;
226
+
227
+/*!
228
+ Identical to continueWithBlock:, except that the block is only run
229
+ if this task did not produce a cancellation, error, or exception.
230
+ If it did, then the failure will be propagated to the returned
231
+ task.
232
+ @param block The block to be run once this task is complete.
233
+ @param cancellationToken The cancellation token (optional).
234
+ @returns A task that will be completed after block has run.
235
+ If block returns a OSSTask, then the task returned from
236
+ this method will not be completed until that task is completed.
237
+ */
238
+- (OSSTask *)continueWithSuccessBlock:(OSSContinuationBlock)block cancellationToken:(nullable OSSCancellationToken *)cancellationToken;
239
+
240
+/*!
241
+ Identical to continueWithExecutor:withBlock:, except that the block
242
+ is only run if this task did not produce a cancellation, error, or
243
+ exception. If it did, then the failure will be propagated to the
244
+ returned task.
245
+ @param executor A OSSExecutor responsible for determining how the
246
+ continuation block will be run.
247
+ @param block The block to be run once this task is complete.
248
+ @returns A task that will be completed after block has run.
249
+ If block returns a OSSTask, then the task returned from
250
+ this method will not be completed until that task is completed.
251
+ */
252
+- (OSSTask *)continueWithExecutor:(OSSExecutor *)executor withSuccessBlock:(OSSContinuationBlock)block;
253
+
254
+/*!
255
+ Identical to continueWithExecutor:withBlock:, except that the block
256
+ is only run if this task did not produce a cancellation, error, or
257
+ exception. If it did, then the failure will be propagated to the
258
+ returned task.
259
+ @param executor A OSSExecutor responsible for determining how the
260
+ continuation block will be run.
261
+ @param block The block to be run once this task is complete.
262
+ @param cancellationToken The cancellation token (optional).
263
+ @returns A task that will be completed after block has run.
264
+ If block returns a OSSTask, then the task returned from
265
+ this method will not be completed until that task is completed.
266
+ */
267
+- (OSSTask *)continueWithExecutor:(OSSExecutor *)executor
268
+                    successBlock:(OSSContinuationBlock)block
269
+               cancellationToken:(nullable OSSCancellationToken *)cancellationToken;
270
+
271
+/*!
272
+ Waits until this operation is completed.
273
+ This method is inefficient and consumes a thread resource while
274
+ it's running. It should be avoided. This method logs a warning
275
+ message if it is used on the main thread.
276
+ */
277
+- (void)waitUntilFinished;
278
+
279
+@end
280
+
281
+NS_ASSUME_NONNULL_END

+ 89
- 0
ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSTaskCompletionSource.h View File

@@ -0,0 +1,89 @@
1
+/*
2
+ *  Copyright (c) 2014, 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
+
11
+#import <Foundation/Foundation.h>
12
+
13
+NS_ASSUME_NONNULL_BEGIN
14
+
15
+@class OSSTask<ResultType>;
16
+
17
+/*!
18
+ A OSSTaskCompletionSource represents the producer side of tasks.
19
+ It is a task that also has methods for changing the state of the
20
+ task by settings its completion values.
21
+ */
22
+@interface OSSTaskCompletionSource<__covariant ResultType> : NSObject
23
+
24
+/*!
25
+ Creates a new unfinished task.
26
+ */
27
++ (instancetype)taskCompletionSource;
28
+
29
+/*!
30
+ The task associated with this TaskCompletionSource.
31
+ */
32
+@property (nonatomic, strong, readonly) OSSTask<ResultType> *task;
33
+
34
+/*!
35
+ Completes the task by setting the result.
36
+ Attempting to set this for a completed task will raise an exception.
37
+ @param result The result of the task.
38
+ */
39
+- (void)setResult:(nullable ResultType)result;
40
+
41
+/*!
42
+ Completes the task by setting the error.
43
+ Attempting to set this for a completed task will raise an exception.
44
+ @param error The error for the task.
45
+ */
46
+- (void)setError:(NSError *)error;
47
+
48
+/*!
49
+ Completes the task by setting an exception.
50
+ Attempting to set this for a completed task will raise an exception.
51
+ @param exception The exception for the task.
52
+ */
53
+- (void)setException:(NSException *)exception;
54
+
55
+/*!
56
+ Completes the task by marking it as cancelled.
57
+ Attempting to set this for a completed task will raise an exception.
58
+ */
59
+- (void)cancel;
60
+
61
+/*!
62
+ Sets the result of the task if it wasn't already completed.
63
+ @returns whether the new value was set.
64
+ */
65
+- (BOOL)trySetResult:(nullable ResultType)result;
66
+
67
+/*!
68
+ Sets the error of the task if it wasn't already completed.
69
+ @param error The error for the task.
70
+ @returns whether the new value was set.
71
+ */
72
+- (BOOL)trySetError:(NSError *)error;
73
+
74
+/*!
75
+ Sets the exception of the task if it wasn't already completed.
76
+ @param exception The exception for the task.
77
+ @returns whether the new value was set.
78
+ */
79
+- (BOOL)trySetException:(NSException *)exception;
80
+
81
+/*!
82
+ Sets the cancellation state of the task if it wasn't already completed.
83
+ @returns whether the new value was set.
84
+ */
85
+- (BOOL)trySetCancelled;
86
+
87
+@end
88
+
89
+NS_ASSUME_NONNULL_END

+ 37
- 0
ios/AliyunSDK/AliyunOSSiOS.framework/Headers/OSSUtil.h View File

@@ -0,0 +1,37 @@
1
+//
2
+//  OSSUtil.h
3
+//  oss_ios_sdk
4
+//
5
+//  Created by zhouzhuo on 8/16/15.
6
+//  Copyright (c) 2015 aliyun.com. All rights reserved.
7
+//
8
+
9
+#import <Foundation/Foundation.h>
10
+
11
+@class OSSFederationToken;
12
+
13
+@interface OSSUtil : NSObject
14
+
15
++ (NSString *)calBase64Sha1WithData:(NSString *)data withSecret:(NSString *)key;
16
++ (NSString *)calBase64WithData:(uint8_t *)data;
17
++ (NSString *)encodeURL:(NSString *)url;
18
++ (NSData *)constructHttpBodyFromPartInfos:(NSArray *)partInfos;
19
++ (NSData *)constructHttpBodyForCreateBucketWithLocation:(NSString *)location;
20
++ (BOOL)validateBucketName:(NSString *)bucketName;
21
++ (BOOL)validateObjectKey:(NSString *)objectKey;
22
++ (BOOL)isOssOriginBucketHost:(NSString *)host;
23
++ (NSString *)getIpByHost:(NSString *)host;
24
++ (BOOL)isNetworkDelegateState;
25
++ (NSString *)dataMD5String:(NSData *)data;
26
++ (NSString *)fileMD5String:(NSString *)path;
27
++ (NSString*)base64ForData:(uint8_t *)input length:(int32_t)length;
28
++ (NSString *)base64Md5ForData:(NSData *)data;
29
++ (NSString *)base64Md5ForFilePath:(NSString *)filePath;
30
++ (NSString *)base64Md5ForFileURL:(NSURL *)fileURL;
31
++ (NSString *)populateSubresourceStringFromParameter:(NSDictionary *)parameters;
32
++ (NSString *)populateQueryStringFromParameter:(NSDictionary *)parameters;
33
++ (BOOL)isSubresource:(NSString *)param;
34
++ (NSString *)sign:(NSString *)content withToken:(OSSFederationToken *)token;
35
++ (NSString *)getRelativePath:(NSString *)fullPath;
36
++ (NSString *)detemineMimeTypeForFilePath:(NSString *)filePath uploadName:(NSString *)uploadName;
37
+@end

+ 6
- 0
ios/AliyunSDK/AliyunOSSiOS.framework/Modules/module.modulemap View File

@@ -0,0 +1,6 @@
1
+framework module AliyunOSSiOS {
2
+  umbrella header "AliyunOSSiOS.h"
3
+
4
+  export *
5
+  module * { export * }
6
+}

+ 12
- 0
ios/RNAliyunOSS+AUTH.h View File

@@ -0,0 +1,12 @@
1
+//
2
+//  RNAliyunOSS+AUTH.h
3
+//  aliyun-oss-rn-sdk
4
+//
5
+//  Created by 罗章 on 2018/5/8.
6
+//
7
+
8
+#import <RNAliyunOSS.h>
9
+
10
+@interface RNAliyunOSS (AUTH)
11
+
12
+@end

+ 78
- 0
ios/RNAliyunOSS+AUTH.m View File

@@ -0,0 +1,78 @@
1
+//
2
+//  RNAliyunOSS+AUTH.m
3
+//  aliyun-oss-rn-sdk
4
+//
5
+//  Created by 罗章 on 2018/5/8.
6
+//
7
+
8
+#import "RNAliyunOSS+AUTH.h"
9
+
10
+@implementation RNAliyunOSS (AUTH)
11
+
12
+
13
+
14
+/**
15
+ initWithPlainTextAccessKey
16
+ 
17
+ */
18
+RCT_EXPORT_METHOD(initWithPlainTextAccessKey:(NSString *)accessKey secretKey:(NSString *)secretKey endPoint:(NSString *)endPoint configuration:(NSDictionary *)configuration){
19
+    
20
+    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:accessKey secretKey:secretKey];
21
+    
22
+    [self initConfiguration: configuration];
23
+    
24
+    self.client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential clientConfiguration:self.clientConfiguration];
25
+}
26
+
27
+
28
+/**
29
+ initWithImplementedSigner
30
+ 
31
+ */
32
+RCT_EXPORT_METHOD(initWithImplementedSigner:(NSString *)signature accessKey:(NSString *)accessKey endPoint:(NSString *)endPoint configuration:(NSDictionary *)configuration){
33
+    
34
+    id<OSSCredentialProvider> credential = [[OSSCustomSignerCredentialProvider alloc] initWithImplementedSigner:^NSString *(NSString *contentToSign, NSError *__autoreleasing *error) {
35
+        if (signature != nil) {
36
+            *error = nil;
37
+        } else {
38
+            // construct error object
39
+            *error = [NSError errorWithDomain:endPoint code:OSSClientErrorCodeSignFailed userInfo:nil];
40
+            return nil;
41
+        }
42
+        return [NSString stringWithFormat:@"OSS %@:%@", accessKey, signature];
43
+    }];
44
+    
45
+    [self initConfiguration: configuration];
46
+    
47
+    self.client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential clientConfiguration:self.clientConfiguration];
48
+}
49
+
50
+
51
+/**
52
+ initWithSecurityToken
53
+ 
54
+ */
55
+RCT_EXPORT_METHOD(initWithSecurityToken:(NSString *)securityToken accessKey:(NSString *)accessKey secretKey:(NSString *)secretKey endPoint:(NSString *)endPoint configuration:(NSDictionary *)configuration){
56
+    
57
+    id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:accessKey secretKeyId:secretKey securityToken:securityToken];
58
+    
59
+    [self initConfiguration: configuration];
60
+    
61
+    
62
+    self.client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential clientConfiguration:self.clientConfiguration];
63
+}
64
+
65
+/**
66
+ initWithServerSTS
67
+ */
68
+RCT_EXPORT_METHOD(initWithServerSTS:(NSString *)server endPoint:(NSString *)endPoint configuration:(NSDictionary *)configuration){
69
+    //直接访问鉴权服务器(推荐,token过期后可以自动更新)
70
+    id<OSSCredentialProvider> credential = [[OSSAuthCredentialProvider alloc] initWithAuthServerUrl:server];
71
+    
72
+    [self initConfiguration: configuration];
73
+
74
+    self.client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential clientConfiguration:self.clientConfiguration];
75
+}
76
+
77
+
78
+@end

+ 12
- 0
ios/RNAliyunOSS+BUCKET.h View File

@@ -0,0 +1,12 @@
1
+//
2
+//  RNAliyunOSS+BUCKET.h
3
+//  aliyun-oss-rn-sdk
4
+//
5
+//  Created by 罗章 on 2018/5/8.
6
+//
7
+
8
+#import <RNAliyunOSS.h>
9
+
10
+@interface RNAliyunOSS (BUCKET)
11
+
12
+@end

+ 97
- 0
ios/RNAliyunOSS+BUCKET.m View File

@@ -0,0 +1,97 @@
1
+//
2
+//  RNAliyunOSS+BUCKET.m
3
+//  aliyun-oss-rn-sdk
4
+//
5
+//  Created by 罗章 on 2018/5/8.
6
+//
7
+
8
+#import "RNAliyunOSS+BUCKET.h"
9
+
10
+@implementation RNAliyunOSS (BUCKET)
11
+
12
+/**
13
+ *异步创建bucket
14
+ */
15
+
16
+RCT_REMAP_METHOD(asyncCreateBucket,bucketName:(NSString*)bucketName acl:(NSString*)acl region:(NSString*)region resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) {
17
+    OSSCreateBucketRequest * create = [OSSCreateBucketRequest new];
18
+    create.bucketName = bucketName ;
19
+    create.xOssACL = acl;
20
+    create.location = region;
21
+    OSSTask * createTask = [self.client createBucket:create];
22
+    [createTask continueWithBlock:^id(OSSTask *task) {
23
+        if (!task.error) {
24
+            NSLog(@"create bucket success!");
25
+            resolve(@"create bucket success!");
26
+        } else {
27
+            NSLog(@"create bucket failed, error: %@", task.error);
28
+            reject(@"Error", @"Upload failed", task.error);
29
+        }
30
+        return nil;
31
+    }];
32
+}
33
+
34
+
35
+/*
36
+ 罗列出所有的bucket
37
+ */
38
+RCT_REMAP_METHOD(asyncListBuckets, resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) {
39
+    OSSGetServiceRequest * getService = [OSSGetServiceRequest new];
40
+    OSSTask * getServiceTask = [self.client getService:getService];
41
+    [getServiceTask continueWithBlock:^id(OSSTask *task) {
42
+        if (!task.error) {
43
+            OSSGetServiceResult * result = task.result;
44
+            NSLog(@"buckets: %@", result.buckets);
45
+            resolve(result.buckets);
46
+            NSLog(@"owner: %@, %@", result.ownerId, result.ownerDispName);
47
+            [result.buckets enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
48
+                NSDictionary * bucketInfo = obj;
49
+                NSLog(@"BucketName: %@", [bucketInfo objectForKey:@"Name"]);
50
+                NSLog(@"CreationDate: %@", [bucketInfo objectForKey:@"CreationDate"]);
51
+                NSLog(@"Location: %@", [bucketInfo objectForKey:@"Location"]);
52
+            }];
53
+        }
54
+        return nil;
55
+    }];
56
+}
57
+
58
+/**
59
+ asyncGetBucketACL
60
+ */
61
+RCT_REMAP_METHOD(asyncGetBucketACL, bucketName:(NSString*)bucketName resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) {
62
+    OSSGetBucketACLRequest *getBucketACL = [OSSGetBucketACLRequest new];
63
+    getBucketACL.bucketName = bucketName;
64
+    
65
+    OSSTask * osstask = [self.client getBucketACL:getBucketACL];
66
+    [osstask continueWithBlock:^id(OSSTask *task) {
67
+        if (!task.error) {
68
+            OSSGetBucketACLResult * result = task.result;
69
+            resolve(result.aclGranted);
70
+        }else {
71
+            reject(@"Error",@"getBucketACL fail",task.error);
72
+        }
73
+        return nil;
74
+    }];
75
+}
76
+
77
+/*
78
+ asyncDeleteBucket
79
+ */
80
+RCT_REMAP_METHOD(asyncDeleteBucket,withBucketName:(NSString*)bucketName resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){
81
+    OSSDeleteBucketRequest * delete = [OSSDeleteBucketRequest new];
82
+    delete.bucketName = bucketName;
83
+    OSSTask * deleteTask = [self.client deleteBucket:delete];
84
+    [deleteTask continueWithBlock:^id(OSSTask *task) {
85
+        if (!task.error) {
86
+            NSLog(@"delete bucket success!");
87
+            resolve(@"delete bucket success");
88
+        } else {
89
+            NSLog(@"delete bucket failed, error: %@", task.error);
90
+            reject(@"Error", @"delete bucket failed", task.error);
91
+        }
92
+        return nil;
93
+    }];
94
+}
95
+
96
+
97
+@end

+ 12
- 0
ios/RNAliyunOSS+DOWNLOAD.h View File

@@ -0,0 +1,12 @@
1
+//
2
+//  RNAliyunOSS+DOWNLOAD.h
3
+//  aliyun-oss-rn-sdk
4
+//
5
+//  Created by 罗章 on 2018/5/8.
6
+//
7
+
8
+#import <RNAliyunOSS.h>
9
+
10
+@interface RNAliyunOSS (DOWNLOAD)
11
+
12
+@end

+ 65
- 0
ios/RNAliyunOSS+DOWNLOAD.m View File

@@ -0,0 +1,65 @@
1
+//
2
+//  RNAliyunOSS+DOWNLOAD.m
3
+//  aliyun-oss-rn-sdk
4
+//
5
+//  Created by 罗章 on 2018/5/8.
6
+//
7
+
8
+#import "RNAliyunOSS+DOWNLOAD.h"
9
+#import <React/RCTLog.h>
10
+#import <React/RCTConvert.h>
11
+@implementation RNAliyunOSS (DOWNLOAD)
12
+
13
+
14
+/**
15
+ Asynchronous downloading
16
+ 
17
+ */
18
+RCT_REMAP_METHOD(asyncDownload, asyncDownloadWithBucketName:(NSString *)bucketName objectKey:(NSString *)objectKey filepath:(NSString *)filepath options:(NSDictionary*)options resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){
19
+    
20
+    OSSGetObjectRequest * get = [OSSGetObjectRequest new];
21
+    
22
+    //required fields
23
+    get.bucketName = bucketName;
24
+    get.objectKey = objectKey;
25
+    
26
+    //图片处理情况
27
+    NSString *xOssProcess = [RCTConvert NSString:options[@"x-oss-process"]];
28
+    get.xOssProcess = xOssProcess;
29
+    
30
+    //optional fields
31
+    get.downloadProgress = ^(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
32
+        NSLog(@"%lld, %lld, %lld", bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
33
+        //         Only send events if anyone is listening
34
+        if (self.hasListeners) {
35
+            [self sendEventWithName:@"downloadProgress" body:@{@"bytesWritten":[NSString stringWithFormat:@"%lld",bytesWritten],
36
+                                                               @"currentSize": [NSString stringWithFormat:@"%lld",totalBytesWritten],
37
+                                                               @"totalSize": [NSString stringWithFormat:@"%lld",totalBytesExpectedToWrite]}];
38
+        }
39
+    };
40
+    
41
+    if (![[filepath oss_trim] isEqualToString:@""]) {
42
+        get.downloadToFileURL = [NSURL fileURLWithPath:[filepath stringByAppendingPathComponent:objectKey]];
43
+    } else {
44
+        NSString *docDir = [self getDocumentDirectory];
45
+        get.downloadToFileURL = [NSURL fileURLWithPath:[docDir stringByAppendingPathComponent:objectKey]];
46
+    }
47
+    
48
+    OSSTask * getTask = [self.client getObject:get];
49
+    
50
+    [getTask continueWithBlock:^id(OSSTask *task) {
51
+        
52
+        if (!task.error) {
53
+            NSLog(@"download object success!");
54
+            OSSGetObjectResult *result = task.result;
55
+            NSLog(@"download dota length: %lu", [result.downloadedData length]);
56
+            resolve([get.downloadToFileURL absoluteString]);
57
+        } else {
58
+            NSLog(@"download object failed, error: %@" ,task.error);
59
+            reject(@"Error", @"Download failed", task.error);
60
+        }
61
+        return nil;
62
+    }];
63
+}
64
+
65
+@end

+ 12
- 0
ios/RNAliyunOSS+LOG.h View File

@@ -0,0 +1,12 @@
1
+//
2
+//  RNAliyunOSS+LOG.h
3
+//  aliyun-oss-rn-sdk
4
+//
5
+//  Created by 罗章 on 2018/5/8.
6
+//
7
+
8
+#import <RNAliyunOSS.h>
9
+
10
+@interface RNAliyunOSS (LOG)
11
+
12
+@end

+ 19
- 0
ios/RNAliyunOSS+LOG.m View File

@@ -0,0 +1,19 @@
1
+//
2
+//  RNAliyunOSS+LOG.m
3
+//  aliyun-oss-rn-sdk
4
+//
5
+//  Created by 罗章 on 2018/5/8.
6
+//
7
+
8
+#import "RNAliyunOSS+LOG.h"
9
+
10
+@implementation RNAliyunOSS (LOG)
11
+
12
+/**
13
+ enable the dev mode
14
+ */
15
+RCT_EXPORT_METHOD(enableDevMode){
16
+    // enable OSS logger
17
+    [OSSLog enableLog];
18
+}
19
+@end

+ 12
- 0
ios/RNAliyunOSS+MULTIPARTUPLOAD.h View File

@@ -0,0 +1,12 @@
1
+//
2
+//  RNAliyunOSS+MULTIPARTUPLOAD.h
3
+//  aliyun-oss-rn-sdk
4
+//
5
+//  Created by 罗章 on 2018/5/10.
6
+//
7
+
8
+#import <RNAliyunOSS.h>
9
+
10
+@interface RNAliyunOSS (MULTIPARTUPLOAD)
11
+
12
+@end

+ 0
- 0
ios/RNAliyunOSS+MULTIPARTUPLOAD.m View File


Some files were not shown because too many files changed in this diff