增加添加和绑定sn,增加阿里云推送
This commit is contained in:
@@ -6,10 +6,14 @@ import com.onekeycall.videotablet.result.Result;
|
|||||||
import com.onekeycall.videotablet.service.DeviceSnService;
|
import com.onekeycall.videotablet.service.DeviceSnService;
|
||||||
import com.onekeycall.videotablet.service.UserService;
|
import com.onekeycall.videotablet.service.UserService;
|
||||||
import com.onekeycall.videotablet.utils.JwtUtil;
|
import com.onekeycall.videotablet.utils.JwtUtil;
|
||||||
|
import com.onekeycall.videotablet.utils.PushUtils;
|
||||||
import com.onekeycall.videotablet.utils.TextUtils;
|
import com.onekeycall.videotablet.utils.TextUtils;
|
||||||
|
import org.apache.commons.lang3.RandomStringUtils;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/public")
|
@RequestMapping("/public")
|
||||||
public class BindSnController {
|
public class BindSnController {
|
||||||
@@ -50,7 +54,62 @@ public class BindSnController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
try {
|
||||||
|
String randomString = RandomStringUtils.randomAlphanumeric(32);
|
||||||
|
PushUtils.aliyunAsyncPush(randomString, userPhone, sn);
|
||||||
|
return Result.ok().message("send message success");
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
return Result.error().message(e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
return Result.ok();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PostMapping("/device_bind")
|
||||||
|
public Result deviceBind(
|
||||||
|
@RequestHeader("Authorization") String authHeader, @RequestHeader("Device-ID") String deviceId,
|
||||||
|
@RequestParam(value = "user_id") String userId, @RequestParam(value = "sn") String sn,
|
||||||
|
@RequestParam(value = "verify_key") String verifyKey) {
|
||||||
|
// 1. 校验 Authorization 头
|
||||||
|
if (!authHeader.startsWith("Bearer ")) {
|
||||||
|
return Result.error().message("Invalid Authorization header");
|
||||||
|
}
|
||||||
|
String token = authHeader.substring(7); // 去掉 "Bearer " 前缀
|
||||||
|
|
||||||
|
// 2. 校验 Token
|
||||||
|
if (!jwtUtil.validateAccessToken(userId, token, deviceId)) {
|
||||||
|
return Result.error().message("Invalid token");
|
||||||
|
}
|
||||||
|
|
||||||
|
User user = userService.getUserByUserId(userId);
|
||||||
|
if (user == null) {
|
||||||
|
return Result.error().message("user not found");
|
||||||
|
}
|
||||||
|
String userPhone = user.getPhone();
|
||||||
|
|
||||||
|
|
||||||
|
// 3. 校验 sn 是否存在
|
||||||
|
DeviceInfo oldDeviceInfo = deviceSnService.findBySn(sn);
|
||||||
|
if (oldDeviceInfo == null) {
|
||||||
|
return Result.error().message("sn not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!TextUtils.isEmpty(oldDeviceInfo.getBindPhone())) {
|
||||||
|
return Result.error().message("sn already bind");
|
||||||
|
}
|
||||||
|
|
||||||
|
oldDeviceInfo.setBindPhone(userPhone);
|
||||||
|
oldDeviceInfo.setBindTime(new Date());
|
||||||
|
oldDeviceInfo.setSn(sn);
|
||||||
|
deviceSnService.save(oldDeviceInfo);
|
||||||
|
|
||||||
|
try {
|
||||||
|
PushUtils.aliyunAsyncPush(verifyKey, userPhone, sn);
|
||||||
|
return Result.ok().message("bind success");
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
return Result.error().message(e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -116,11 +116,10 @@ public class LoginController {
|
|||||||
tokenMap.put("user_id", user.getUserId());
|
tokenMap.put("user_id", user.getUserId());
|
||||||
tokenMap.put("has_password", user.isHasPassword());
|
tokenMap.put("has_password", user.isHasPassword());
|
||||||
tokenMap.put("token", tokenPair.toMap());
|
tokenMap.put("token", tokenPair.toMap());
|
||||||
|
redisTemplate.delete(phone);
|
||||||
return Result.ok().data(tokenMap);
|
return Result.ok().data(tokenMap);
|
||||||
} catch (RuntimeException e) {
|
} catch (RuntimeException e) {
|
||||||
return Result.error().message(e.getMessage());
|
return Result.error().message(e.getMessage());
|
||||||
} finally {
|
|
||||||
redisTemplate.delete(phone);
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
return Result.error().message("verify key is expired");
|
return Result.error().message("verify key is expired");
|
||||||
@@ -150,6 +149,7 @@ public class LoginController {
|
|||||||
tokenMap.put("user_id", user.getUserId());
|
tokenMap.put("user_id", user.getUserId());
|
||||||
tokenMap.put("has_password", user.isHasPassword());
|
tokenMap.put("has_password", user.isHasPassword());
|
||||||
tokenMap.put("token", tokenPair.toMap());
|
tokenMap.put("token", tokenPair.toMap());
|
||||||
|
redisTemplate.delete(phone);
|
||||||
return Result.ok().data(tokenMap);
|
return Result.ok().data(tokenMap);
|
||||||
} catch (RuntimeException e) {
|
} catch (RuntimeException e) {
|
||||||
return Result.error().message(e.getMessage());
|
return Result.error().message(e.getMessage());
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package com.onekeycall.videotablet.controller;
|
||||||
|
|
||||||
|
import com.onekeycall.videotablet.entity.DeviceInfo;
|
||||||
|
import com.onekeycall.videotablet.entity.User;
|
||||||
|
import com.onekeycall.videotablet.result.Result;
|
||||||
|
import com.onekeycall.videotablet.service.DeviceSnService;
|
||||||
|
import com.onekeycall.videotablet.service.UserService;
|
||||||
|
import com.onekeycall.videotablet.utils.JwtUtil;
|
||||||
|
import com.onekeycall.videotablet.utils.PushUtils;
|
||||||
|
import com.onekeycall.videotablet.utils.TextUtils;
|
||||||
|
import org.apache.commons.lang3.RandomStringUtils;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/public")
|
||||||
|
public class ManageSnController {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private JwtUtil jwtUtil;
|
||||||
|
@Autowired
|
||||||
|
private UserService userService;
|
||||||
|
@Autowired
|
||||||
|
private DeviceSnService deviceSnService;
|
||||||
|
|
||||||
|
@PostMapping("/add_sn")
|
||||||
|
public Result addSn(
|
||||||
|
@RequestHeader("Authorization") String authHeader, @RequestHeader("Device-ID") String deviceId,
|
||||||
|
@RequestParam(value = "user_id") String userId, @RequestParam(value = "sn") String sn) {
|
||||||
|
// 1. 校验 Authorization 头
|
||||||
|
if (!authHeader.startsWith("Bearer ")) {
|
||||||
|
return Result.error().message("Invalid Authorization header");
|
||||||
|
}
|
||||||
|
String token = authHeader.substring(7); // 去掉 "Bearer " 前缀
|
||||||
|
|
||||||
|
// 2. 校验 Token
|
||||||
|
if (!jwtUtil.validateAccessToken(userId, token, deviceId)) {
|
||||||
|
return Result.error().message("Invalid token");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 校验 sn 是否存在
|
||||||
|
DeviceInfo oldDeviceInfo = deviceSnService.findBySn(sn);
|
||||||
|
if (oldDeviceInfo != null) {
|
||||||
|
return Result.error().message("sn already exists");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 新增 sn
|
||||||
|
DeviceInfo deviceInfo = new DeviceInfo();
|
||||||
|
deviceInfo.setSn(sn);
|
||||||
|
deviceInfo.setAddTime(new Date());
|
||||||
|
deviceSnService.save(deviceInfo);
|
||||||
|
|
||||||
|
return Result.ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package com.onekeycall.videotablet.controller;
|
||||||
|
|
||||||
|
import com.onekeycall.videotablet.entity.DeviceInfo;
|
||||||
|
import com.onekeycall.videotablet.result.Result;
|
||||||
|
import com.onekeycall.videotablet.service.DeviceSnService;
|
||||||
|
import com.onekeycall.videotablet.service.UserService;
|
||||||
|
import com.onekeycall.videotablet.tencent.trtc.TLSSigAPIv2;
|
||||||
|
import com.onekeycall.videotablet.utils.JwtUtil;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/public")
|
||||||
|
public class TencentTrtcController {
|
||||||
|
@Autowired
|
||||||
|
private JwtUtil jwtUtil;
|
||||||
|
@Autowired
|
||||||
|
private UserService userService;
|
||||||
|
@Autowired
|
||||||
|
private DeviceSnService deviceSnService;
|
||||||
|
|
||||||
|
|
||||||
|
@GetMapping("/get_trtc_sig")
|
||||||
|
public Result getTrtcSig(
|
||||||
|
@RequestHeader("Authorization") String authHeader, @RequestHeader("Device-ID") String deviceId,
|
||||||
|
@RequestParam(value = "user_id") String userId
|
||||||
|
) {
|
||||||
|
if (!authHeader.startsWith("Bearer ")) {
|
||||||
|
return Result.error().message("Invalid Authorization header");
|
||||||
|
}
|
||||||
|
String token = authHeader.substring(7); // 去掉 "Bearer " 前缀
|
||||||
|
|
||||||
|
if (!jwtUtil.validateAccessToken(userId, token, deviceId)) {
|
||||||
|
return Result.error().message("Invalid token");
|
||||||
|
}
|
||||||
|
|
||||||
|
TLSSigAPIv2 tlsSigAPIv2 = new TLSSigAPIv2(1600100994, "ccc0d591fe50bd9c05df7e3182256eb43fd83d1127ae7dc01a3d256dd80f3ae2");
|
||||||
|
String sig = tlsSigAPIv2.genUserSig(userId);
|
||||||
|
Map<String, Object> map = new HashMap<>();
|
||||||
|
map.put("sig", sig);
|
||||||
|
map.put("expire", Instant.now().getEpochSecond() + TLSSigAPIv2.EXPIRETIME);
|
||||||
|
return Result.ok().data(map);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package com.onekeycall.videotablet.converter;
|
||||||
|
|
||||||
|
|
||||||
|
import com.onekeycall.videotablet.utils.AESUtil;
|
||||||
|
import jakarta.persistence.AttributeConverter;
|
||||||
|
import jakarta.persistence.Converter;
|
||||||
|
|
||||||
|
@Converter(autoApply = true)
|
||||||
|
public class AesAttributeConverter implements AttributeConverter<String, String> {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String convertToDatabaseColumn(String attribute) {
|
||||||
|
// 实体属性转数据库列:在写入数据库之前加密
|
||||||
|
if (attribute == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return AESUtil.encrypt(attribute);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String convertToEntityAttribute(String dbData) {
|
||||||
|
// 数据库列转实体属性:在从数据库读取后解密
|
||||||
|
if (dbData == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return AESUtil.decrypt(dbData);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,33 +1,47 @@
|
|||||||
package com.onekeycall.videotablet.entity;
|
package com.onekeycall.videotablet.entity;
|
||||||
|
|
||||||
|
import com.onekeycall.videotablet.converter.AesAttributeConverter;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
|
@Setter
|
||||||
@Entity
|
@Entity
|
||||||
@Table(name = "devices_sn")
|
@Table(name = "devices_sn")
|
||||||
public class DeviceInfo {
|
public class DeviceInfo {
|
||||||
|
|
||||||
@Id
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
@Column(name = "id",unique = true, nullable = false)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@Convert(converter = AesAttributeConverter.class)
|
||||||
@Column(name = "sn", unique = true, nullable = false)
|
@Column(name = "sn", unique = true, nullable = false)
|
||||||
private String sn;
|
private String sn;
|
||||||
|
|
||||||
@Column(name = "device_model", nullable = false)
|
@Column(name = "device_model")
|
||||||
private String deviceModel;
|
private String deviceModel;
|
||||||
|
|
||||||
@Column(name = "device_alias")
|
@Column(name = "device_alias")
|
||||||
private String deviceAlias;
|
private String deviceAlias;
|
||||||
|
|
||||||
|
@Convert(converter = AesAttributeConverter.class)
|
||||||
@Column(name = "user_id")
|
@Column(name = "user_id")
|
||||||
private String userId;
|
private String userId;
|
||||||
|
|
||||||
|
@Convert(converter = AesAttributeConverter.class)
|
||||||
@Column(name = "bind_phone")
|
@Column(name = "bind_phone")
|
||||||
private String bindPhone;
|
private String bindPhone;
|
||||||
|
|
||||||
@Column(name = "add_time", nullable = false)
|
@Column(name = "add_time", nullable = false)
|
||||||
private Date addTime;
|
private Date addTime;
|
||||||
|
|
||||||
|
@Column(name = "bind_time")
|
||||||
|
private Date bindTime;
|
||||||
|
|
||||||
@Column(name = "activation_time")
|
@Column(name = "activation_time")
|
||||||
private Date activationTime;
|
private Date activationTime;
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.onekeycall.videotablet.entity;
|
package com.onekeycall.videotablet.entity;
|
||||||
|
|
||||||
|
import com.onekeycall.videotablet.converter.AesAttributeConverter;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import org.springframework.security.core.GrantedAuthority;
|
import org.springframework.security.core.GrantedAuthority;
|
||||||
import org.springframework.security.core.userdetails.UserDetails;
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
@@ -22,15 +23,19 @@ public class User implements UserDetails {
|
|||||||
@Column(name = "id")
|
@Column(name = "id")
|
||||||
private Long id;
|
private Long id;
|
||||||
|
|
||||||
|
// 使用@Convert注解指定转换器
|
||||||
|
@Convert(converter = AesAttributeConverter.class)
|
||||||
@Column(name = "user_id", unique = true, nullable = false)
|
@Column(name = "user_id", unique = true, nullable = false)
|
||||||
private String userId;
|
private String userId;
|
||||||
|
|
||||||
|
@Convert(converter = AesAttributeConverter.class)
|
||||||
@Column
|
@Column
|
||||||
private String nickname;
|
private String nickname;
|
||||||
|
|
||||||
@Column()
|
@Column()
|
||||||
private String password;
|
private String password;
|
||||||
|
|
||||||
|
@Convert(converter = AesAttributeConverter.class)
|
||||||
@Column(unique = true, nullable = false)
|
@Column(unique = true, nullable = false)
|
||||||
private String phone;
|
private String phone;
|
||||||
|
|
||||||
|
|||||||
@@ -17,4 +17,8 @@ public class DeviceSnService {
|
|||||||
public DeviceInfo findBySn(String sn) {
|
public DeviceInfo findBySn(String sn) {
|
||||||
return deviceSnRepository.findBySn(sn);
|
return deviceSnRepository.findBySn(sn);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void save(DeviceInfo deviceInfo) {
|
||||||
|
deviceSnRepository.save(deviceInfo);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package com.onekeycall.videotablet.service;
|
|||||||
import com.onekeycall.videotablet.entity.User;
|
import com.onekeycall.videotablet.entity.User;
|
||||||
import com.onekeycall.videotablet.repository.UserRepository;
|
import com.onekeycall.videotablet.repository.UserRepository;
|
||||||
import com.onekeycall.videotablet.result.Result;
|
import com.onekeycall.videotablet.result.Result;
|
||||||
|
import com.onekeycall.videotablet.utils.AESUtil;
|
||||||
import com.onekeycall.videotablet.utils.SecureIdGenerator;
|
import com.onekeycall.videotablet.utils.SecureIdGenerator;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.data.redis.core.RedisTemplate;
|
import org.springframework.data.redis.core.RedisTemplate;
|
||||||
@@ -111,6 +112,7 @@ public class UserService implements UserDetailsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public User getUserByUserId(String userId) {
|
public User getUserByUserId(String userId) {
|
||||||
return userRepository.findUserByUserId(userId).orElseThrow(() -> new RuntimeException("User not found with userId: " + userId));
|
return userRepository.findUserByUserId(userId).
|
||||||
|
orElseThrow(() -> new UsernameNotFoundException("User not found with userId: " + userId));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package com.onekeycall.videotablet.tencent.trtc;
|
||||||
|
|
||||||
|
import java.util.Base64;
|
||||||
|
|
||||||
|
public class Base64URL {
|
||||||
|
public static byte[] base64EncodeUrl(byte[] input) {
|
||||||
|
byte[] base64 = Base64.getEncoder().encode(input);
|
||||||
|
for (int i = 0; i < base64.length; ++i)
|
||||||
|
switch (base64[i]) {
|
||||||
|
case '+':
|
||||||
|
base64[i] = '*';
|
||||||
|
break;
|
||||||
|
case '/':
|
||||||
|
base64[i] = '-';
|
||||||
|
break;
|
||||||
|
case '=':
|
||||||
|
base64[i] = '_';
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return base64;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,324 @@
|
|||||||
|
package com.onekeycall.videotablet.tencent.trtc;
|
||||||
|
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.security.*;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.zip.Deflater;
|
||||||
|
|
||||||
|
import javax.crypto.Mac;
|
||||||
|
import javax.crypto.spec.SecretKeySpec;
|
||||||
|
|
||||||
|
public class TLSSigAPIv2 {
|
||||||
|
final private long sdkappid;
|
||||||
|
final private String key;
|
||||||
|
public static final long EXPIRETIME = 15552000;
|
||||||
|
|
||||||
|
public TLSSigAPIv2(long sdkappid, String key) {
|
||||||
|
this.sdkappid = sdkappid;
|
||||||
|
this.key = key;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 默认180天
|
||||||
|
*
|
||||||
|
* @param userid
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public String genUserSig(String userid) {
|
||||||
|
return genUserSig(userid, EXPIRETIME, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 【功能说明】用于签发 TRTC 和 IM 服务中必须要使用的 UserSig 鉴权票据
|
||||||
|
* <p>
|
||||||
|
* 【参数说明】
|
||||||
|
*
|
||||||
|
* @param userid - 用户id,限制长度为32字节,只允许包含大小写英文字母(a-zA-Z)、数字(0-9)及下划线和连词符。
|
||||||
|
* @param expire - UserSig 票据的过期时间,单位是秒,比如 86400 代表生成的 UserSig 票据在一天后就无法再使用了。
|
||||||
|
* @return usersig -生成的签名
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Function: Used to issue UserSig that is required by the TRTC and IM services.
|
||||||
|
* <p>
|
||||||
|
* Parameter description:
|
||||||
|
*
|
||||||
|
* @param userid - User ID. The value can be up to 32 bytes in length and contain letters (a-z and A-Z), digits (0-9), underscores (_), and hyphens (-).
|
||||||
|
* @param expire - UserSig expiration time, in seconds. For example, 86400 indicates that the generated UserSig will expire one day after being generated.
|
||||||
|
* @return usersig - Generated signature.
|
||||||
|
*/
|
||||||
|
public String genUserSig(String userid, long expire) {
|
||||||
|
return genUserSig(userid, expire, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 【功能说明】
|
||||||
|
* 用于签发 TRTC 进房参数中可选的 PrivateMapKey 权限票据。
|
||||||
|
* PrivateMapKey 需要跟 UserSig 一起使用,但 PrivateMapKey 比 UserSig 有更强的权限控制能力:
|
||||||
|
* - UserSig 只能控制某个 UserID 有无使用 TRTC 服务的权限,只要 UserSig 正确,其对应的 UserID 可以进出任意房间。
|
||||||
|
* - PrivateMapKey 则是将 UserID 的权限控制的更加严格,包括能不能进入某个房间,能不能在该房间里上行音视频等等。
|
||||||
|
* 如果要开启 PrivateMapKey 严格权限位校验,需要在【实时音视频控制台】/【应用管理】/【应用信息】中打开“启动权限密钥”开关。
|
||||||
|
* <p>
|
||||||
|
* 【参数说明】
|
||||||
|
*
|
||||||
|
* @param userid - 用户id,限制长度为32字节,只允许包含大小写英文字母(a-zA-Z)、数字(0-9)及下划线和连词符。
|
||||||
|
* @param expire - PrivateMapKey 票据的过期时间,单位是秒,比如 86400 生成的 PrivateMapKey 票据在一天后就无法再使用了。
|
||||||
|
* @param roomid - 房间号,用于指定该 userid 可以进入的房间号
|
||||||
|
* @param privilegeMap - 权限位,使用了一个字节中的 8 个比特位,分别代表八个具体的功能权限开关:
|
||||||
|
* - 第 1 位:0000 0001 = 1,创建房间的权限
|
||||||
|
* - 第 2 位:0000 0010 = 2,加入房间的权限
|
||||||
|
* - 第 3 位:0000 0100 = 4,发送语音的权限
|
||||||
|
* - 第 4 位:0000 1000 = 8,接收语音的权限
|
||||||
|
* - 第 5 位:0001 0000 = 16,发送视频的权限
|
||||||
|
* - 第 6 位:0010 0000 = 32,接收视频的权限
|
||||||
|
* - 第 7 位:0100 0000 = 64,发送辅路(也就是屏幕分享)视频的权限
|
||||||
|
* - 第 8 位:1000 0000 = 200,接收辅路(也就是屏幕分享)视频的权限
|
||||||
|
* - privilegeMap == 1111 1111 == 255 代表该 userid 在该 roomid 房间内的所有功能权限。
|
||||||
|
* - privilegeMap == 0010 1010 == 42 代表该 userid 拥有加入房间和接收音视频数据的权限,但不具备其他权限。
|
||||||
|
* @return usersig - 生成带userbuf的签名
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Function:
|
||||||
|
* Used to issue PrivateMapKey that is optional for room entry.
|
||||||
|
* PrivateMapKey must be used together with UserSig but with more powerful permission control capabilities.
|
||||||
|
* - UserSig can only control whether a UserID has permission to use the TRTC service. As long as the UserSig is correct, the user with the corresponding UserID can enter or leave any room.
|
||||||
|
* - PrivateMapKey specifies more stringent permissions for a UserID, including whether the UserID can be used to enter a specific room and perform audio/video upstreaming in the room.
|
||||||
|
* To enable stringent PrivateMapKey permission bit verification, you need to enable permission key in TRTC console > Application Management > Application Info.
|
||||||
|
* <p>
|
||||||
|
* Parameter description:
|
||||||
|
*
|
||||||
|
* @param userid - User ID. The value can be up to 32 bytes in length and contain letters (a-z and A-Z), digits (0-9), underscores (_), and hyphens (-).
|
||||||
|
* @param roomid - ID of the room to which the specified UserID can enter.
|
||||||
|
* @param expire - PrivateMapKey expiration time, in seconds. For example, 86400 indicates that the generated PrivateMapKey will expire one day after being generated.
|
||||||
|
* @param privilegeMap - Permission bits. Eight bits in the same byte are used as the permission switches of eight specific features:
|
||||||
|
* - Bit 1: 0000 0001 = 1, permission for room creation
|
||||||
|
* - Bit 2: 0000 0010 = 2, permission for room entry
|
||||||
|
* - Bit 3: 0000 0100 = 4, permission for audio sending
|
||||||
|
* - Bit 4: 0000 1000 = 8, permission for audio receiving
|
||||||
|
* - Bit 5: 0001 0000 = 16, permission for video sending
|
||||||
|
* - Bit 6: 0010 0000 = 32, permission for video receiving
|
||||||
|
* - Bit 7: 0100 0000 = 64, permission for substream video sending (screen sharing)
|
||||||
|
* - Bit 8: 1000 0000 = 200, permission for substream video receiving (screen sharing)
|
||||||
|
* - privilegeMap == 1111 1111 == 255: Indicates that the UserID has all feature permissions of the room specified by roomid.
|
||||||
|
* - privilegeMap == 0010 1010 == 42: Indicates that the UserID has only the permissions to enter the room and receive audio/video data.
|
||||||
|
* @return usersig - Generate signature with userbuf
|
||||||
|
*/
|
||||||
|
public String genPrivateMapKey(String userid, long expire, long roomid, long privilegeMap) {
|
||||||
|
byte[] userbuf = genUserBuf(userid, roomid, expire, privilegeMap, 0, ""); //生成userbuf
|
||||||
|
return genUserSig(userid, expire, userbuf);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 【功能说明】
|
||||||
|
* 用于签发 TRTC 进房参数中可选的 PrivateMapKey 权限票据。
|
||||||
|
* PrivateMapKey 需要跟 UserSig 一起使用,但 PrivateMapKey 比 UserSig 有更强的权限控制能力:
|
||||||
|
* - UserSig 只能控制某个 UserID 有无使用 TRTC 服务的权限,只要 UserSig 正确,其对应的 UserID 可以进出任意房间。
|
||||||
|
* - PrivateMapKey 则是将 UserID 的权限控制的更加严格,包括能不能进入某个房间,能不能在该房间里上行音视频等等。
|
||||||
|
* 如果要开启 PrivateMapKey 严格权限位校验,需要在【实时音视频控制台】/【应用管理】/【应用信息】中打开“启动权限密钥”开关。
|
||||||
|
* <p>
|
||||||
|
* 【参数说明】
|
||||||
|
*
|
||||||
|
* @param userid - 用户id,限制长度为32字节,只允许包含大小写英文字母(a-zA-Z)、数字(0-9)及下划线和连词符。
|
||||||
|
* @param expire - PrivateMapKey 票据的过期时间,单位是秒,比如 86400 生成的 PrivateMapKey 票据在一天后就无法再使用了。
|
||||||
|
* @param roomstr - 字符串房间号,用于指定该 userid 可以进入的房间号
|
||||||
|
* @param privilegeMap - 权限位,使用了一个字节中的 8 个比特位,分别代表八个具体的功能权限开关:
|
||||||
|
* - 第 1 位:0000 0001 = 1,创建房间的权限
|
||||||
|
* - 第 2 位:0000 0010 = 2,加入房间的权限
|
||||||
|
* - 第 3 位:0000 0100 = 4,发送语音的权限
|
||||||
|
* - 第 4 位:0000 1000 = 8,接收语音的权限
|
||||||
|
* - 第 5 位:0001 0000 = 16,发送视频的权限
|
||||||
|
* - 第 6 位:0010 0000 = 32,接收视频的权限
|
||||||
|
* - 第 7 位:0100 0000 = 64,发送辅路(也就是屏幕分享)视频的权限
|
||||||
|
* - 第 8 位:1000 0000 = 200,接收辅路(也就是屏幕分享)视频的权限
|
||||||
|
* - privilegeMap == 1111 1111 == 255 代表该 userid 在该 roomid 房间内的所有功能权限。
|
||||||
|
* - privilegeMap == 0010 1010 == 42 代表该 userid 拥有加入房间和接收音视频数据的权限,但不具备其他权限。
|
||||||
|
* @return usersig - 生成带userbuf的签名
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Function:
|
||||||
|
* Used to issue PrivateMapKey that is optional for room entry.
|
||||||
|
* PrivateMapKey must be used together with UserSig but with more powerful permission control capabilities.
|
||||||
|
* - UserSig can only control whether a UserID has permission to use the TRTC service. As long as the UserSig is correct, the user with the corresponding UserID can enter or leave any room.
|
||||||
|
* - PrivateMapKey specifies more stringent permissions for a UserID, including whether the UserID can be used to enter a specific room and perform audio/video upstreaming in the room.
|
||||||
|
* To enable stringent PrivateMapKey permission bit verification, you need to enable permission key in TRTC console > Application Management > Application Info.
|
||||||
|
* <p>
|
||||||
|
* Parameter description:
|
||||||
|
*
|
||||||
|
* @param userid - User ID. The value can be up to 32 bytes in length and contain letters (a-z and A-Z), digits (0-9), underscores (_), and hyphens (-).
|
||||||
|
* @param roomid - ID of the room to which the specified UserID can enter.
|
||||||
|
* @param expire - PrivateMapKey expiration time, in seconds. For example, 86400 indicates that the generated PrivateMapKey will expire one day after being generated.
|
||||||
|
* @param privilegeMap - Permission bits. Eight bits in the same byte are used as the permission switches of eight specific features:
|
||||||
|
* - Bit 1: 0000 0001 = 1, permission for room creation
|
||||||
|
* - Bit 2: 0000 0010 = 2, permission for room entry
|
||||||
|
* - Bit 3: 0000 0100 = 4, permission for audio sending
|
||||||
|
* - Bit 4: 0000 1000 = 8, permission for audio receiving
|
||||||
|
* - Bit 5: 0001 0000 = 16, permission for video sending
|
||||||
|
* - Bit 6: 0010 0000 = 32, permission for video receiving
|
||||||
|
* - Bit 7: 0100 0000 = 64, permission for substream video sending (screen sharing)
|
||||||
|
* - Bit 8: 1000 0000 = 200, permission for substream video receiving (screen sharing)
|
||||||
|
* - privilegeMap == 1111 1111 == 255: Indicates that the UserID has all feature permissions of the room specified by roomid.
|
||||||
|
* - privilegeMap == 0010 1010 == 42: Indicates that the UserID has only the permissions to enter the room and receive audio/video data.
|
||||||
|
* @return usersig - Generate signature with userbuf
|
||||||
|
*/
|
||||||
|
public String genPrivateMapKeyWithStringRoomID(String userid, long expire, String roomstr, long privilegeMap) {
|
||||||
|
byte[] userbuf = genUserBuf(userid, 0, expire, privilegeMap, 0, roomstr); //生成userbuf
|
||||||
|
return genUserSig(userid, expire, userbuf);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String hmacsha256(String identifier, long currTime, long expire, String base64Userbuf) {
|
||||||
|
String contentToBeSigned = "TLS.identifier:" + identifier + "\n"
|
||||||
|
+ "TLS.sdkappid:" + sdkappid + "\n"
|
||||||
|
+ "TLS.time:" + currTime + "\n"
|
||||||
|
+ "TLS.expire:" + expire + "\n";
|
||||||
|
if (null != base64Userbuf) {
|
||||||
|
contentToBeSigned += "TLS.userbuf:" + base64Userbuf + "\n";
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
byte[] byteKey = key.getBytes(StandardCharsets.UTF_8);
|
||||||
|
Mac hmac = Mac.getInstance("HmacSHA256");
|
||||||
|
SecretKeySpec keySpec = new SecretKeySpec(byteKey, "HmacSHA256");
|
||||||
|
hmac.init(keySpec);
|
||||||
|
byte[] byteSig = hmac.doFinal(contentToBeSigned.getBytes(StandardCharsets.UTF_8));
|
||||||
|
return (Base64.getEncoder().encodeToString(byteSig)).replaceAll("\\s*", "");
|
||||||
|
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String genUserSig(String userid, long expire, byte[] userbuf) {
|
||||||
|
|
||||||
|
long currTime = System.currentTimeMillis() / 1000;
|
||||||
|
|
||||||
|
JsonObject sigDoc = new JsonObject();
|
||||||
|
sigDoc.addProperty("TLS.ver", "2.0");
|
||||||
|
sigDoc.addProperty("TLS.identifier", userid);
|
||||||
|
sigDoc.addProperty("TLS.sdkappid", sdkappid);
|
||||||
|
sigDoc.addProperty("TLS.expire", expire);
|
||||||
|
sigDoc.addProperty("TLS.time", currTime);
|
||||||
|
|
||||||
|
String base64UserBuf = null;
|
||||||
|
if (null != userbuf) {
|
||||||
|
base64UserBuf = Base64.getEncoder().encodeToString(userbuf).replaceAll("\\s*", "");
|
||||||
|
sigDoc.addProperty("TLS.userbuf", base64UserBuf);
|
||||||
|
}
|
||||||
|
String sig = hmacsha256(userid, currTime, expire, base64UserBuf);
|
||||||
|
if (sig.length() == 0) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
sigDoc.addProperty("TLS.sig", sig);
|
||||||
|
Deflater compressor = new Deflater();
|
||||||
|
compressor.setInput(sigDoc.toString().getBytes(StandardCharsets.UTF_8));
|
||||||
|
compressor.finish();
|
||||||
|
byte[] compressedBytes = new byte[2048];
|
||||||
|
int compressedBytesLength = compressor.deflate(compressedBytes);
|
||||||
|
compressor.end();
|
||||||
|
return (new String(Base64URL.base64EncodeUrl(Arrays.copyOfRange(compressedBytes,
|
||||||
|
0, compressedBytesLength)))).replaceAll("\\s*", "");
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] genUserBuf(String account, long dwAuthID, long dwExpTime,
|
||||||
|
long dwPrivilegeMap, long dwAccountType, String RoomStr) {
|
||||||
|
//视频校验位需要用到的字段,按照网络字节序放入buf中
|
||||||
|
/*
|
||||||
|
cVer unsigned char/1 版本号,填0
|
||||||
|
wAccountLen unsigned short /2 第三方自己的帐号长度
|
||||||
|
account wAccountLen 第三方自己的帐号字符
|
||||||
|
dwSdkAppid unsigned int/4 sdkappid
|
||||||
|
dwAuthID unsigned int/4 群组号码
|
||||||
|
dwExpTime unsigned int/4 过期时间 ,直接使用填入的值
|
||||||
|
dwPrivilegeMap unsigned int/4 权限位,主播0xff,观众0xab
|
||||||
|
dwAccountType unsigned int/4 第三方帐号类型
|
||||||
|
*/
|
||||||
|
|
||||||
|
//The fields required for the video check digit are placed in buf according to the network byte order.
|
||||||
|
/*
|
||||||
|
cVer unsigned char/1 Version number, fill in 0
|
||||||
|
wAccountLen unsigned short /2 Third party's own account length
|
||||||
|
account wAccountLen Third party's own account characters
|
||||||
|
dwSdkAppid unsigned int/4 sdkappid
|
||||||
|
dwAuthID unsigned int/4 group number
|
||||||
|
dwExpTime unsigned int/4 Expiration time , use the filled value directly
|
||||||
|
dwPrivilegeMap unsigned int/4 Permission bits, host 0xff, audience 0xab
|
||||||
|
dwAccountType unsigned int/4 Third-party account type
|
||||||
|
*/
|
||||||
|
int accountLength = account.length();
|
||||||
|
int roomStrLength = RoomStr.length();
|
||||||
|
int offset = 0;
|
||||||
|
int bufLength = 1 + 2 + accountLength + 20;
|
||||||
|
if (roomStrLength > 0) {
|
||||||
|
bufLength = bufLength + 2 + roomStrLength;
|
||||||
|
}
|
||||||
|
byte[] userbuf = new byte[bufLength];
|
||||||
|
|
||||||
|
//cVer
|
||||||
|
if (roomStrLength > 0) {
|
||||||
|
userbuf[offset++] = 1;
|
||||||
|
} else {
|
||||||
|
userbuf[offset++] = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
//wAccountLen
|
||||||
|
userbuf[offset++] = (byte) ((accountLength & 0xFF00) >> 8);
|
||||||
|
userbuf[offset++] = (byte) (accountLength & 0x00FF);
|
||||||
|
|
||||||
|
//account
|
||||||
|
for (; offset < 3 + accountLength; ++offset) {
|
||||||
|
userbuf[offset] = (byte) account.charAt(offset - 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
//dwSdkAppid
|
||||||
|
userbuf[offset++] = (byte) ((sdkappid & 0xFF000000) >> 24);
|
||||||
|
userbuf[offset++] = (byte) ((sdkappid & 0x00FF0000) >> 16);
|
||||||
|
userbuf[offset++] = (byte) ((sdkappid & 0x0000FF00) >> 8);
|
||||||
|
userbuf[offset++] = (byte) (sdkappid & 0x000000FF);
|
||||||
|
|
||||||
|
//dwAuthId,房间号
|
||||||
|
//dwAuthId, room number
|
||||||
|
userbuf[offset++] = (byte) ((dwAuthID & 0xFF000000) >> 24);
|
||||||
|
userbuf[offset++] = (byte) ((dwAuthID & 0x00FF0000) >> 16);
|
||||||
|
userbuf[offset++] = (byte) ((dwAuthID & 0x0000FF00) >> 8);
|
||||||
|
userbuf[offset++] = (byte) (dwAuthID & 0x000000FF);
|
||||||
|
|
||||||
|
//expire,过期时间,当前时间 + 有效期(单位:秒)
|
||||||
|
//expire,Expiration time, current time + validity period (unit: seconds)
|
||||||
|
long currTime = System.currentTimeMillis() / 1000;
|
||||||
|
long expire = currTime + dwExpTime;
|
||||||
|
userbuf[offset++] = (byte) ((expire & 0xFF000000) >> 24);
|
||||||
|
userbuf[offset++] = (byte) ((expire & 0x00FF0000) >> 16);
|
||||||
|
userbuf[offset++] = (byte) ((expire & 0x0000FF00) >> 8);
|
||||||
|
userbuf[offset++] = (byte) (expire & 0x000000FF);
|
||||||
|
|
||||||
|
//dwPrivilegeMap,权限位
|
||||||
|
//dwPrivilegeMap,Permission bits
|
||||||
|
userbuf[offset++] = (byte) ((dwPrivilegeMap & 0xFF000000) >> 24);
|
||||||
|
userbuf[offset++] = (byte) ((dwPrivilegeMap & 0x00FF0000) >> 16);
|
||||||
|
userbuf[offset++] = (byte) ((dwPrivilegeMap & 0x0000FF00) >> 8);
|
||||||
|
userbuf[offset++] = (byte) (dwPrivilegeMap & 0x000000FF);
|
||||||
|
|
||||||
|
//dwAccountType,账户类型
|
||||||
|
//dwAccountType,account type
|
||||||
|
userbuf[offset++] = (byte) ((dwAccountType & 0xFF000000) >> 24);
|
||||||
|
userbuf[offset++] = (byte) ((dwAccountType & 0x00FF0000) >> 16);
|
||||||
|
userbuf[offset++] = (byte) ((dwAccountType & 0x0000FF00) >> 8);
|
||||||
|
userbuf[offset++] = (byte) (dwAccountType & 0x000000FF);
|
||||||
|
|
||||||
|
|
||||||
|
if (roomStrLength > 0) {
|
||||||
|
//roomStrLen
|
||||||
|
userbuf[offset++] = (byte) ((roomStrLength & 0xFF00) >> 8);
|
||||||
|
userbuf[offset++] = (byte) (roomStrLength & 0x00FF);
|
||||||
|
|
||||||
|
//roomStr
|
||||||
|
for (; offset < bufLength; ++offset) {
|
||||||
|
userbuf[offset] = (byte) RoomStr.charAt(offset - (bufLength - roomStrLength));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return userbuf;
|
||||||
|
}
|
||||||
|
}
|
||||||
80
src/main/java/com/onekeycall/videotablet/utils/AESUtil.java
Normal file
80
src/main/java/com/onekeycall/videotablet/utils/AESUtil.java
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
package com.onekeycall.videotablet.utils;
|
||||||
|
|
||||||
|
import javax.crypto.Cipher;
|
||||||
|
import javax.crypto.spec.SecretKeySpec;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Base64;
|
||||||
|
|
||||||
|
public class AESUtil {
|
||||||
|
// 使用ECB模式(无需IV)
|
||||||
|
private static final String ALGORITHM = "AES/ECB/PKCS5Padding";
|
||||||
|
|
||||||
|
// 密钥长度要求:128/192/256位(16/24/32字节)
|
||||||
|
private static final int KEY_LENGTH = 32; // 256位密钥
|
||||||
|
|
||||||
|
// 从环境变量获取密钥(生产环境推荐)
|
||||||
|
// private static final String SECRET_KEY = System.getenv("AES_KEY");
|
||||||
|
|
||||||
|
// 测试用密钥(确保长度符合要求)
|
||||||
|
private static final String SECRET_KEY = "dasdasdasdawqeq12345312gs6h092fs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 加密方法(ECB模式)
|
||||||
|
* @param plaintext 明文
|
||||||
|
* @return Base64编码的密文
|
||||||
|
*/
|
||||||
|
public static String encrypt(String plaintext) {
|
||||||
|
try {
|
||||||
|
// 验证密钥长度
|
||||||
|
validateKey();
|
||||||
|
|
||||||
|
// 初始化加密器
|
||||||
|
Cipher cipher = Cipher.getInstance(ALGORITHM);
|
||||||
|
SecretKeySpec keySpec = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), "AES");
|
||||||
|
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
|
||||||
|
|
||||||
|
// 加密数据
|
||||||
|
byte[] encrypted = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
|
||||||
|
|
||||||
|
return Base64.getEncoder().encodeToString(encrypted);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("加密失败", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解密方法(ECB模式)
|
||||||
|
* @param ciphertext Base64编码的密文
|
||||||
|
* @return 解密后的明文
|
||||||
|
*/
|
||||||
|
public static String decrypt(String ciphertext) {
|
||||||
|
try {
|
||||||
|
// 验证密钥长度
|
||||||
|
validateKey();
|
||||||
|
|
||||||
|
// 初始化解密器
|
||||||
|
Cipher cipher = Cipher.getInstance(ALGORITHM);
|
||||||
|
SecretKeySpec keySpec = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), "AES");
|
||||||
|
cipher.init(Cipher.DECRYPT_MODE, keySpec);
|
||||||
|
|
||||||
|
// 解密数据
|
||||||
|
byte[] decodedBytes = Base64.getDecoder().decode(ciphertext);
|
||||||
|
byte[] decrypted = cipher.doFinal(decodedBytes);
|
||||||
|
|
||||||
|
return new String(decrypted, StandardCharsets.UTF_8);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("解密失败", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证密钥长度是否符合要求
|
||||||
|
*/
|
||||||
|
private static void validateKey() {
|
||||||
|
byte[] keyBytes = SECRET_KEY.getBytes(StandardCharsets.UTF_8);
|
||||||
|
if (keyBytes.length != 16 && keyBytes.length != 24 && keyBytes.length != 32) {
|
||||||
|
throw new IllegalArgumentException("无效的密钥长度。AES要求密钥长度为16(128位)、24(192位)或32字节(256位)。"
|
||||||
|
+ "当前长度: " + keyBytes.length + "字节");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,54 +2,85 @@ package com.onekeycall.videotablet.utils;
|
|||||||
|
|
||||||
import com.aliyun.auth.credentials.Credential;
|
import com.aliyun.auth.credentials.Credential;
|
||||||
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
|
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
|
||||||
import com.aliyun.credentials.models.Config;
|
import com.aliyun.sdk.service.push20160801.AsyncClient;
|
||||||
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
|
|
||||||
import com.aliyun.sdk.service.push20160801.models.PushRequest;
|
import com.aliyun.sdk.service.push20160801.models.PushRequest;
|
||||||
import com.aliyun.sdk.service.push20160801.models.PushResponse;
|
import com.aliyun.sdk.service.push20160801.models.PushResponse;
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import darabonba.core.client.ClientOverrideConfiguration;
|
import darabonba.core.client.ClientOverrideConfiguration;
|
||||||
|
|
||||||
import java.util.concurrent.CompletableFuture;
|
import java.util.concurrent.CompletableFuture;
|
||||||
import com.aliyun.tea.*;
|
import java.util.concurrent.ExecutionException;
|
||||||
import com.aliyun.push20160801.*;
|
|
||||||
import com.aliyun.push20160801.models.*;
|
|
||||||
import com.aliyun.teaopenapi.*;
|
|
||||||
import com.aliyun.teaopenapi.models.*;
|
|
||||||
import com.aliyun.teautil.*;
|
|
||||||
|
|
||||||
public class PushUtils {
|
public class PushUtils {
|
||||||
// public static com.aliyun.push20160801.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
|
public static void aliyunAsyncPush(String verifyKey, String phone,String sn) throws ExecutionException, InterruptedException {
|
||||||
// Config config = new Config();
|
// HttpClient Configuration
|
||||||
// // 您的AccessKey ID
|
/*HttpClient httpClient = new ApacheAsyncHttpClientBuilder()
|
||||||
// config.accessKeyId = accessKeyId;
|
.connectionTimeout(Duration.ofSeconds(10)) // Set the connection timeout time, the default is 10 seconds
|
||||||
// // 您的AccessKey Secret
|
.responseTimeout(Duration.ofSeconds(10)) // Set the response timeout time, the default is 20 seconds
|
||||||
// config.accessKeySecret = accessKeySecret;
|
.maxConnections(128) // Set the connection pool size
|
||||||
// config.regionId = "cn-hangzhou";
|
.maxIdleTimeOut(Duration.ofSeconds(50)) // Set the connection pool timeout, the default is 30 seconds
|
||||||
// return new com.aliyun.push20160801.Client(config);
|
// Configure the proxy
|
||||||
// }
|
.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("<your-proxy-hostname>", 9001))
|
||||||
//
|
.setCredentials("<your-proxy-username>", "<your-proxy-password>"))
|
||||||
// public static void aliyunAsyncPush( String message, String title) {
|
// If it is an https connection, you need to configure the certificate, or ignore the certificate(.ignoreSSL(true))
|
||||||
//
|
.x509TrustManagers(new X509TrustManager[]{})
|
||||||
// java.util.List<String> args = java.util.Arrays.asList(args_);
|
.keyManagers(new KeyManager[]{})
|
||||||
// com.aliyun.push20160801.Client client = Sample.createClient(com.aliyun.darabonba.env.EnvClient.getEnv("ACCESS_KEY_ID"), com.aliyun.darabonba.env.EnvClient.getEnv("ACCESS_KEY_SECRET"));
|
.ignoreSSL(false)
|
||||||
// PushRequest request = new PushRequest()
|
.build();*/
|
||||||
// .setAppKey(com.aliyun.darabonbanumber.Client.parseLong(args.get(0)))
|
|
||||||
// .setPushType("MESSAGE")
|
|
||||||
// .setDeviceType("ALL")
|
|
||||||
// .setStoreOffline(true)
|
|
||||||
// .setIOSRemind(true)
|
|
||||||
// .setAndroidRemind(true)
|
|
||||||
// .setTarget("DEVICE")
|
|
||||||
// .setTargetValue(args.get(1))
|
|
||||||
// .setTitle(args.get(2))
|
|
||||||
// .setBody(args.get(3))
|
|
||||||
// .setIOSRemindBody(args.get(4))
|
|
||||||
// .setAndroidPopupTitle(args.get(5))
|
|
||||||
// .setAndroidPopupBody(args.get(6));
|
|
||||||
// PushResponse response = client.push(request);
|
|
||||||
// com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(response.body)));
|
|
||||||
// }
|
|
||||||
|
|
||||||
|
// Configure Credentials authentication information, including ak, secret, token
|
||||||
|
StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
|
||||||
|
// Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
|
||||||
|
.accessKeyId("LTAI5tAffPd7YNsEbNfQSiwU")
|
||||||
|
.accessKeySecret("6RzsuGceNOUD0WFpRfQRZ8eLXdHtFA")
|
||||||
|
//.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS token
|
||||||
|
.build());
|
||||||
|
|
||||||
|
// Configure the Client
|
||||||
|
AsyncClient client = AsyncClient.builder()
|
||||||
|
.region("cn-chengdu") // Region ID
|
||||||
|
//.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
|
||||||
|
.credentialsProvider(provider)
|
||||||
|
//.serviceConfiguration(Configuration.create()) // Service-level configuration
|
||||||
|
// Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
|
||||||
|
.overrideConfiguration(
|
||||||
|
ClientOverrideConfiguration.create()
|
||||||
|
// Endpoint 请参考 https://api.aliyun.com/product/Push
|
||||||
|
.setEndpointOverride("cloudpush.aliyuncs.com")
|
||||||
|
//.setConnectTimeout(Duration.ofSeconds(30))
|
||||||
|
)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
// Parameter settings for API request
|
||||||
|
PushRequest pushRequest = PushRequest.builder()
|
||||||
|
.appKey(335580260L)
|
||||||
|
.pushType("MESSAGE")
|
||||||
|
.deviceType("ANDROID")
|
||||||
|
.target("ALIAS")
|
||||||
|
.targetValue(sn)
|
||||||
|
.title("1")
|
||||||
|
.storeOffline(true)
|
||||||
|
.body("{ \"perator\":\""+phone+"\",\"time\":\""+System.currentTimeMillis()+"\",\"verify_key\":\""+verifyKey+"\" }")
|
||||||
|
// Request-level configuration rewrite, can set Http request parameters, etc.
|
||||||
|
// .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
// Asynchronously get the return value of the API request
|
||||||
|
CompletableFuture<PushResponse> response = client.push(pushRequest);
|
||||||
|
// Synchronously get the return value of the API request
|
||||||
|
PushResponse resp = response.get();
|
||||||
|
System.out.println(new Gson().toJson(resp));
|
||||||
|
// Asynchronous processing of return values
|
||||||
|
/*response.thenAccept(resp -> {
|
||||||
|
System.out.println(new Gson().toJson(resp));
|
||||||
|
}).exceptionally(throwable -> { // Handling exceptions
|
||||||
|
System.out.println(throwable.getMessage());
|
||||||
|
return null;
|
||||||
|
});*/
|
||||||
|
|
||||||
|
// Finally, close the client
|
||||||
|
client.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user