@code_shuai/react-native-kuaishou-open-sdk 0.0.0-stage → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/PRD.md +64 -0
- package/README.md +59 -2
- package/android/build.gradle +20 -0
- package/android/consumer-rules.pro +2 -0
- package/android/src/main/AndroidManifest.xml +27 -0
- package/android/src/main/java/com/finstao/kuaishou/KuaishouFileProvider.java +5 -0
- package/android/src/main/java/com/finstao/kuaishou/KuaishouModule.java +422 -0
- package/android/src/main/java/com/finstao/kuaishou/KuaishouPackage.java +20 -0
- package/android/src/main/res/xml/rn_kuaishou_paths.xml +3 -0
- package/example/shareMedia.ts +16 -0
- package/ios/RNKuaishouOpenSDK.h +8 -0
- package/ios/RNKuaishouOpenSDK.m +271 -0
- package/lib/core.d.ts +60 -0
- package/lib/core.js +75 -0
- package/lib/index.d.ts +14 -0
- package/lib/index.js +8 -0
- package/package.json +32 -4
- package/react-native-kuaishou-open-sdk.podspec +19 -0
- package/src/core.ts +111 -0
- package/src/index.ts +18 -0
package/PRD.md
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# React Native 快手 Open SDK PRD
|
|
2
|
+
|
|
3
|
+
版本:0.1|2026-11-13|待评审。本文定义独立 RN 桥接包的产品范围与验收要求;尚未接入 SDK 或完成设备验证。
|
|
4
|
+
|
|
5
|
+
## 1. 目标与使用场景
|
|
6
|
+
|
|
7
|
+
今小店已有抖音分享接入与联调页。新增快手主站作为作品分享目的地:用户从今小店选择一张或多张图片,或一个视频,点击「分享到快手」,进入快手编辑并由用户自行决定是否发布。首个接入宿主为 `promoter-app`,目标兼容其 RN 0.83 与新架构配置。SDK 独立于业务,可供其他 RN 宿主复用。
|
|
8
|
+
|
|
9
|
+
沿用抖音 SDK 的统一 API、显式资源准备、能力查询、原生回调保留、单请求与超时清理设计。宿主负责素材下载与鉴权、缓存、海报生成、权限引导、按钮和提示。SDK 负责校验本地素材、平台适配、拉起及回调。首期不做登录授权、后台代发、H5 bridge、作品状态查询、话题/文案预填、挂载小程序、文件附件、极速版适配或 npm 发布操作。
|
|
10
|
+
|
|
11
|
+
## 2. 能力调研与首期范围
|
|
12
|
+
|
|
13
|
+
| 能力 | 官方资料所见 | 产品决策 |
|
|
14
|
+
| --- | --- | --- |
|
|
15
|
+
| 单图、单视频进入编辑 | Android 有明确请求示例;iOS 能力表列出两项,具体请求与素材格式待核对官方包 | P0,Android/iOS 分别真机通过后开放 |
|
|
16
|
+
| 单图进入发布页 | 双端能力表列出;Android 有示例 | P1;验证落地页和回跳后按端启用 |
|
|
17
|
+
| 单视频进入发布页 | Android 文档要求申请权限;双端 FAQ 均说明权限不足或素材超长可能落到剪辑页 | P1,先核实应用权限、落地页与降级行为;不作为 P0 阻塞 |
|
|
18
|
+
| 多图进入编辑 | 双端能力表列出;Android 文档给出 SDK ≥ 3.0.4、快手客户端 ≥ 9.7.20 的该能力门槛 | P0;按选择顺序传入,双端核对最大张数和格式,分别真机通过后开放 |
|
|
19
|
+
| 裁剪、混合素材、智能剪辑 | Android 有相应示例,但示例目标端因功能而异;iOS 能力表列出部分相关能力 | 后续评估,本期不暴露混合素材参数 |
|
|
20
|
+
| 私信分享(好友、群聊、指定人、链接卡片) | 本项目接入场景不支持 | 不纳入范围,不提供 `shareToContacts`,不安排权限申请、联调或验收 |
|
|
21
|
+
| 「转发到日常」 | 当前资料未确认有与抖音日常等价的移动 SDK 能力 | 不提供 |
|
|
22
|
+
| 小程序挂载、话题 | Android 示例的小程序挂载需单独权限;双端 FAQ 说明公开 SDK 不支持发布视频时携带话题 | 不提供;示例中的扩展字段不作为公开契约 |
|
|
23
|
+
|
|
24
|
+
依据:[Android 移动应用接入](https://open.kuaishou.com/platformDocs/develop/mobile-app/android.html)、[iOS 移动应用接入](https://open.kuaishou.com/platformDocs/develop/mobile-app/ios.html)、[Android 开放平台接口页](https://open.kuaishou.com/platform/openApi?group=GROUP_OPEN_PLATFORM&menu=11)、[iOS 开放平台接口页](https://open.kuaishou.com/platform/openApi?group=GROUP_OPEN_PLATFORM&menu=8)。[快手小程序私信分享](https://open.kuaishou.com/docs/develop/functionAccessGuide/share.html)属于小程序场景,不能用来证明原生移动应用的私信权限或卡片类型。
|
|
25
|
+
|
|
26
|
+
## 3. 用户流程与公开 API
|
|
27
|
+
|
|
28
|
+
1. 用户选择本地素材,点击「分享到快手」。宿主按既有隐私同意流程初始化,再查询主站安装状态和对应媒体能力。
|
|
29
|
+
2. 未安装、明确不支持或权限不足时,提示原因并保留当前素材;安装/升级由用户主动选择,不自动跳应用商店。能力未知时不标为可用;已开放的平台可允许用户主动尝试,并显示实际结果。
|
|
30
|
+
3. 宿主显式准备素材,SDK 校验后拉起快手编辑页。用户在快手内操作并可返回今小店。App 回前台不能推断分享成功;等待时可选择「停止等待」,或由超时结束。
|
|
31
|
+
4. 宿主根据回调显示结果。即使 SDK 报告分享成功,也不显示「作品已发布」,不据此写入已发布状态。
|
|
32
|
+
|
|
33
|
+
| API 草案 | 契约 |
|
|
34
|
+
| --- | --- |
|
|
35
|
+
| `configure({ appId, universalLink? })` | 同一配置可重复初始化;等待分享时不能更换配置。iOS 所需的 Universal Link 由宿主提供,具体必填规则按锁定 SDK 定稿。初始化完成不等于平台能力获批。 |
|
|
36
|
+
| `isAppInstalled()` | 只检测快手主站;极速版单独安装不视为主站已安装。 |
|
|
37
|
+
| `getCapabilities()` | 按媒体类型、目标页返回 `supported / unsupported / unknown`;安装状态与能力分开,客户端能力不替代应用权限确认。 |
|
|
38
|
+
| `prepareResources(resources, options?)` | 显式准备本地资源,完成必要的平台适配;如果选定的 iOS 路径确需写相册,宿主须明确选择并先获得所需权限。 |
|
|
39
|
+
| `share({ mediaType, resources, targetPage, timeoutMs? })` | P0 仅接受 `targetPage: 'edit'`。图片接受一张或多张同类型资源,保留传入顺序;视频只接受一个资源;不接受图视频混合。多图能力不支持时明确报错,不截取首张。后续可增加 `publish`;未开放的有效能力明确报错,不静默改成编辑。 |
|
|
40
|
+
| `cancelPendingShare()` | 只终止本地等待,不会关闭快手、撤销分享或删除素材。 |
|
|
41
|
+
|
|
42
|
+
输入拟用 `{ type: 'file', uri }` 与 `{ type: 'photoAsset', localIdentifier }` 的判别联合;第二类是否公开取决于实际 iOS 资源契约。文件入口仅接收支持的本地 URI,不接收 HTTP(S) 媒体地址。SDK 不自行下载、转码、读剪贴板或触发权限弹窗。文档须列出平台资源格式、支持的编码/大小/时长、兼容矩阵及最小可用客户端版本;未知限制以实际 SDK、平台权限和真机结果为准。
|
|
43
|
+
|
|
44
|
+
## 4. 双端接入与回调
|
|
45
|
+
|
|
46
|
+
- Android:单图、多图和单视频编辑分别映射到 `SinglePictureEdit.Req`、`MultiPictureEdit.Req` 和 `SingleVideoEdit.Req`;多图用 `isAppSupportEditMultiPicture` 检查客户端支持情况。通过 `IKwaiOpenAPI` 发送并注册响应监听;为主站配置包可见性。私有文件优先验证 FileProvider 和临时只读授权;URI 方式核对 `isAppSupportUri`,官方文档要求 SDK 至少 3.0.3。当前客户端不支持安全的文件交付方式时明确报错,不静默把素材复制到公共相册。临时资源按验证过的读取时机清理,停止等待后也不能立即删除快手仍可能在读的文件。
|
|
47
|
+
- iOS:依据官方接入文档和 [KwaiSDK-iOS 官方示例](https://github.com/KwaiSocial/KwaiSDK-iOS)核对 Pod、媒体请求类型、支持的资源和回调字段。配置 URL Scheme、查询白名单、Associated Domains 与 AASA,验证 URL 和 Universal Link 路由;保留抖音与 RN Linking 等已有处理链。先验证快手自身的文件/相册要求,不把抖音的 PhotoKit 流程当作快手前提;若需要写相册,明确告知新增资产会保留,不自动删除用户相册内容。
|
|
48
|
+
- 配置与隐私:使用 [快手开放平台](https://open.kuaishou.com/platform)登记移动应用,核对实际包名、签名、Bundle ID、App ID 及环境权限。App Secret 不进入 RN、原生包或示例。记录 SDK 版本、依赖来源、发布许可与隐私披露要求;以正式签名构建验证配置。生产配置或能力未就绪时保留关闭开关。
|
|
49
|
+
|
|
50
|
+
`share` 返回 `{ status, platform, nativeResponse }`;`status` 为 `success / cancelled / failed / unknown`,仅描述可信原生响应。SDK 请求受理只记录为拉起阶段,不能结算为 `success`。取消只有在 SDK 提供明确信号时才映射;未知码返回 `unknown` 并保留可公开读取的原生码和消息,避免将 Android「拒绝当次分享」一律解释为取消。原生响应按端维护映射表,日志不记录绝对素材路径、账号标识或密钥。
|
|
51
|
+
|
|
52
|
+
本地错误包括 `E_NOT_CONFIGURED`、`E_NOT_INSTALLED`、`E_UNSUPPORTED`、`E_INVALID_RESOURCE`、`E_PERMISSION`、`E_BUSY`、`E_LAUNCH_FAILED`、`E_TIMEOUT`、`E_WAIT_CANCELLED`。同一时间只允许一个未结束请求;重复点击返回 `E_BUSY`。验证官方会话或事务字段能否可靠关联回调;去重,忽略过期回调,尤其不能让上一次超时后的回调结算下一次。无法可靠关联时,先阻止复用可能串线的会话并完成专项验证。超时默认值在联调后锁定,用户返回前台不自动判定结果。禁止自动重试;进程被杀后不恢复旧 Promise。
|
|
53
|
+
|
|
54
|
+
## 5. 实施与验收
|
|
55
|
+
|
|
56
|
+
| 阶段 | 产物与通过条件 |
|
|
57
|
+
| --- | --- |
|
|
58
|
+
| 官方能力验证 | 拿到测试应用与 SDK,锁定 Android/iOS 版本;用官方示例分别跑单图、多图、单视频,记录素材要求、目标页、原生回调、可用版本及权限。 |
|
|
59
|
+
| RN 桥接与示例 | 交付 TS API、双端桥接、独立示例和接入 README。README 给出 RN 到原生方法映射、配置与故障排查、资源权限、结果边界。验证当前宿主 RN 0.83 自动链接及 Debug/Release 构建。 |
|
|
60
|
+
| 今小店联调 | 先用开发入口联调,参照抖音测试页提供初始化、安装/能力检测、选图/选视频、查看结果和停止等待。六条主路径(Android/iOS × 单图/多图/单视频)均能进入正确编辑页,测试素材实际可用,多图张数和顺序正确。业务入口在此之后接入,使用中英文文案,并验证已有抖音分享和深链。 |
|
|
61
|
+
| 异常与回归 | 覆盖未安装、仅安装极速版、旧客户端、未登录、超出图片张数限制、图视频混选、无效/不可读素材、权限拒绝、取消/未回跳、重复点击、超时、停止等待后重试、重复/迟到回调、前后台和进程重启;有相册适配时覆盖有限授权。Android 验证私有 URI 访问和清理,iOS 验证双向跳转和签名配置。 |
|
|
62
|
+
| 灰度门槛 | 按系统和能力开启入口;记录拉起、SDK 回调和本地超时三种不同事件,观察失败原因。仅开启已通过真机验证的能力,未验证能力留在开发入口。 |
|
|
63
|
+
|
|
64
|
+
本地需求基线:同级抖音 SDK 项目的 `docs/PRD.md`,以及今小店 `app/container/mine/DouyinShareTest.tsx`、`README.md` 中的真机联调说明。本次仅完成文档调研,尚未验证快手应用权限、SDK 二进制或真机行为。
|
package/README.md
CHANGED
|
@@ -1,3 +1,60 @@
|
|
|
1
|
-
#
|
|
1
|
+
# React Native 快手 Open SDK
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
为 React Native 0.83 封装快手主站作品分享。支持单图、多图及单视频编辑请求。所用原生 SDK 为 Android 3.7.6 和 iOS 3.7.3。产品范围见 [PRD](PRD.md)。
|
|
4
|
+
|
|
5
|
+
## 安装与配置
|
|
6
|
+
|
|
7
|
+
从本地使用时,先在 SDK 根目录执行 `npm install && npm run build`,再在宿主安装此目录作为依赖。React Native 自动链接原生模块。应用配置完成后重新构建宿主。
|
|
8
|
+
|
|
9
|
+
- Android 分享使用 `configure({ appId })` 传入的运行时 App ID,可由接口下发。宿主无需配置 `KWAI_APP_ID`;桥接库在 Manifest 中为空缺的官方 AAR App ID 元数据提供空字符串默认值,每次分享前调用官方 `updateKwaiAppId(appId)`。已有宿主可继续显式声明 Manifest App ID,分享以运行时值为准;仅配置 Gradle 占位符时可删除该配置。保留 Maven Central。官方依赖提供按宿主包名注册的回跳 Activity 和别名,桥接库声明主站包可见性及 FileProvider。本库未封装快手账号授权登录,该能力需由宿主显式覆盖上述授权元数据,并按官方授权文档接入。
|
|
10
|
+
- iOS 执行 `pod install`。将 App ID 加到 URL Types,并按官方文档合并 `LSApplicationQueriesSchemes`、Associated Domains 和 AASA。将快手登记的 HTTPS Universal Link(结尾为 `/`)传给 `configure`。在宿主的 AppDelegate 或 SceneDelegate 中将匹配快手回跳的 URL 和 Universal Link 交给 `[RNKuaishouOpenSDK handleOpenURL:url]`、`[RNKuaishouOpenSDK handleOpenUniversalLink:userActivity]`。其他链接继续走宿主现有处理链。使用相册素材前,由宿主声明 `NSPhotoLibraryUsageDescription` 并取得所需访问权限。
|
|
11
|
+
- iOS 官方 Pod 使用静态库。用 arm64 真机联调,模拟器不能验证快手分享。3.7.3 头文件标注视频编辑需要申请权限。
|
|
12
|
+
- 测试和发布构建均使用实际登记的应用标识。应用凭据中的 App Secret 不需要传给客户端。
|
|
13
|
+
|
|
14
|
+
## 调用
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import Kuaishou from '@code_shuai/react-native-kuaishou-open-sdk'
|
|
18
|
+
|
|
19
|
+
await Kuaishou.configure({
|
|
20
|
+
appId: 'YOUR_KUAISHOU_APP_ID',
|
|
21
|
+
universalLink: 'https://your-domain.example/kuaishou/',
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
const capabilities = await Kuaishou.getCapabilities()
|
|
25
|
+
const resources = await Kuaishou.prepareResources(selectedResources, {
|
|
26
|
+
mediaType: 'image',
|
|
27
|
+
saveToPhotos: false,
|
|
28
|
+
})
|
|
29
|
+
const result = await Kuaishou.share({
|
|
30
|
+
mediaType: 'image',
|
|
31
|
+
resources,
|
|
32
|
+
targetPage: 'edit',
|
|
33
|
+
})
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
| API | 行为 |
|
|
37
|
+
| --- | --- |
|
|
38
|
+
| `isAppInstalled()` | 检查快手主站 |
|
|
39
|
+
| `getCapabilities()` | 提供 `imageEdit`、`multiImageEdit`、`videoEdit` 三项能力。SDK 无法单独检测时返回 `unknown`。客户端检测不代表应用权限。 |
|
|
40
|
+
| `prepareResources()` | Android 接受 `{ type: 'file', uri }`,其中 URI 为 `file://` 或可读的 `content://`。iOS 接受 `{ type: 'photoAsset', localIdentifier }`,也可显式设置 `saveToPhotos: true` 导入可读的本地文件。写入的照片由用户管理。 |
|
|
41
|
+
| `share()` | 保留输入顺序。Android 使用 `SinglePictureEdit`、`MultiPictureEdit`、`SingleVideoEdit`。iOS 使用 `KSShareMediaRequest` 及图片/视频编辑类型。图片至少一张,视频仅一条。多图上限和媒体兼容性待真机确认。Android 发送时准备缓存和临时只读授权,过期文件在后续请求时清理。 |
|
|
42
|
+
| `cancelPendingShare()` | 停止本地等待。返回是否存在待处理请求。 |
|
|
43
|
+
|
|
44
|
+
同一配置可重复初始化,Android 在没有待处理分享时可以更换 App ID,等待分享期间更换会返回 `E_BUSY`。接口下发的 App ID 仍需在开放平台登记当前包名、签名及分享权限。
|
|
45
|
+
|
|
46
|
+
一次只允许一个请求,默认等待 120 秒,可通过 `timeoutMs` 调整。收到已关联的 SDK 响应后返回 `status`、`platform`、`nativeResponse`。SDK 报告成功不表示作品已发布。SDK 没有明确的媒体取消信号时,不将拒绝或未回跳映射为用户取消。参数无效、未安装、能力不支持、权限不足、拉起失败、并发和超时等本地错误通过 Promise 拒绝返回,按错误的 `code` 处理。进程被杀后无法恢复旧请求。
|
|
47
|
+
|
|
48
|
+
调用示例见 [shareMedia.ts](example/shareMedia.ts)。原生配置见 [快手 Android 文档](https://open.kuaishou.com/platformDocs/develop/mobile-app/android.html)与 [快手 iOS 文档](https://open.kuaishou.com/platformDocs/develop/mobile-app/ios.html)。
|
|
49
|
+
|
|
50
|
+
## npm 打包与发布
|
|
51
|
+
|
|
52
|
+
在 SDK 根目录执行以下命令。
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
npm install
|
|
56
|
+
npm run release:check
|
|
57
|
+
npm pack
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
`release:check` 会构建 TypeScript、运行测试,并检查 npm 包是否包含 JS、类型声明和双端原生代码。 `npm pack` 在生成本地 tarball 前重新构建。准备发布公开包时,使用 `npm publish --access public`,npm 会先执行同一套发布检查。
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
apply plugin: 'com.android.library'
|
|
2
|
+
|
|
3
|
+
android {
|
|
4
|
+
namespace 'com.finstao.kuaishou'
|
|
5
|
+
compileSdkVersion rootProject.ext.has('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 35
|
|
6
|
+
defaultConfig {
|
|
7
|
+
minSdkVersion 24
|
|
8
|
+
consumerProguardFiles 'consumer-rules.pro'
|
|
9
|
+
}
|
|
10
|
+
compileOptions {
|
|
11
|
+
sourceCompatibility JavaVersion.VERSION_17
|
|
12
|
+
targetCompatibility JavaVersion.VERSION_17
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
dependencies {
|
|
17
|
+
implementation 'com.facebook.react:react-android'
|
|
18
|
+
implementation 'androidx.core:core:1.13.1'
|
|
19
|
+
implementation 'com.github.kwaisocial:kwai-opensdk-withauth:3.7.6'
|
|
20
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
<manifest
|
|
2
|
+
xmlns:android="http://schemas.android.com/apk/res/android"
|
|
3
|
+
xmlns:tools="http://schemas.android.com/tools">
|
|
4
|
+
<queries>
|
|
5
|
+
<package android:name="com.smile.gifmaker" />
|
|
6
|
+
</queries>
|
|
7
|
+
<application>
|
|
8
|
+
<!-- Sharing receives its App ID at runtime. Override the official AAR placeholders. -->
|
|
9
|
+
<meta-data
|
|
10
|
+
android:name="APP_ID"
|
|
11
|
+
android:value=""
|
|
12
|
+
tools:replace="android:value" />
|
|
13
|
+
<meta-data
|
|
14
|
+
android:name="KWAI_APP_ID"
|
|
15
|
+
android:value=""
|
|
16
|
+
tools:replace="android:value" />
|
|
17
|
+
<provider
|
|
18
|
+
android:name=".KuaishouFileProvider"
|
|
19
|
+
android:authorities="${applicationId}.rn-kuaishou.files"
|
|
20
|
+
android:exported="false"
|
|
21
|
+
android:grantUriPermissions="true">
|
|
22
|
+
<meta-data
|
|
23
|
+
android:name="android.support.FILE_PROVIDER_PATHS"
|
|
24
|
+
android:resource="@xml/rn_kuaishou_paths" />
|
|
25
|
+
</provider>
|
|
26
|
+
</application>
|
|
27
|
+
</manifest>
|
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
package com.finstao.kuaishou;
|
|
2
|
+
|
|
3
|
+
import android.app.Activity;
|
|
4
|
+
import android.content.Intent;
|
|
5
|
+
import android.content.pm.PackageManager;
|
|
6
|
+
import android.net.Uri;
|
|
7
|
+
import android.os.Handler;
|
|
8
|
+
import android.os.Looper;
|
|
9
|
+
import android.webkit.MimeTypeMap;
|
|
10
|
+
|
|
11
|
+
import androidx.core.content.FileProvider;
|
|
12
|
+
|
|
13
|
+
import com.facebook.react.bridge.Arguments;
|
|
14
|
+
import com.facebook.react.bridge.Promise;
|
|
15
|
+
import com.facebook.react.bridge.ReactApplicationContext;
|
|
16
|
+
import com.facebook.react.bridge.ReactContextBaseJavaModule;
|
|
17
|
+
import com.facebook.react.bridge.ReactMethod;
|
|
18
|
+
import com.facebook.react.bridge.ReadableArray;
|
|
19
|
+
import com.facebook.react.bridge.ReadableMap;
|
|
20
|
+
import com.facebook.react.bridge.WritableMap;
|
|
21
|
+
import com.kwai.opensdk.sdk.constants.KwaiPlatform;
|
|
22
|
+
import com.kwai.opensdk.sdk.model.base.BaseReq;
|
|
23
|
+
import com.kwai.opensdk.sdk.model.base.BaseResp;
|
|
24
|
+
import com.kwai.opensdk.sdk.model.base.OpenSdkConfig;
|
|
25
|
+
import com.kwai.opensdk.sdk.model.postshare.MultiPictureEdit;
|
|
26
|
+
import com.kwai.opensdk.sdk.model.postshare.PostShareMediaInfo;
|
|
27
|
+
import com.kwai.opensdk.sdk.model.postshare.SinglePictureEdit;
|
|
28
|
+
import com.kwai.opensdk.sdk.model.postshare.SingleVideoEdit;
|
|
29
|
+
import com.kwai.opensdk.sdk.openapi.IKwaiAPIEventListener;
|
|
30
|
+
import com.kwai.opensdk.sdk.openapi.KwaiOpenAPI;
|
|
31
|
+
|
|
32
|
+
import java.io.File;
|
|
33
|
+
import java.io.FileOutputStream;
|
|
34
|
+
import java.io.IOException;
|
|
35
|
+
import java.io.InputStream;
|
|
36
|
+
import java.util.ArrayList;
|
|
37
|
+
import java.util.Locale;
|
|
38
|
+
import java.util.UUID;
|
|
39
|
+
import java.util.concurrent.Executors;
|
|
40
|
+
import java.util.concurrent.ExecutorService;
|
|
41
|
+
|
|
42
|
+
public final class KuaishouModule extends ReactContextBaseJavaModule {
|
|
43
|
+
private static final String TARGET = "com.smile.gifmaker";
|
|
44
|
+
private static final int READ_GRANT = Intent.FLAG_GRANT_READ_URI_PERMISSION;
|
|
45
|
+
private static final long RETENTION_MS = 24L * 60 * 60 * 1000;
|
|
46
|
+
|
|
47
|
+
private final ReactApplicationContext context;
|
|
48
|
+
private final Handler main = new Handler(Looper.getMainLooper());
|
|
49
|
+
private final ExecutorService files = Executors.newSingleThreadExecutor();
|
|
50
|
+
private String appId;
|
|
51
|
+
private Pending pending;
|
|
52
|
+
private String lastSessionId;
|
|
53
|
+
private boolean invalidated;
|
|
54
|
+
|
|
55
|
+
private static final class Pending {
|
|
56
|
+
final Promise promise;
|
|
57
|
+
final String token = UUID.randomUUID().toString();
|
|
58
|
+
KwaiOpenAPI api;
|
|
59
|
+
IKwaiAPIEventListener listener;
|
|
60
|
+
Runnable timeout;
|
|
61
|
+
|
|
62
|
+
Pending(Promise promise) {
|
|
63
|
+
this.promise = promise;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
KuaishouModule(ReactApplicationContext context) {
|
|
68
|
+
super(context);
|
|
69
|
+
this.context = context;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
@Override
|
|
73
|
+
public String getName() {
|
|
74
|
+
return "RNKuaishouOpenSDK";
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
@ReactMethod
|
|
78
|
+
public void configure(ReadableMap config, Promise promise) {
|
|
79
|
+
main.post(() -> {
|
|
80
|
+
try {
|
|
81
|
+
String id = config.getString("appId");
|
|
82
|
+
if (id == null || id.trim().isEmpty()) {
|
|
83
|
+
promise.reject("E_INVALID_CONFIG", "A Kuaishou App ID is required");
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (pending != null && !id.equals(appId)) {
|
|
87
|
+
promise.reject("E_BUSY", "A share is pending");
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
appId = id;
|
|
91
|
+
promise.resolve(null);
|
|
92
|
+
}
|
|
93
|
+
catch (Exception error) {
|
|
94
|
+
promise.reject("E_INVALID_CONFIG", "A valid Kuaishou App ID is required");
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
private boolean installed() {
|
|
100
|
+
try {
|
|
101
|
+
return context.getPackageManager().getApplicationInfo(TARGET, 0).enabled;
|
|
102
|
+
}
|
|
103
|
+
catch (PackageManager.NameNotFoundException error) {
|
|
104
|
+
return false;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
@ReactMethod
|
|
109
|
+
public void isAppInstalled(Promise promise) {
|
|
110
|
+
promise.resolve(installed());
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
private void targetMainApp(BaseReq request) {
|
|
114
|
+
request.setPlatformArray(new String[] { KwaiPlatform.Platform.KWAI_APP });
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
@ReactMethod
|
|
118
|
+
public void getCapabilities(Promise promise) {
|
|
119
|
+
main.post(() -> {
|
|
120
|
+
WritableMap result = Arguments.createMap();
|
|
121
|
+
boolean present = installed();
|
|
122
|
+
String basic = present ? "unknown" : "unsupported";
|
|
123
|
+
result.putString("imageEdit", basic);
|
|
124
|
+
result.putString("videoEdit", basic);
|
|
125
|
+
String multi = basic;
|
|
126
|
+
if (present) {
|
|
127
|
+
try {
|
|
128
|
+
MultiPictureEdit.Req request = new MultiPictureEdit.Req();
|
|
129
|
+
targetMainApp(request);
|
|
130
|
+
multi = new KwaiOpenAPI(context).isAppSupportEditMultiPicture(context, request)
|
|
131
|
+
? "supported" : "unsupported";
|
|
132
|
+
}
|
|
133
|
+
catch (RuntimeException ignored) {
|
|
134
|
+
// No reliable capability result.
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
result.putString("multiImageEdit", multi);
|
|
138
|
+
promise.resolve(result);
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
@ReactMethod
|
|
143
|
+
public void prepareResources(ReadableMap request, Promise promise) {
|
|
144
|
+
ReadableArray resources = request.getArray("resources");
|
|
145
|
+
for (int i = 0; i < resources.size(); i++) {
|
|
146
|
+
if (!"file".equals(resources.getMap(i).getString("type"))) {
|
|
147
|
+
promise.reject("E_INVALID_RESOURCE", "Android requires local file URIs");
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
promise.resolve(Arguments.makeNativeArray(resources.toArrayList()));
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
@ReactMethod
|
|
155
|
+
public void share(ReadableMap request, Promise promise) {
|
|
156
|
+
main.post(() -> {
|
|
157
|
+
if (invalidated) {
|
|
158
|
+
promise.reject("E_LAUNCH_FAILED", "Module is unavailable");
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
if (appId == null) {
|
|
162
|
+
promise.reject("E_NOT_CONFIGURED", "Call configure first");
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
if (pending != null) {
|
|
166
|
+
promise.reject("E_BUSY", "A share is pending");
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
if (!installed()) {
|
|
170
|
+
promise.reject("E_NOT_INSTALLED", "Kuaishou is not installed");
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
Pending work = new Pending(promise);
|
|
175
|
+
pending = work;
|
|
176
|
+
work.timeout = () -> reject(work, "E_TIMEOUT", "Share response timed out");
|
|
177
|
+
main.postDelayed(work.timeout, request.getInt("timeoutMs"));
|
|
178
|
+
boolean image = "image".equals(request.getString("mediaType"));
|
|
179
|
+
ReadableArray resources = request.getArray("resources");
|
|
180
|
+
ArrayList<String> sources = new ArrayList<>();
|
|
181
|
+
for (int i = 0; i < resources.size(); i++) {
|
|
182
|
+
ReadableMap resource = resources.getMap(i);
|
|
183
|
+
if (!"file".equals(resource.getString("type"))) {
|
|
184
|
+
reject(work, "E_INVALID_RESOURCE", "Android requires local file URIs");
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
sources.add(resource.getString("uri"));
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
files.execute(() -> {
|
|
191
|
+
File root = new File(context.getCacheDir(), "rn-kuaishou");
|
|
192
|
+
File folder = new File(root, work.token);
|
|
193
|
+
try {
|
|
194
|
+
purgeExpired(root);
|
|
195
|
+
if (!folder.mkdirs()) {
|
|
196
|
+
throw new IOException("Cache directory unavailable");
|
|
197
|
+
}
|
|
198
|
+
ArrayList<String> paths = new ArrayList<>();
|
|
199
|
+
for (int i = 0; i < sources.size(); i++) {
|
|
200
|
+
paths.add(stage(folder, sources.get(i), i, image).toString());
|
|
201
|
+
}
|
|
202
|
+
main.post(() -> {
|
|
203
|
+
if (!launch(work, paths, image)) {
|
|
204
|
+
if (!invalidated) {
|
|
205
|
+
files.execute(() -> deleteFolder(folder));
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
catch (Exception error) {
|
|
211
|
+
deleteFolder(folder);
|
|
212
|
+
main.post(() -> reject(work, "E_INVALID_RESOURCE", "Could not read share media"));
|
|
213
|
+
}
|
|
214
|
+
});
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
private Uri stage(File folder, String source, int index, boolean image) throws IOException {
|
|
219
|
+
Uri uri = Uri.parse(source);
|
|
220
|
+
String mime = context.getContentResolver().getType(uri);
|
|
221
|
+
String name = uri.getLastPathSegment();
|
|
222
|
+
String extension = name == null ? "" : name.replaceFirst("^.*\\.", "").toLowerCase(Locale.ROOT);
|
|
223
|
+
var types = MimeTypeMap.getSingleton();
|
|
224
|
+
if (mime == null || "application/octet-stream".equals(mime)) {
|
|
225
|
+
mime = types.getMimeTypeFromExtension(extension);
|
|
226
|
+
}
|
|
227
|
+
if (mime == null || !mime.startsWith(image ? "image/" : "video/")) {
|
|
228
|
+
throw new IOException("Media type does not match request");
|
|
229
|
+
}
|
|
230
|
+
extension = types.getExtensionFromMimeType(mime);
|
|
231
|
+
if (extension == null) {
|
|
232
|
+
throw new IOException("Unsupported media format");
|
|
233
|
+
}
|
|
234
|
+
File file = new File(folder, index + "." + extension);
|
|
235
|
+
try (InputStream input = context.getContentResolver().openInputStream(uri);
|
|
236
|
+
FileOutputStream output = new FileOutputStream(file)) {
|
|
237
|
+
if (input == null) {
|
|
238
|
+
throw new IOException("No media stream");
|
|
239
|
+
}
|
|
240
|
+
byte[] buffer = new byte[65536];
|
|
241
|
+
int count;
|
|
242
|
+
while ((count = input.read(buffer)) != -1) {
|
|
243
|
+
output.write(buffer, 0, count);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
if (file.length() == 0) {
|
|
247
|
+
throw new IOException("Empty media");
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
return FileProvider.getUriForFile(
|
|
251
|
+
context, context.getPackageName() + ".rn-kuaishou.files", file
|
|
252
|
+
);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
private boolean launch(Pending work, ArrayList<String> paths, boolean image) {
|
|
256
|
+
if (pending != work) {
|
|
257
|
+
return false;
|
|
258
|
+
}
|
|
259
|
+
Activity activity = getCurrentActivity();
|
|
260
|
+
if (activity == null || activity.isFinishing()) {
|
|
261
|
+
reject(work, "E_LAUNCH_FAILED", "No active host activity");
|
|
262
|
+
return false;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
try {
|
|
266
|
+
KwaiOpenAPI api = new KwaiOpenAPI(context);
|
|
267
|
+
work.api = api;
|
|
268
|
+
// The sharing API uses this runtime ID instead of the Manifest fallback.
|
|
269
|
+
api.updateKwaiAppId(appId);
|
|
270
|
+
api.setOpenSdkConfig(new OpenSdkConfig.Builder()
|
|
271
|
+
.setGoToMargetAppNotInstall(false)
|
|
272
|
+
.setGoToMargetAppVersionNotSupport(false)
|
|
273
|
+
.setSetClearTaskFlag(false)
|
|
274
|
+
.setShowDefaultLoading(false)
|
|
275
|
+
.build());
|
|
276
|
+
|
|
277
|
+
PostShareMediaInfo media = new PostShareMediaInfo();
|
|
278
|
+
media.mMultiMediaAssets = paths;
|
|
279
|
+
// Let Kuaishou route a video to its clip page when needed.
|
|
280
|
+
media.mDisableFallback = image;
|
|
281
|
+
BaseReq request;
|
|
282
|
+
boolean multi = image && paths.size() > 1;
|
|
283
|
+
if (multi) {
|
|
284
|
+
MultiPictureEdit.Req edit = new MultiPictureEdit.Req();
|
|
285
|
+
edit.mediaInfo = media;
|
|
286
|
+
request = edit;
|
|
287
|
+
}
|
|
288
|
+
else if (image) {
|
|
289
|
+
SinglePictureEdit.Req edit = new SinglePictureEdit.Req();
|
|
290
|
+
edit.mediaInfo = media;
|
|
291
|
+
request = edit;
|
|
292
|
+
}
|
|
293
|
+
else {
|
|
294
|
+
SingleVideoEdit.Req edit = new SingleVideoEdit.Req();
|
|
295
|
+
edit.mediaInfo = media;
|
|
296
|
+
request = edit;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
targetMainApp(request);
|
|
300
|
+
request.transaction = work.token;
|
|
301
|
+
request.sessionId = api.getOpenAPISessionId();
|
|
302
|
+
// SDK session IDs are timestamp based. Avoid reusing the previous session.
|
|
303
|
+
if (request.sessionId.equals(lastSessionId)) {
|
|
304
|
+
reject(work, "E_BUSY", "Please retry the share");
|
|
305
|
+
return false;
|
|
306
|
+
}
|
|
307
|
+
lastSessionId = request.sessionId;
|
|
308
|
+
if (!api.isAppSupportUri(context, request)
|
|
309
|
+
|| (multi && !api.isAppSupportEditMultiPicture(context, request))) {
|
|
310
|
+
reject(work, "E_UNSUPPORTED", "Installed Kuaishou cannot accept this share");
|
|
311
|
+
return false;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
work.listener = response -> main.post(() -> receive(work, response));
|
|
315
|
+
api.addKwaiAPIEventListerer(work.listener);
|
|
316
|
+
for (String path : paths) {
|
|
317
|
+
context.grantUriPermission(TARGET, Uri.parse(path), READ_GRANT);
|
|
318
|
+
}
|
|
319
|
+
if (api.sendReq(request, activity)) {
|
|
320
|
+
return true;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
catch (RuntimeException ignored) {
|
|
324
|
+
// Return a local launch error without logging media paths.
|
|
325
|
+
}
|
|
326
|
+
reject(work, "E_LAUNCH_FAILED", "Kuaishou did not accept the request");
|
|
327
|
+
return false;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
private void receive(Pending work, BaseResp response) {
|
|
331
|
+
if (pending != work || response == null
|
|
332
|
+
|| !work.api.getOpenAPISessionId().equals(response.sessionId)
|
|
333
|
+
|| (response.transaction != null && !response.transaction.isEmpty()
|
|
334
|
+
&& !work.token.equals(response.transaction))) {
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
WritableMap nativeResponse = Arguments.createMap();
|
|
339
|
+
nativeResponse.putInt("code", response.errorCode);
|
|
340
|
+
nativeResponse.putString("message", response.errorMsg);
|
|
341
|
+
WritableMap result = Arguments.createMap();
|
|
342
|
+
String status = "unknown";
|
|
343
|
+
if (response.errorCode == 1) {
|
|
344
|
+
status = "success";
|
|
345
|
+
}
|
|
346
|
+
else if (response.errorCode == -1
|
|
347
|
+
|| (response.errorCode <= -1005 && response.errorCode >= -1019)) {
|
|
348
|
+
status = "failed";
|
|
349
|
+
}
|
|
350
|
+
result.putString("status", status);
|
|
351
|
+
result.putString("platform", "android");
|
|
352
|
+
result.putMap("nativeResponse", nativeResponse);
|
|
353
|
+
clear(work);
|
|
354
|
+
work.promise.resolve(result);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
private void clear(Pending work) {
|
|
358
|
+
pending = null;
|
|
359
|
+
main.removeCallbacks(work.timeout);
|
|
360
|
+
if (work.listener != null) {
|
|
361
|
+
work.api.removeKwaiAPIEventListerer();
|
|
362
|
+
work.listener = null;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
private void reject(Pending work, String code, String message) {
|
|
367
|
+
if (pending == work) {
|
|
368
|
+
clear(work);
|
|
369
|
+
work.promise.reject(code, message);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
@ReactMethod
|
|
374
|
+
public void cancelPendingShare(Promise promise) {
|
|
375
|
+
main.post(() -> {
|
|
376
|
+
Pending work = pending;
|
|
377
|
+
if (work != null) {
|
|
378
|
+
reject(work, "E_WAIT_CANCELLED", "Stopped waiting for Kuaishou");
|
|
379
|
+
}
|
|
380
|
+
promise.resolve(work != null);
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
@Override
|
|
385
|
+
public void invalidate() {
|
|
386
|
+
main.post(() -> {
|
|
387
|
+
invalidated = true;
|
|
388
|
+
files.shutdown();
|
|
389
|
+
if (pending != null) {
|
|
390
|
+
reject(pending, "E_WAIT_CANCELLED", "React Native module was invalidated");
|
|
391
|
+
}
|
|
392
|
+
});
|
|
393
|
+
super.invalidate();
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
private void purgeExpired(File root) {
|
|
397
|
+
File[] folders = root.listFiles();
|
|
398
|
+
if (folders == null) {
|
|
399
|
+
return;
|
|
400
|
+
}
|
|
401
|
+
long cutoff = System.currentTimeMillis() - RETENTION_MS;
|
|
402
|
+
for (File folder : folders) {
|
|
403
|
+
if (folder.lastModified() < cutoff) {
|
|
404
|
+
deleteFolder(folder);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
private void deleteFolder(File folder) {
|
|
410
|
+
File[] assets = folder.listFiles();
|
|
411
|
+
if (assets != null) {
|
|
412
|
+
for (File asset : assets) {
|
|
413
|
+
Uri uri = FileProvider.getUriForFile(
|
|
414
|
+
context, context.getPackageName() + ".rn-kuaishou.files", asset
|
|
415
|
+
);
|
|
416
|
+
context.revokeUriPermission(TARGET, uri, READ_GRANT);
|
|
417
|
+
asset.delete();
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
folder.delete();
|
|
421
|
+
}
|
|
422
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
package com.finstao.kuaishou;
|
|
2
|
+
|
|
3
|
+
import com.facebook.react.ReactPackage;
|
|
4
|
+
import com.facebook.react.bridge.NativeModule;
|
|
5
|
+
import com.facebook.react.bridge.ReactApplicationContext;
|
|
6
|
+
import com.facebook.react.uimanager.ViewManager;
|
|
7
|
+
import java.util.Collections;
|
|
8
|
+
import java.util.List;
|
|
9
|
+
|
|
10
|
+
public final class KuaishouPackage implements ReactPackage {
|
|
11
|
+
@Override
|
|
12
|
+
public List<NativeModule> createNativeModules(ReactApplicationContext context) {
|
|
13
|
+
return Collections.singletonList(new KuaishouModule(context));
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
@Override
|
|
17
|
+
public List<ViewManager> createViewManagers(ReactApplicationContext context) {
|
|
18
|
+
return Collections.emptyList();
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import Kuaishou, {
|
|
2
|
+
type Configuration,
|
|
3
|
+
type MediaType,
|
|
4
|
+
type Resource,
|
|
5
|
+
} from '@code_shuai/react-native-kuaishou-open-sdk'
|
|
6
|
+
|
|
7
|
+
export async function shareMedia(
|
|
8
|
+
configuration: Configuration,
|
|
9
|
+
mediaType: MediaType,
|
|
10
|
+
resources: readonly Resource[],
|
|
11
|
+
saveToPhotos = false,
|
|
12
|
+
) {
|
|
13
|
+
await Kuaishou.configure(configuration)
|
|
14
|
+
const prepared = await Kuaishou.prepareResources(resources, { mediaType, saveToPhotos })
|
|
15
|
+
return Kuaishou.share({ mediaType, resources: prepared, targetPage: 'edit' })
|
|
16
|
+
}
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
#import "RNKuaishouOpenSDK.h"
|
|
2
|
+
|
|
3
|
+
#import <Photos/Photos.h>
|
|
4
|
+
#import <KwaiSDK/KSApi.h>
|
|
5
|
+
|
|
6
|
+
@interface RNKuaishouOpenSDK () <KSApiDelegate>
|
|
7
|
+
@property (nonatomic, copy) NSString *appId;
|
|
8
|
+
@property (nonatomic, copy) NSString *universalLink;
|
|
9
|
+
@property (nonatomic, copy) NSString *pendingState;
|
|
10
|
+
@property (nonatomic, copy) RCTPromiseResolveBlock pendingResolve;
|
|
11
|
+
@property (nonatomic, copy) RCTPromiseRejectBlock pendingReject;
|
|
12
|
+
@property (nonatomic, copy) dispatch_block_t timeout;
|
|
13
|
+
@end
|
|
14
|
+
|
|
15
|
+
@implementation RNKuaishouOpenSDK
|
|
16
|
+
|
|
17
|
+
RCT_EXPORT_MODULE()
|
|
18
|
+
|
|
19
|
+
+ (BOOL)requiresMainQueueSetup {
|
|
20
|
+
return NO;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
- (dispatch_queue_t)methodQueue {
|
|
24
|
+
return dispatch_get_main_queue();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
+ (BOOL)handleOpenURL:(NSURL *)url {
|
|
28
|
+
return [KSApi handleOpenURL:url];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
+ (BOOL)handleOpenUniversalLink:(NSUserActivity *)userActivity {
|
|
32
|
+
return [KSApi handleOpenUniversalLink:userActivity];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
RCT_EXPORT_METHOD(configure:(NSDictionary *)config
|
|
36
|
+
resolve:(RCTPromiseResolveBlock)resolve
|
|
37
|
+
reject:(RCTPromiseRejectBlock)reject) {
|
|
38
|
+
NSString *appId = config[@"appId"];
|
|
39
|
+
NSString *link = [config[@"universalLink"] isKindOfClass:NSString.class]
|
|
40
|
+
? config[@"universalLink"] : nil;
|
|
41
|
+
NSURLComponents *url = [NSURLComponents componentsWithString:link ?: @""];
|
|
42
|
+
if (![url.scheme.lowercaseString isEqualToString:@"https"] || !url.host.length
|
|
43
|
+
|| ![url.path hasSuffix:@"/"] || url.query != nil || url.fragment != nil) {
|
|
44
|
+
reject(@"E_INVALID_CONFIG", @"iOS requires an HTTPS Universal Link ending in /", nil);
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
if ([appId isEqualToString:self.appId] && [link isEqualToString:self.universalLink]) {
|
|
48
|
+
resolve(nil);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
if (self.pendingState) {
|
|
52
|
+
reject(@"E_BUSY", @"A share is pending", nil);
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
if (![KSApi registerApp:appId universalLink:link delegate:self]) {
|
|
56
|
+
reject(@"E_INVALID_CONFIG", @"Kuaishou SDK registration failed", nil);
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
self.appId = appId;
|
|
60
|
+
self.universalLink = link;
|
|
61
|
+
resolve(nil);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
RCT_EXPORT_METHOD(isAppInstalled:(RCTPromiseResolveBlock)resolve
|
|
65
|
+
reject:(RCTPromiseRejectBlock)reject) {
|
|
66
|
+
resolve(@([KSApi isAppInstalledFor:KSApiApplication_Kwai]));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
RCT_EXPORT_METHOD(getCapabilities:(RCTPromiseResolveBlock)resolve
|
|
70
|
+
reject:(RCTPromiseRejectBlock)reject) {
|
|
71
|
+
BOOL available = [KSApi isAppInstalledFor:KSApiApplication_Kwai] && [KSApi isKSAppSupportMediaApiV2];
|
|
72
|
+
resolve(@{
|
|
73
|
+
@"imageEdit": available ? @"supported" : @"unsupported",
|
|
74
|
+
@"multiImageEdit": available ? @"unknown" : @"unsupported",
|
|
75
|
+
@"videoEdit": available ? @"unknown" : @"unsupported",
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
- (BOOL)canReadPhotos {
|
|
80
|
+
PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatusForAccessLevel:PHAccessLevelReadWrite];
|
|
81
|
+
return status == PHAuthorizationStatusAuthorized || status == PHAuthorizationStatusLimited;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
- (BOOL)validAsset:(NSString *)identifier image:(BOOL)image {
|
|
85
|
+
PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[identifier] options:nil].firstObject;
|
|
86
|
+
return asset && asset.mediaType == (image ? PHAssetMediaTypeImage : PHAssetMediaTypeVideo);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
RCT_EXPORT_METHOD(prepareResources:(NSDictionary *)request
|
|
90
|
+
resolve:(RCTPromiseResolveBlock)resolve
|
|
91
|
+
reject:(RCTPromiseRejectBlock)reject) {
|
|
92
|
+
if (![self canReadPhotos]) {
|
|
93
|
+
reject(@"E_PERMISSION", @"Grant photo library read/write access before preparing media", nil);
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
BOOL image = [request[@"mediaType"] isEqual:@"image"];
|
|
97
|
+
BOOL save = [request[@"saveToPhotos"] boolValue];
|
|
98
|
+
NSArray<NSDictionary *> *resources = request[@"resources"];
|
|
99
|
+
NSMutableArray *prepared = [resources mutableCopy];
|
|
100
|
+
NSMutableDictionary<NSNumber *, NSURL *> *files = [NSMutableDictionary dictionary];
|
|
101
|
+
|
|
102
|
+
for (NSUInteger i = 0; i < resources.count; i++) {
|
|
103
|
+
NSDictionary *resource = resources[i];
|
|
104
|
+
if ([resource[@"type"] isEqual:@"photoAsset"]) {
|
|
105
|
+
if (![self validAsset:resource[@"localIdentifier"] image:image]) {
|
|
106
|
+
reject(@"E_INVALID_RESOURCE", @"Photo asset is unavailable or has the wrong media type", nil);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
NSURL *url = [NSURL URLWithString:resource[@"uri"]];
|
|
113
|
+
if (!save || !url.isFileURL || ![[NSFileManager defaultManager] isReadableFileAtPath:url.path]) {
|
|
114
|
+
reject(@"E_INVALID_RESOURCE", @"Choose photo assets or explicitly prepare readable files", nil);
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
files[@(i)] = url;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if (!files.count) {
|
|
121
|
+
resolve(prepared);
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
__block BOOL missingAsset = NO;
|
|
126
|
+
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
|
|
127
|
+
[files enumerateKeysAndObjectsUsingBlock:^(NSNumber *index, NSURL *url, BOOL *stop) {
|
|
128
|
+
PHAssetChangeRequest *change = image
|
|
129
|
+
? [PHAssetChangeRequest creationRequestForAssetFromImageAtFileURL:url]
|
|
130
|
+
: [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:url];
|
|
131
|
+
NSString *identifier = change.placeholderForCreatedAsset.localIdentifier;
|
|
132
|
+
if (identifier.length) {
|
|
133
|
+
prepared[index.unsignedIntegerValue] = @{@"type": @"photoAsset", @"localIdentifier": identifier};
|
|
134
|
+
}
|
|
135
|
+
else {
|
|
136
|
+
missingAsset = YES;
|
|
137
|
+
}
|
|
138
|
+
}];
|
|
139
|
+
} completionHandler:^(BOOL success, NSError *error) {
|
|
140
|
+
if (!success || missingAsset) {
|
|
141
|
+
reject(@"E_INVALID_RESOURCE", @"Could not prepare photo library assets", nil);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
resolve(prepared);
|
|
145
|
+
}];
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
RCT_EXPORT_METHOD(share:(NSDictionary *)request
|
|
149
|
+
resolve:(RCTPromiseResolveBlock)resolve
|
|
150
|
+
reject:(RCTPromiseRejectBlock)reject) {
|
|
151
|
+
if (!self.appId) {
|
|
152
|
+
reject(@"E_NOT_CONFIGURED", @"Call configure first", nil);
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
if (self.pendingState) {
|
|
156
|
+
reject(@"E_BUSY", @"A share is pending", nil);
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
if (![KSApi isAppInstalledFor:KSApiApplication_Kwai]) {
|
|
160
|
+
reject(@"E_NOT_INSTALLED", @"Kuaishou is not installed", nil);
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
if (![KSApi isKSAppSupportMediaApiV2]) {
|
|
164
|
+
reject(@"E_UNSUPPORTED", @"Installed Kuaishou cannot accept this share", nil);
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (![self canReadPhotos]) {
|
|
168
|
+
reject(@"E_PERMISSION", @"Photo library access is required", nil);
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
BOOL image = [request[@"mediaType"] isEqual:@"image"];
|
|
173
|
+
NSMutableArray<KSShareMediaAsset *> *assets = [NSMutableArray array];
|
|
174
|
+
for (NSDictionary *resource in request[@"resources"]) {
|
|
175
|
+
NSString *identifier = resource[@"localIdentifier"];
|
|
176
|
+
if (![resource[@"type"] isEqual:@"photoAsset"] || ![self validAsset:identifier image:image]) {
|
|
177
|
+
reject(@"E_INVALID_RESOURCE", @"Share requires readable iOS photo assets of the selected type", nil);
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
[assets addObject:[KSShareMediaAsset assetForPhotoLibrary:identifier isImage:image]];
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
KSShareMediaObject *media = [KSShareMediaObject new];
|
|
184
|
+
media.multipartAssets = assets;
|
|
185
|
+
media.disableFallback = YES;
|
|
186
|
+
KSShareMediaRequest *nativeRequest = [KSShareMediaRequest new];
|
|
187
|
+
nativeRequest.applicationList = @[@(KSApiApplication_Kwai)];
|
|
188
|
+
nativeRequest.mediaFeature = image ? KSShareMediaFeature_PictureEdit : KSShareMediaFeature_VideoEdit;
|
|
189
|
+
nativeRequest.mediaObject = media;
|
|
190
|
+
NSString *state = NSUUID.UUID.UUIDString;
|
|
191
|
+
nativeRequest.state = state;
|
|
192
|
+
self.pendingState = state;
|
|
193
|
+
self.pendingResolve = resolve;
|
|
194
|
+
self.pendingReject = reject;
|
|
195
|
+
|
|
196
|
+
__weak typeof(self) weakSelf = self;
|
|
197
|
+
self.timeout = dispatch_block_create(0, ^{
|
|
198
|
+
[weakSelf rejectState:state code:@"E_TIMEOUT" message:@"Share response timed out"];
|
|
199
|
+
});
|
|
200
|
+
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, [request[@"timeoutMs"] longLongValue] * NSEC_PER_MSEC),
|
|
201
|
+
dispatch_get_main_queue(), self.timeout);
|
|
202
|
+
[KSApi sendRequest:nativeRequest completion:^(BOOL accepted) {
|
|
203
|
+
if (!accepted) {
|
|
204
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
205
|
+
[weakSelf rejectState:state code:@"E_LAUNCH_FAILED" message:@"Kuaishou did not accept the request"];
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
}];
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
- (void)ksApiDidReceiveResponse:(KSBaseResponse *)response {
|
|
212
|
+
if (![response isKindOfClass:KSShareMediaResponse.class]) {
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
217
|
+
if (![self.pendingState isEqualToString:response.state]) {
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
NSError *error = response.error;
|
|
221
|
+
NSString *status = @"unknown";
|
|
222
|
+
if (error && error.code == KSErrorCodeSuccess) {
|
|
223
|
+
status = @"success";
|
|
224
|
+
}
|
|
225
|
+
else if (error && (error.code == -1 || error.code == -1005 || error.code == -1006
|
|
226
|
+
|| error.code == -1010 || (error.code >= 1001 && error.code <= 1005)
|
|
227
|
+
|| error.code == 20088 || error.code == 100200101)) {
|
|
228
|
+
status = @"failed";
|
|
229
|
+
}
|
|
230
|
+
RCTPromiseResolveBlock resolve = self.pendingResolve;
|
|
231
|
+
[self clearPending];
|
|
232
|
+
resolve(@{
|
|
233
|
+
@"platform": @"ios",
|
|
234
|
+
@"status": status,
|
|
235
|
+
@"nativeResponse": @{
|
|
236
|
+
@"code": error ? @(error.code) : NSNull.null,
|
|
237
|
+
@"message": error.localizedDescription ?: NSNull.null,
|
|
238
|
+
},
|
|
239
|
+
});
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
- (void)clearPending {
|
|
244
|
+
if (self.timeout) {
|
|
245
|
+
dispatch_block_cancel(self.timeout);
|
|
246
|
+
}
|
|
247
|
+
self.timeout = nil;
|
|
248
|
+
self.pendingResolve = nil;
|
|
249
|
+
self.pendingReject = nil;
|
|
250
|
+
self.pendingState = nil;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
- (void)rejectState:(NSString *)state code:(NSString *)code message:(NSString *)message {
|
|
254
|
+
if (![self.pendingState isEqualToString:state]) {
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
RCTPromiseRejectBlock reject = self.pendingReject;
|
|
258
|
+
[self clearPending];
|
|
259
|
+
reject(code, message, nil);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
RCT_EXPORT_METHOD(cancelPendingShare:(RCTPromiseResolveBlock)resolve
|
|
263
|
+
reject:(RCTPromiseRejectBlock)reject) {
|
|
264
|
+
NSString *state = self.pendingState;
|
|
265
|
+
if (state) {
|
|
266
|
+
[self rejectState:state code:@"E_WAIT_CANCELLED" message:@"Stopped waiting for Kuaishou"];
|
|
267
|
+
}
|
|
268
|
+
resolve(@(state != nil));
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
@end
|
package/lib/core.d.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
export type MediaType = 'image' | 'video';
|
|
2
|
+
export type FileResource = {
|
|
3
|
+
type: 'file';
|
|
4
|
+
uri: string;
|
|
5
|
+
};
|
|
6
|
+
export type PhotoAsset = {
|
|
7
|
+
type: 'photoAsset';
|
|
8
|
+
localIdentifier: string;
|
|
9
|
+
};
|
|
10
|
+
export type Resource = FileResource | PhotoAsset;
|
|
11
|
+
export type Capability = 'supported' | 'unsupported' | 'unknown';
|
|
12
|
+
export type Capabilities = Record<'imageEdit' | 'multiImageEdit' | 'videoEdit', Capability>;
|
|
13
|
+
export type Configuration = {
|
|
14
|
+
appId: string;
|
|
15
|
+
universalLink?: string;
|
|
16
|
+
};
|
|
17
|
+
export type ShareRequest = {
|
|
18
|
+
mediaType: MediaType;
|
|
19
|
+
resources: readonly Resource[];
|
|
20
|
+
targetPage: 'edit';
|
|
21
|
+
timeoutMs?: number;
|
|
22
|
+
};
|
|
23
|
+
export type ShareResult = {
|
|
24
|
+
status: 'success' | 'cancelled' | 'failed' | 'unknown';
|
|
25
|
+
platform: 'android' | 'ios';
|
|
26
|
+
nativeResponse: {
|
|
27
|
+
code: number | null;
|
|
28
|
+
message: string | null;
|
|
29
|
+
};
|
|
30
|
+
};
|
|
31
|
+
type NativeBridge = {
|
|
32
|
+
configure(config: Configuration): Promise<void>;
|
|
33
|
+
isAppInstalled(): Promise<boolean>;
|
|
34
|
+
getCapabilities(): Promise<Capabilities>;
|
|
35
|
+
prepareResources(request: {
|
|
36
|
+
mediaType: MediaType;
|
|
37
|
+
resources: readonly Resource[];
|
|
38
|
+
saveToPhotos: boolean;
|
|
39
|
+
}): Promise<Resource[]>;
|
|
40
|
+
share(request: ShareRequest & {
|
|
41
|
+
timeoutMs: number;
|
|
42
|
+
}): Promise<ShareResult>;
|
|
43
|
+
cancelPendingShare(): Promise<boolean>;
|
|
44
|
+
};
|
|
45
|
+
export declare class KuaishouError extends Error {
|
|
46
|
+
readonly code: string;
|
|
47
|
+
constructor(code: string, message: string);
|
|
48
|
+
}
|
|
49
|
+
export declare function createKuaishou(getNative: () => NativeBridge | undefined): {
|
|
50
|
+
configure(config: Configuration): Promise<void>;
|
|
51
|
+
isAppInstalled(): Promise<boolean>;
|
|
52
|
+
getCapabilities(): Promise<Capabilities>;
|
|
53
|
+
prepareResources(resources: readonly Resource[], options: {
|
|
54
|
+
mediaType: MediaType;
|
|
55
|
+
saveToPhotos?: boolean;
|
|
56
|
+
}): Promise<Resource[]>;
|
|
57
|
+
share(request: ShareRequest): Promise<ShareResult>;
|
|
58
|
+
cancelPendingShare(): Promise<boolean>;
|
|
59
|
+
};
|
|
60
|
+
export {};
|
package/lib/core.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.KuaishouError = void 0;
|
|
4
|
+
exports.createKuaishou = createKuaishou;
|
|
5
|
+
class KuaishouError extends Error {
|
|
6
|
+
constructor(code, message) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.code = code;
|
|
9
|
+
this.name = 'KuaishouError';
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
exports.KuaishouError = KuaishouError;
|
|
13
|
+
function validateResources(mediaType, resources) {
|
|
14
|
+
if ((mediaType !== 'image' && mediaType !== 'video')
|
|
15
|
+
|| !Array.isArray(resources)
|
|
16
|
+
|| resources.length === 0
|
|
17
|
+
|| (mediaType === 'video' && resources.length !== 1)) {
|
|
18
|
+
throw new KuaishouError('E_INVALID_RESOURCE', 'Select images or one video');
|
|
19
|
+
}
|
|
20
|
+
for (const resource of resources) {
|
|
21
|
+
const valid = resource?.type === 'file'
|
|
22
|
+
? typeof resource.uri === 'string' && /^(file|content):\/\/[^\s]+$/.test(resource.uri)
|
|
23
|
+
: resource?.type === 'photoAsset'
|
|
24
|
+
&& typeof resource.localIdentifier === 'string'
|
|
25
|
+
&& resource.localIdentifier.trim().length > 0;
|
|
26
|
+
if (!valid) {
|
|
27
|
+
throw new KuaishouError('E_INVALID_RESOURCE', 'Expected a local file URI or photo asset');
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function createKuaishou(getNative) {
|
|
32
|
+
function native() {
|
|
33
|
+
const bridge = getNative();
|
|
34
|
+
if (!bridge) {
|
|
35
|
+
throw new KuaishouError('E_UNSUPPORTED', 'Kuaishou native module is unavailable');
|
|
36
|
+
}
|
|
37
|
+
return bridge;
|
|
38
|
+
}
|
|
39
|
+
return {
|
|
40
|
+
async configure(config) {
|
|
41
|
+
if (typeof config?.appId !== 'string' || !config.appId.trim()) {
|
|
42
|
+
throw new KuaishouError('E_INVALID_CONFIG', 'A Kuaishou App ID is required');
|
|
43
|
+
}
|
|
44
|
+
await native().configure(config);
|
|
45
|
+
},
|
|
46
|
+
async isAppInstalled() {
|
|
47
|
+
return native().isAppInstalled();
|
|
48
|
+
},
|
|
49
|
+
async getCapabilities() {
|
|
50
|
+
return native().getCapabilities();
|
|
51
|
+
},
|
|
52
|
+
async prepareResources(resources, options) {
|
|
53
|
+
validateResources(options.mediaType, resources);
|
|
54
|
+
return native().prepareResources({
|
|
55
|
+
resources,
|
|
56
|
+
mediaType: options.mediaType,
|
|
57
|
+
saveToPhotos: options.saveToPhotos === true,
|
|
58
|
+
});
|
|
59
|
+
},
|
|
60
|
+
async share(request) {
|
|
61
|
+
if (request.targetPage !== 'edit') {
|
|
62
|
+
throw new KuaishouError('E_UNSUPPORTED', 'Only the edit page is supported');
|
|
63
|
+
}
|
|
64
|
+
validateResources(request.mediaType, request.resources);
|
|
65
|
+
const timeoutMs = request.timeoutMs ?? 120000;
|
|
66
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 600000) {
|
|
67
|
+
throw new KuaishouError('E_INVALID_TIMEOUT', 'timeoutMs must be between 1 and 600000');
|
|
68
|
+
}
|
|
69
|
+
return native().share({ ...request, timeoutMs });
|
|
70
|
+
},
|
|
71
|
+
async cancelPendingShare() {
|
|
72
|
+
return native().cancelPendingShare();
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
}
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export type { Capabilities, Capability, Configuration, FileResource, MediaType, PhotoAsset, Resource, ShareRequest, ShareResult, } from './core';
|
|
2
|
+
export { KuaishouError } from './core';
|
|
3
|
+
declare const _default: {
|
|
4
|
+
configure(config: import("./core").Configuration): Promise<void>;
|
|
5
|
+
isAppInstalled(): Promise<boolean>;
|
|
6
|
+
getCapabilities(): Promise<import("./core").Capabilities>;
|
|
7
|
+
prepareResources(resources: readonly import("./core").Resource[], options: {
|
|
8
|
+
mediaType: import("./core").MediaType;
|
|
9
|
+
saveToPhotos?: boolean;
|
|
10
|
+
}): Promise<import("./core").Resource[]>;
|
|
11
|
+
share(request: import("./core").ShareRequest): Promise<import("./core").ShareResult>;
|
|
12
|
+
cancelPendingShare(): Promise<boolean>;
|
|
13
|
+
};
|
|
14
|
+
export default _default;
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.KuaishouError = void 0;
|
|
4
|
+
const react_native_1 = require("react-native");
|
|
5
|
+
const core_1 = require("./core");
|
|
6
|
+
var core_2 = require("./core");
|
|
7
|
+
Object.defineProperty(exports, "KuaishouError", { enumerable: true, get: function () { return core_2.KuaishouError; } });
|
|
8
|
+
exports.default = (0, core_1.createKuaishou)(() => react_native_1.NativeModules.RNKuaishouOpenSDK);
|
package/package.json
CHANGED
|
@@ -1,6 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@code_shuai/react-native-kuaishou-open-sdk",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.2",
|
|
4
|
+
"description": "React Native bridge for Kuaishou Open SDK media sharing",
|
|
5
|
+
"main": "lib/index.js",
|
|
6
|
+
"types": "lib/index.d.ts",
|
|
7
|
+
"react-native": "src/index.ts",
|
|
8
|
+
"files": [
|
|
9
|
+
"lib",
|
|
10
|
+
"src",
|
|
11
|
+
"android/src",
|
|
12
|
+
"android/build.gradle",
|
|
13
|
+
"android/consumer-rules.pro",
|
|
14
|
+
"ios",
|
|
15
|
+
"*.podspec",
|
|
16
|
+
"example",
|
|
17
|
+
"PRD.md"
|
|
18
|
+
],
|
|
19
|
+
"scripts": {
|
|
20
|
+
"build": "tsc -p tsconfig.json",
|
|
21
|
+
"test": "npm run build && node --test tests/*.test.cjs",
|
|
22
|
+
"prepack": "npm run build",
|
|
23
|
+
"prepublishOnly": "npm run release:check",
|
|
24
|
+
"release:check": "npm test && node scripts/check-package.cjs"
|
|
25
|
+
},
|
|
26
|
+
"peerDependencies": {
|
|
27
|
+
"react": "^19.0.0",
|
|
28
|
+
"react-native": "0.83.x"
|
|
29
|
+
},
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"typescript": "~5.8.3",
|
|
32
|
+
"@types/react": "^19.0.0"
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
require 'json'
|
|
2
|
+
|
|
3
|
+
package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
|
|
4
|
+
|
|
5
|
+
Pod::Spec.new do |s|
|
|
6
|
+
s.name = 'react-native-kuaishou-open-sdk'
|
|
7
|
+
s.version = package['version']
|
|
8
|
+
s.summary = package['description']
|
|
9
|
+
s.homepage = 'https://github.com/KwaiSocial/KwaiSDK-iOS'
|
|
10
|
+
s.author = 'Finstao'
|
|
11
|
+
s.license = { :type => 'Proprietary' }
|
|
12
|
+
s.source = { :path => '.' }
|
|
13
|
+
s.ios.deployment_target = '15.1'
|
|
14
|
+
s.source_files = 'ios/**/*.{h,m}'
|
|
15
|
+
s.static_framework = true
|
|
16
|
+
s.frameworks = 'Photos'
|
|
17
|
+
s.dependency 'React-Core'
|
|
18
|
+
s.dependency 'KwaiSDK', '3.7.3'
|
|
19
|
+
end
|
package/src/core.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
export type MediaType = 'image' | 'video'
|
|
2
|
+
export type FileResource = { type: 'file'; uri: string }
|
|
3
|
+
export type PhotoAsset = { type: 'photoAsset'; localIdentifier: string }
|
|
4
|
+
export type Resource = FileResource | PhotoAsset
|
|
5
|
+
export type Capability = 'supported' | 'unsupported' | 'unknown'
|
|
6
|
+
export type Capabilities = Record<'imageEdit' | 'multiImageEdit' | 'videoEdit', Capability>
|
|
7
|
+
export type Configuration = { appId: string; universalLink?: string }
|
|
8
|
+
export type ShareRequest = {
|
|
9
|
+
mediaType: MediaType
|
|
10
|
+
resources: readonly Resource[]
|
|
11
|
+
targetPage: 'edit'
|
|
12
|
+
timeoutMs?: number
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export type ShareResult = {
|
|
16
|
+
status: 'success' | 'cancelled' | 'failed' | 'unknown'
|
|
17
|
+
platform: 'android' | 'ios'
|
|
18
|
+
nativeResponse: { code: number | null; message: string | null }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
type NativeBridge = {
|
|
22
|
+
configure(config: Configuration): Promise<void>
|
|
23
|
+
isAppInstalled(): Promise<boolean>
|
|
24
|
+
getCapabilities(): Promise<Capabilities>
|
|
25
|
+
prepareResources(request: {
|
|
26
|
+
mediaType: MediaType
|
|
27
|
+
resources: readonly Resource[]
|
|
28
|
+
saveToPhotos: boolean
|
|
29
|
+
}): Promise<Resource[]>
|
|
30
|
+
share(request: ShareRequest & { timeoutMs: number }): Promise<ShareResult>
|
|
31
|
+
cancelPendingShare(): Promise<boolean>
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export class KuaishouError extends Error {
|
|
35
|
+
constructor(public readonly code: string, message: string) {
|
|
36
|
+
super(message)
|
|
37
|
+
this.name = 'KuaishouError'
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function validateResources(mediaType: MediaType, resources: readonly Resource[]) {
|
|
42
|
+
if ((mediaType !== 'image' && mediaType !== 'video')
|
|
43
|
+
|| !Array.isArray(resources)
|
|
44
|
+
|| resources.length === 0
|
|
45
|
+
|| (mediaType === 'video' && resources.length !== 1)) {
|
|
46
|
+
throw new KuaishouError('E_INVALID_RESOURCE', 'Select images or one video')
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
for (const resource of resources) {
|
|
50
|
+
const valid = resource?.type === 'file'
|
|
51
|
+
? typeof resource.uri === 'string' && /^(file|content):\/\/[^\s]+$/.test(resource.uri)
|
|
52
|
+
: resource?.type === 'photoAsset'
|
|
53
|
+
&& typeof resource.localIdentifier === 'string'
|
|
54
|
+
&& resource.localIdentifier.trim().length > 0
|
|
55
|
+
|
|
56
|
+
if (!valid) {
|
|
57
|
+
throw new KuaishouError('E_INVALID_RESOURCE', 'Expected a local file URI or photo asset')
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function createKuaishou(getNative: () => NativeBridge | undefined) {
|
|
63
|
+
function native() {
|
|
64
|
+
const bridge = getNative()
|
|
65
|
+
if (!bridge) {
|
|
66
|
+
throw new KuaishouError('E_UNSUPPORTED', 'Kuaishou native module is unavailable')
|
|
67
|
+
}
|
|
68
|
+
return bridge
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return {
|
|
72
|
+
async configure(config: Configuration) {
|
|
73
|
+
if (typeof config?.appId !== 'string' || !config.appId.trim()) {
|
|
74
|
+
throw new KuaishouError('E_INVALID_CONFIG', 'A Kuaishou App ID is required')
|
|
75
|
+
}
|
|
76
|
+
await native().configure(config)
|
|
77
|
+
},
|
|
78
|
+
async isAppInstalled() {
|
|
79
|
+
return native().isAppInstalled()
|
|
80
|
+
},
|
|
81
|
+
async getCapabilities() {
|
|
82
|
+
return native().getCapabilities()
|
|
83
|
+
},
|
|
84
|
+
async prepareResources(
|
|
85
|
+
resources: readonly Resource[],
|
|
86
|
+
options: { mediaType: MediaType; saveToPhotos?: boolean },
|
|
87
|
+
) {
|
|
88
|
+
validateResources(options.mediaType, resources)
|
|
89
|
+
return native().prepareResources({
|
|
90
|
+
resources,
|
|
91
|
+
mediaType: options.mediaType,
|
|
92
|
+
saveToPhotos: options.saveToPhotos === true,
|
|
93
|
+
})
|
|
94
|
+
},
|
|
95
|
+
async share(request: ShareRequest) {
|
|
96
|
+
if (request.targetPage !== 'edit') {
|
|
97
|
+
throw new KuaishouError('E_UNSUPPORTED', 'Only the edit page is supported')
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
validateResources(request.mediaType, request.resources)
|
|
101
|
+
const timeoutMs = request.timeoutMs ?? 120_000
|
|
102
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 600_000) {
|
|
103
|
+
throw new KuaishouError('E_INVALID_TIMEOUT', 'timeoutMs must be between 1 and 600000')
|
|
104
|
+
}
|
|
105
|
+
return native().share({ ...request, timeoutMs })
|
|
106
|
+
},
|
|
107
|
+
async cancelPendingShare() {
|
|
108
|
+
return native().cancelPendingShare()
|
|
109
|
+
},
|
|
110
|
+
}
|
|
111
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { NativeModules } from 'react-native'
|
|
2
|
+
|
|
3
|
+
import { createKuaishou } from './core'
|
|
4
|
+
|
|
5
|
+
export type {
|
|
6
|
+
Capabilities,
|
|
7
|
+
Capability,
|
|
8
|
+
Configuration,
|
|
9
|
+
FileResource,
|
|
10
|
+
MediaType,
|
|
11
|
+
PhotoAsset,
|
|
12
|
+
Resource,
|
|
13
|
+
ShareRequest,
|
|
14
|
+
ShareResult,
|
|
15
|
+
} from './core'
|
|
16
|
+
export { KuaishouError } from './core'
|
|
17
|
+
|
|
18
|
+
export default createKuaishou(() => NativeModules.RNKuaishouOpenSDK)
|