Commit e9e40a82 authored by 张永's avatar 张永

调整 阿里云接口,创建转码模板

parent 3f52e3fb
......@@ -12,12 +12,16 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import com.egolm.common.HttpUtil;
import com.egolm.common.StringUtil;
import com.egolm.common.bean.Rjx;
import com.egolm.film.api.service.Messages;
import com.egolm.film.util.AliyunSign;
import com.egolm.film.util.AliyunUtil;
import io.swagger.annotations.Api;
......@@ -36,6 +40,10 @@ public class AliyunApiController {
@Value("${aliyun.sts.accessKeySecret}")
private String accessKeySecret;
@Value("${aliyun.video.templateId}")
private String templateId;
@Autowired
private Messages messages;
......@@ -74,7 +82,7 @@ public class AliyunApiController {
return Rjx.jsonOk().set("RequestId", response.getRequestId()).set("UploadAuth", response.getUploadAuth())
.set("UploadAddress", response.getUploadAddress())
.set("VideoId", response.getVideoId());
.set("VideoId", response.getVideoId()).set("templateId", templateId);
}
......@@ -93,7 +101,7 @@ public class AliyunApiController {
AliyunUtil aliyunUtil = new AliyunUtil(accessKeyId,accessKeySecret);
RefreshUploadVideoResponse response = aliyunUtil.refreshUploadVideo(videoId);
if(response != null) {
return Rjx.jsonOk().set("RequestId", response.getRequestId()).set("UploadAuth", response.getUploadAuth()).set("UploadAddress", response.getUploadAddress());
return Rjx.jsonOk().set("RequestId", response.getRequestId()).set("UploadAuth", response.getUploadAuth()).set("UploadAddress", response.getUploadAddress()).set("templateId", templateId);
}else {
return Rjx.jsonErr().setCode(-1).setMessage("InvalidVideo.NotFound : The video does not exist.");
}
......@@ -129,5 +137,109 @@ public class AliyunApiController {
}
}
/**
* https://help.aliyun.com/document_detail/52839.html?spm=a2c4g.11186623.2.16.56da9028Qxc5wl#TranscodeTemplate
* @Title: transcode
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param: @param request
* @param: @return
* @return: Object
* @throws
*/
@ResponseBody
@ApiOperation("新增视频转码模板")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query", name = "templateName", dataType = "String", required = true, value = "转码组名称", defaultValue = ""),
@ApiImplicitParam(paramType = "query", name = "watermarkIds", dataType = "String", required = true, value = "水印ID(值来源于水印管理)", defaultValue = ""),
})
@RequestMapping(value = "/addTranscodeTemplate",method=RequestMethod.GET)
public Object addTranscodeTemplate(HttpServletRequest request) {
String templateName = request.getParameter("templateName");
String watermarkIds = request.getParameter("watermarkIds");
if(!StringUtil.isNotEmpty(templateName,watermarkIds)) {
return Rjx.jsonErr().setCode(-1).setMessage("参数不能为空");
}
//模板参数信息
JSONObject videoObj = new JSONObject();
videoObj.put("Codec", "H.264");
videoObj.put("Bitrate", "900");
videoObj.put("Width", "960");
videoObj.put("Height", "540");
videoObj.put("Remove",false);
videoObj.put("Fps", "25");
videoObj.put("Gop", "250");
JSONObject audioObj = new JSONObject();
audioObj.put("Codec", "AAC");
audioObj.put("Bitrate", "96");
audioObj.put("Remove", false);
audioObj.put("Samplerate", "44100");
audioObj.put("Channels", "2");
JSONObject containerObj = new JSONObject();
containerObj.put("Format", "m3u8"); //填m3u8 生成的格式就为 hls
JSONObject muxConfigObj = new JSONObject();
JSONObject segmentObj = new JSONObject();
segmentObj.put("Duration", "10");
muxConfigObj.put("Segment", segmentObj);
JSONObject encryptSettingObj = new JSONObject();
encryptSettingObj.put("EncryptType", "Private");
JSONObject packageSettingObj = new JSONObject();
packageSettingObj.put("PackageType", "HLSPackage");
JSONObject packageConfigObj = new JSONObject();
packageConfigObj.put("BandWidth", "900000");
packageSettingObj.put("PackageConfig",packageConfigObj);
JSONObject obj = new JSONObject();
obj.put("Video",videoObj);
obj.put("Audio", audioObj);
obj.put("Container", containerObj);
obj.put("MuxConfig", muxConfigObj);
obj.put("EncryptSetting", encryptSettingObj);
//obj.put("PackageSetting", packageSettingObj);
obj.put("WatermarkIds", watermarkIds);
obj.put("Definition", "SD"); //原画
obj.put("TemplateName",templateName);
JSONArray array = new JSONArray();
array.add(obj);
//生成私有参数,不同API需要修改
Map<String,String> privateParams = new HashMap<String,String>();
privateParams.put("Action", "AddTranscodeTemplateGroup");
privateParams.put("Name", templateName);
privateParams.put("TranscodeTemplateList", array.toJSONString());
System.out.println(array.toJSONString());
//生成公共参数,不需要修改
Map<String, String> publicParams = AliyunSign.generatePublicParamters();
//生成OpenAPI地址,不需要修改
String URL = AliyunSign.generateOpenAPIURL(publicParams, privateParams);
//发送HTTP GET 请求
String result = HttpUtil.get(URL);
System.out.println(result);
return result;
}
}
package com.egolm.film.util;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.SignatureException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SimpleTimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import com.egolm.common.DateUtil;
import com.egolm.common.StringUtil;
public class AliyunSign {
private final static Logger LOG = Logger.getLogger(AliyunSign.class.getName());
private final static String HMAC_SHA1_ALGORITHM = "HmacSHA1";
private final static String VOD_DOMAIN = "http://vod.cn-shanghai.aliyuncs.com";
private final static String HTTP_METHOD = "GET";
private final static String ISO8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
/**
* 获取CQS 的字符串
*
* @param allParams
* @return
*/
private static String getCQS(List<String> allParams) {
ParamsComparator paramsComparator = new ParamsComparator();
Collections.sort(allParams, paramsComparator);
String cqString = "";
for (int i = 0; i < allParams.size(); i++) {
cqString += allParams.get(i);
if (i != allParams.size() - 1) {
cqString += "&";
}
}
return cqString;
}
private static class ParamsComparator implements Comparator<String> {
@Override
public int compare(String lhs, String rhs) {
return lhs.compareTo(rhs);
}
}
/**
* 参数urlEncode
*
* @param value
* @return
*/
private static String percentEncode(String value) {
try {
String urlEncodeOrignStr = URLEncoder.encode(value, "UTF-8");
String plusReplaced = urlEncodeOrignStr.replace("+", "%20");
String starReplaced = plusReplaced.replace("*", "%2A");
String waveReplaced = starReplaced.replace("%7E", "~");
return waveReplaced;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return value;
}
private static List<String> getAllParams(Map<String, String> publicParams, Map<String, String> privateParams) {
List<String> encodeParams = new ArrayList<String>();
if (publicParams != null) {
for (String key : publicParams.keySet()) {
String value = publicParams.get(key);
//将参数和值都urlEncode一下。
String encodeKey = percentEncode(key);
String encodeVal = percentEncode(value);
encodeParams.add(encodeKey + "=" + encodeVal);
}
}
if (privateParams != null) {
for (String key : privateParams.keySet()) {
String value = privateParams.get(key);
//将参数和值都urlEncode一下。
String encodeKey = percentEncode(key);
String encodeVal = percentEncode(value);
encodeParams.add(encodeKey + "=" + encodeVal);
}
}
return encodeParams;
}
private static String hmacSHA1Signature(String accessKeySecret, String stringtoSign) {
try {
String key = accessKeySecret + "&";
try {
SecretKeySpec signKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signKey);
byte[] rawHmac = mac.doFinal(stringtoSign.getBytes());
//按照Base64 编码规则把上面的 HMAC 值编码成字符串,即得到签名值(Signature)
return StringUtil.encodeBase64String(rawHmac);
} catch (Exception e) {
throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
}
} catch (SignatureException e) {
e.printStackTrace();
}
return "";
}
private static void out(String newLine) {
LOG.log(Level.INFO, newLine);
}
/**
* @param domain 请求地址
* @param httpMethod HTTP请求方式GET,POST等
* @param publicParams 公共参数
* @param privateParams 接口的私有参数
* @return 最后的url
*/
public static String generateURL(String httpMethod,String access_key_secret, Map<String, String> publicParams, Map<String, String> privateParams) {
List<String> allEncodeParams = getAllParams(publicParams, privateParams);
String cqsString = getCQS(allEncodeParams);
out("CanonicalizedQueryString = " + cqsString);
String stringToSign = httpMethod + "&" + percentEncode("/") + "&" + percentEncode(cqsString);
out("StringtoSign = " + stringToSign);
String signature = hmacSHA1Signature(access_key_secret, stringToSign);
out("Signature = " + signature);
return VOD_DOMAIN + "?" + cqsString + "&" + percentEncode("Signature") + "=" + percentEncode(signature);
}
/**
* 生成当前UTC时间戳
*
* @return
*/
public static String generateTimestamp() {
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat df = new SimpleDateFormat(ISO8601_DATE_FORMAT);
df.setTimeZone(new SimpleTimeZone(0, "GMT"));
return df.format(date);
}
public static void main(String[] args) {
Map<String,String> publicParams = new HashMap<String,String>();
publicParams.put("Format", "JSON");
publicParams.put("Version", "2017-03-21");
publicParams.put("AccessKeyId", "LTAIOtHCCpDLXYp8");
publicParams.put("SignatureMethod", "HMAC-SHA1");
publicParams.put("Timestamp", DateUtil.format(new Date(), DateUtil.FMT_UTC_ALIYUN));
publicParams.put("SignatureVersion", "1.0");
publicParams.put("SignatureNonce", StringUtil.getNonceStr());
Map<String,String> privateParams = new HashMap<String,String>();
privateParams.put("Action", "GetMezzanineInfo");
privateParams.put("VideoId", "818e5a5ce8b749d79ee61f3debed95bc");
System.out.println(generateURL( HTTP_METHOD, "LTAIOtHCCpDLXYp8", publicParams, privateParams));
}
}
package com.egolm.film.util;
import sun.misc.BASE64Encoder;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import com.egolm.common.HttpUtil;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.SignatureException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* 视频点播OpenAPI调用示例
* 以GetVideoPlayAuth接口为例,其他接口请替换相应接口名称及私有参数
*/
public class AliyunSign {
//账号AK信息请填写(必选)
private static String access_key_id = "LTAIOtHCCpDLXYp8";
//账号AK信息请填写(必选)
private static String access_key_secret = "9XTHW7P9TTRvCsBHBSclOue2tdWOoa";
//STS临时授权方式访问时该参数为必选,使用主账号AK和RAM子账号AK不需要填写
private static String security_token = "";
//以下参数不需要修改
private final static String VOD_DOMAIN = "http://vod.cn-shanghai.aliyuncs.com";
private final static String ISO8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
private final static String HTTP_METHOD = "GET";
private final static String HMAC_SHA1_ALGORITHM = "HmacSHA1";
private final static String UTF_8 = "utf-8";
private final static Logger LOG = Logger.getLogger(AliyunSign.class.getName());
public static void main(String[] args) throws IOException {
//生成私有参数,不同API需要修改
Map<String, String> privateParams = generatePrivateParamters();
//生成公共参数,不需要修改
Map<String, String> publicParams = generatePublicParamters();
//生成OpenAPI地址,不需要修改
String URL = generateOpenAPIURL(publicParams, privateParams);
//发送HTTP GET 请求
String result = HttpUtil.get(URL);
System.out.println(result);
}
/**
* 生成视频点播OpenAPI私有参数
* 不同API需要修改此方法中的参数
*
* @return
*/
private static Map<String, String> generatePrivateParamters() {
// 接口私有参数列表, 不同API请替换相应参数
Map<String, String> privateParams = new HashMap<>();
// 视频ID
privateParams.put("VideoId", "5aed81b74ba84920be578cdfe004af4b");
// API名称
privateParams.put("Action", "GetVideoPlayAuth");
return privateParams;
}
/**
* 生成视频点播OpenAPI公共参数
* 不需要修改
*
* @return
*/
public static Map<String, String> generatePublicParamters() {
Map<String, String> publicParams = new HashMap<>();
publicParams.put("Format", "JSON");
publicParams.put("Version", "2017-03-21");
publicParams.put("AccessKeyId", access_key_id);
publicParams.put("SignatureMethod", "HMAC-SHA1");
publicParams.put("Timestamp", generateTimestamp());
publicParams.put("SignatureVersion", "1.0");
publicParams.put("SignatureNonce", generateRandom());
if (security_token != null && security_token.length() > 0) {
publicParams.put("SecurityToken", security_token);
}
return publicParams;
}
/**
* 生成OpenAPI地址
* @param privateParams
* @return
* @throws Exception
*/
public static String generateOpenAPIURL(Map<String, String> publicParams, Map<String, String> privateParams) {
return generateURL(VOD_DOMAIN, HTTP_METHOD, publicParams, privateParams);
}
/**
* @param domain 请求地址
* @param httpMethod HTTP请求方式GET,POST等
* @param publicParams 公共参数
* @param privateParams 接口的私有参数
* @return 最后的url
*/
private static String generateURL(String domain, String httpMethod, Map<String, String> publicParams, Map<String, String> privateParams) {
List<String> allEncodeParams = getAllParams(publicParams, privateParams);
String cqsString = getCQS(allEncodeParams);
out("CanonicalizedQueryString = " + cqsString);
String stringToSign = httpMethod + "&" + percentEncode("/") + "&" + percentEncode(cqsString);
out("StringtoSign = " + stringToSign);
String signature = hmacSHA1Signature(access_key_secret, stringToSign);
out("Signature = " + signature);
return domain + "?" + cqsString + "&" + percentEncode("Signature") + "=" + percentEncode(signature);
}
private static List<String> getAllParams(Map<String, String> publicParams, Map<String, String> privateParams) {
List<String> encodeParams = new ArrayList<String>();
if (publicParams != null) {
for (String key : publicParams.keySet()) {
String value = publicParams.get(key);
//将参数和值都urlEncode一下。
String encodeKey = percentEncode(key);
String encodeVal = percentEncode(value);
encodeParams.add(encodeKey + "=" + encodeVal);
}
}
if (privateParams != null) {
for (String key : privateParams.keySet()) {
String value = privateParams.get(key);
//将参数和值都urlEncode一下。
String encodeKey = percentEncode(key);
String encodeVal = percentEncode(value);
encodeParams.add(encodeKey + "=" + encodeVal);
}
}
return encodeParams;
}
/**
* 参数urlEncode
*
* @param value
* @return
*/
private static String percentEncode(String value) {
try {
String urlEncodeOrignStr = URLEncoder.encode(value, "UTF-8");
String plusReplaced = urlEncodeOrignStr.replace("+", "%20");
String starReplaced = plusReplaced.replace("*", "%2A");
String waveReplaced = starReplaced.replace("%7E", "~");
return waveReplaced;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return value;
}
/**
* 获取CQS 的字符串
*
* @param allParams
* @return
*/
private static String getCQS(List<String> allParams) {
ParamsComparator paramsComparator = new ParamsComparator();
Collections.sort(allParams, paramsComparator);
String cqString = "";
for (int i = 0; i < allParams.size(); i++) {
cqString += allParams.get(i);
if (i != allParams.size() - 1) {
cqString += "&";
}
}
return cqString;
}
private static class ParamsComparator implements Comparator<String> {
@Override
public int compare(String lhs, String rhs) {
return lhs.compareTo(rhs);
}
}
private static String hmacSHA1Signature(String accessKeySecret, String stringtoSign) {
try {
String key = accessKeySecret + "&";
try {
SecretKeySpec signKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signKey);
byte[] rawHmac = mac.doFinal(stringtoSign.getBytes());
//按照Base64 编码规则把上面的 HMAC 值编码成字符串,即得到签名值(Signature)
return new String(new BASE64Encoder().encode(rawHmac));
} catch (Exception e) {
throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
}
} catch (SignatureException e) {
e.printStackTrace();
}
return "";
}
/**
* 生成随机数
*
* @return
*/
private static String generateRandom() {
String signatureNonce = UUID.randomUUID().toString();
return signatureNonce;
}
/**
* 生成当前UTC时间戳
*
* @return
*/
public static String generateTimestamp() {
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat df = new SimpleDateFormat(ISO8601_DATE_FORMAT);
df.setTimeZone(new SimpleTimeZone(0, "GMT"));
return df.format(date);
}
private static String httpGet(String url) throws IOException {
/*
* Read and covert a inputStream to a String.
* Referred this:
* http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string
*/
out("URL = " + url);
@SuppressWarnings("resource")
Scanner s = new Scanner(new URL(url).openStream(), UTF_8).useDelimiter("\\A");
try {
String resposne = s.hasNext() ? s.next() : "true";
out("Response = " + resposne);
return resposne;
} finally {
s.close();
}
}
private static void out(String newLine) {
LOG.log(Level.INFO, newLine);
}
}
\ No newline at end of file
package com.egolm.film.util;
import java.util.HashMap;
import java.util.Map;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoRequest;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoRequest;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import com.egolm.common.HttpsUtil;
import com.egolm.film.config.XRException;
public class AliyunUtil {
private String accessKeyId = "";//"LTAIOtHCCpDLXYp8";
private String accessKeySecret = "";//"9XTHW7P9TTRvCsBHBSclOue2tdWOoa";
private final DefaultAcsClient aliyunClient;
public AliyunUtil() {
this.aliyunClient = new DefaultAcsClient(DefaultProfile.getProfile("cn-shanghai", accessKeyId, accessKeySecret));
}
public AliyunUtil(String accessKeyId,String accessKeySecret) {
this.accessKeyId = accessKeyId;
this.accessKeySecret = accessKeySecret;
this.aliyunClient = new DefaultAcsClient(DefaultProfile.getProfile("cn-shanghai", accessKeyId, accessKeySecret));
}
/**
*
* @Title: createUploadVideo @Description: 获取视频上传凭证和地址 @param: @param
* client @param: @return @return: String @throws
*/
public CreateUploadVideoResponse createUploadVideo(Map<String,Object> params) {
CreateUploadVideoRequest request = new CreateUploadVideoRequest();
CreateUploadVideoResponse response = null;
try {
/*
* 必选,视频源文件名称(必须带后缀, 支持 ".3gp", ".asf", ".avi", ".dat", ".dv", ".flv", ".f4v",
* ".gif", ".m2t", ".m3u8", ".m4v", ".mj2", ".mjpeg", ".mkv", ".mov", ".mp4",
* ".mpe", ".mpg", ".mpeg", ".mts", ".ogg", ".qt", ".rm", ".rmvb", ".swf",
* ".ts", ".vob", ".wmv", ".webm"".aac", ".ac3", ".acm", ".amr", ".ape", ".caf",
* ".flac", ".m4a", ".mp3", ".ra", ".wav", ".wma")
*/
request.setFileName(params.get("fileName")+"");
// 必选,视频标题
request.setTitle(params.get("title")+"");
// 可选,分类ID
request.setCateId(params.get("cateId")==null?0l:Long.valueOf(params.get("cateId")+""));
// 可选,视频标签,多个用逗号分隔
request.setTags(params.get("tags")+"");
// 可选,视频描述
request.setDescription(params.get("description")+"");
response = aliyunClient.getAcsResponse(request);
} catch (ServerException e) {
System.out.println("CreateUploadVideoRequest Server Exception:");
e.printStackTrace();
return null;
} catch (ClientException e) {
System.out.println("CreateUploadVideoRequest Client Exception:");
e.printStackTrace();
return null;
}
System.out.println("RequestId:" + response.getRequestId());
System.out.println("UploadAuth:" + response.getUploadAuth());
System.out.println("UploadAddress:" + response.getUploadAddress());
return response;
}
/**
*
* @Title: refreshUploadVideo
* @Description: 刷新视频上传凭证
* @param: @param client
* @param: @param videoId
* @return: void
* @throws
*/
public RefreshUploadVideoResponse refreshUploadVideo(String videoId) {
RefreshUploadVideoRequest request = new RefreshUploadVideoRequest();
RefreshUploadVideoResponse response = null;
try {
request.setVideoId(videoId);
response = aliyunClient.getAcsResponse(request);
System.out.println("RequestId:" + response.getRequestId());
System.out.println("UploadAuth:" + response.getUploadAuth());
} catch (ServerException e) {
System.out.println("RefreshUploadVideoRequest Server Exception:");
e.printStackTrace();
} catch (ClientException e) {
System.out.println("RefreshUploadVideoRequest Client Exception:");
e.printStackTrace();
}
return response;
}
/**
*
* @Title: getVideoPlayAuth
* @Description: 获取播放凭证
* @param: @param videoId
* @param: @return
* @return: GetVideoPlayAuthResponse
* @throws
*/
public GetVideoPlayAuthResponse getVideoPlayAuth(String videoId) {
GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
request.setVideoId(videoId);
GetVideoPlayAuthResponse response = null;
try {
response = aliyunClient.getAcsResponse(request);
} catch (ServerException e) {
throw new XRException("GetVideoPlayAuthRequest Server failed");
} catch (ClientException e) {
throw new XRException("GetVideoPlayAuthRequest Client failed");
}
response.getPlayAuth(); //播放凭证
response.getVideoMeta(); //视频Meta信息
return response;
}
@SuppressWarnings("deprecation")
public void createSts() {
String endpoint = "sts.aliyuncs.com";
String accessKeyId = this.accessKeyId;
String accessKeySecret = this.accessKeySecret;
String roleArn = "acs:ram::1877540435175471:role/siffvodrole";
String roleSessionName = "stsVideo";
String policy = "{\r\n" +
" \"Statement\": [\r\n" +
" {\r\n" +
" \"Action\": \"sts:AssumeRole\",\r\n" +
" \"Effect\": \"Allow\",\r\n" +
" \"Principal\": {\r\n" +
" \"RAM\": [\r\n" +
" \"acs:ram::1877540435175471:root\"\r\n" +
" ]\r\n" +
" }\r\n" +
" }\r\n" +
" ],\r\n" +
" \"Version\": \"1\"\r\n" +
"}";
System.out.println(policy);
try {
// 添加endpoint(直接使用STS endpoint,前两个参数留空,无需添加region ID)
DefaultProfile.addEndpoint("", "", "Sts", endpoint);
// 构造default profile(参数留空,无需添加region ID)
IClientProfile profile = DefaultProfile.getProfile("", accessKeyId, accessKeySecret);
// 用profile构造client
DefaultAcsClient client = new DefaultAcsClient(profile);
final AssumeRoleRequest request = new AssumeRoleRequest();
request.setMethod(MethodType.POST);
request.setRoleArn(roleArn);
request.setRoleSessionName(roleSessionName);
// request.setPolicy(policy); // Optional
final AssumeRoleResponse response = client.getAcsResponse(request);
System.out.println("Expiration: " + response.getCredentials().getExpiration());
System.out.println("Access Key Id: " + response.getCredentials().getAccessKeyId());
System.out.println("Access Key Secret: " + response.getCredentials().getAccessKeySecret());
System.out.println("Security Token: " + response.getCredentials().getSecurityToken());
System.out.println("RequestId: " + response.getRequestId());
} catch (ClientException e) {
System.out.println("Failed:");
System.out.println("Error code: " + e.getErrCode());
System.out.println("Error message: " + e.getErrMsg());
System.out.println("RequestId: " + e.getRequestId());
}
}
/**
* https://help.aliyun.com/document_detail/59624.html?spm=a2c4g.11174283.6.678.4e66149buh5G0P
* @Title: getVideoSourceFile
* @Description: 获取视频源文件地址
* @param:
* @return: void
* @throws
*/
public void getVideoSourceFile(String videoId) {
Map<String,String> publicParams = new HashMap<String,String>();
/* publicParams.put("Format", "JSON");
publicParams.put("Version", "2017-03-21");
publicParams.put("AccessKeyId", this.accessKeyId);
publicParams.put("SignatureMethod", "HMAC-SHA1");
publicParams.put("Timestamp", AliyunSign.generateTimestamp());
publicParams.put("SignatureVersion", "1.0");
publicParams.put("SignatureNonce", StringUtil.getNonceStr()); */
publicParams.put("Format", "JSON");
publicParams.put("Version", "2017-03-21");
publicParams.put("AccessKeyId", "111");
publicParams.put("SignatureMethod", "HMAC-SHA1");
publicParams.put("Timestamp","2018-11-09T08%3A14%3A30Z");
publicParams.put("SignatureVersion", "1.0");
publicParams.put("SignatureNonce", "f4291034-4f94-4dc2-bb67-02bbef57c46b");
Map<String,String> privateParams = new HashMap<String,String>();
/* privateParams.put("Action", "GetMezzanineInfo");
privateParams.put("VideoId", "818e5a5ce8b749d79ee61f3debed95bc");*/
// 视频ID
privateParams.put("VideoId", "5aed81b74ba84920be578cdfe004af4b");
// API名称
privateParams.put("Action", "GetVideoPlayAuth");
String url = AliyunSign.generateURL("GET", this.accessKeyId, publicParams, privateParams);
String result = HttpsUtil.doGet(url);
System.out.println(result);
}
public static void main(String[] args) {
AliyunUtil aliyunUtil = new AliyunUtil("111","9XTHW7P9TTRvCsBHBSclOue2tdWOoa");
//aliyunUtil.createSts();
aliyunUtil.getVideoSourceFile("d4b55faeb1b24fb4a4ee06e994e90b76");
}
}
package com.egolm.film.util;
import java.util.HashMap;
import java.util.Map;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoRequest;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoRequest;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import com.egolm.common.HttpsUtil;
import com.egolm.film.config.XRException;
public class AliyunUtil {
private String accessKeyId = "";//"LTAIOtHCCpDLXYp8";
private String accessKeySecret = "";//"9XTHW7P9TTRvCsBHBSclOue2tdWOoa";
private final DefaultAcsClient aliyunClient;
public AliyunUtil() {
this.aliyunClient = new DefaultAcsClient(DefaultProfile.getProfile("cn-shanghai", accessKeyId, accessKeySecret));
}
public AliyunUtil(String accessKeyId,String accessKeySecret) {
this.accessKeyId = accessKeyId;
this.accessKeySecret = accessKeySecret;
this.aliyunClient = new DefaultAcsClient(DefaultProfile.getProfile("cn-shanghai", accessKeyId, accessKeySecret));
}
/**
*
* @Title: createUploadVideo @Description: 获取视频上传凭证和地址 @param: @param
* client @param: @return @return: String @throws
*/
public CreateUploadVideoResponse createUploadVideo(Map<String,Object> params) {
CreateUploadVideoRequest request = new CreateUploadVideoRequest();
CreateUploadVideoResponse response = null;
try {
/*
* 必选,视频源文件名称(必须带后缀, 支持 ".3gp", ".asf", ".avi", ".dat", ".dv", ".flv", ".f4v",
* ".gif", ".m2t", ".m3u8", ".m4v", ".mj2", ".mjpeg", ".mkv", ".mov", ".mp4",
* ".mpe", ".mpg", ".mpeg", ".mts", ".ogg", ".qt", ".rm", ".rmvb", ".swf",
* ".ts", ".vob", ".wmv", ".webm"".aac", ".ac3", ".acm", ".amr", ".ape", ".caf",
* ".flac", ".m4a", ".mp3", ".ra", ".wav", ".wma")
*/
request.setFileName(params.get("fileName")+"");
// 必选,视频标题
request.setTitle(params.get("title")+"");
// 可选,分类ID
request.setCateId(params.get("cateId")==null?0l:Long.valueOf(params.get("cateId")+""));
// 可选,视频标签,多个用逗号分隔
request.setTags(params.get("tags")+"");
// 可选,视频描述
request.setDescription(params.get("description")+"");
response = aliyunClient.getAcsResponse(request);
} catch (ServerException e) {
System.out.println("CreateUploadVideoRequest Server Exception:");
e.printStackTrace();
return null;
} catch (ClientException e) {
System.out.println("CreateUploadVideoRequest Client Exception:");
e.printStackTrace();
return null;
}
System.out.println("RequestId:" + response.getRequestId());
System.out.println("UploadAuth:" + response.getUploadAuth());
System.out.println("UploadAddress:" + response.getUploadAddress());
return response;
}
/**
*
* @Title: refreshUploadVideo
* @Description: 刷新视频上传凭证
* @param: @param client
* @param: @param videoId
* @return: void
* @throws
*/
public RefreshUploadVideoResponse refreshUploadVideo(String videoId) {
RefreshUploadVideoRequest request = new RefreshUploadVideoRequest();
RefreshUploadVideoResponse response = null;
try {
request.setVideoId(videoId);
response = aliyunClient.getAcsResponse(request);
System.out.println("RequestId:" + response.getRequestId());
System.out.println("UploadAuth:" + response.getUploadAuth());
} catch (ServerException e) {
System.out.println("RefreshUploadVideoRequest Server Exception:");
e.printStackTrace();
} catch (ClientException e) {
System.out.println("RefreshUploadVideoRequest Client Exception:");
e.printStackTrace();
}
return response;
}
/**
*
* @Title: getVideoPlayAuth
* @Description: 获取播放凭证
* @param: @param videoId
* @param: @return
* @return: GetVideoPlayAuthResponse
* @throws
*/
public GetVideoPlayAuthResponse getVideoPlayAuth(String videoId) {
GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
request.setVideoId(videoId);
GetVideoPlayAuthResponse response = null;
try {
response = aliyunClient.getAcsResponse(request);
} catch (ServerException e) {
throw new XRException("GetVideoPlayAuthRequest Server failed");
} catch (ClientException e) {
throw new XRException("GetVideoPlayAuthRequest Client failed");
}
response.getPlayAuth(); //播放凭证
response.getVideoMeta(); //视频Meta信息
return response;
}
@SuppressWarnings("deprecation")
public void createSts() {
String endpoint = "sts.aliyuncs.com";
String accessKeyId = this.accessKeyId;
String accessKeySecret = this.accessKeySecret;
String roleArn = "acs:ram::1877540435175471:role/siffvodrole";
String roleSessionName = "stsVideo";
String policy = "{\r\n" +
" \"Statement\": [\r\n" +
" {\r\n" +
" \"Action\": \"sts:AssumeRole\",\r\n" +
" \"Effect\": \"Allow\",\r\n" +
" \"Principal\": {\r\n" +
" \"RAM\": [\r\n" +
" \"acs:ram::1877540435175471:root\"\r\n" +
" ]\r\n" +
" }\r\n" +
" }\r\n" +
" ],\r\n" +
" \"Version\": \"1\"\r\n" +
"}";
System.out.println(policy);
try {
// 添加endpoint(直接使用STS endpoint,前两个参数留空,无需添加region ID)
DefaultProfile.addEndpoint("", "", "Sts", endpoint);
// 构造default profile(参数留空,无需添加region ID)
IClientProfile profile = DefaultProfile.getProfile("", accessKeyId, accessKeySecret);
// 用profile构造client
DefaultAcsClient client = new DefaultAcsClient(profile);
final AssumeRoleRequest request = new AssumeRoleRequest();
request.setMethod(MethodType.POST);
request.setRoleArn(roleArn);
request.setRoleSessionName(roleSessionName);
// request.setPolicy(policy); // Optional
final AssumeRoleResponse response = client.getAcsResponse(request);
System.out.println("Expiration: " + response.getCredentials().getExpiration());
System.out.println("Access Key Id: " + response.getCredentials().getAccessKeyId());
System.out.println("Access Key Secret: " + response.getCredentials().getAccessKeySecret());
System.out.println("Security Token: " + response.getCredentials().getSecurityToken());
System.out.println("RequestId: " + response.getRequestId());
} catch (ClientException e) {
System.out.println("Failed:");
System.out.println("Error code: " + e.getErrCode());
System.out.println("Error message: " + e.getErrMsg());
System.out.println("RequestId: " + e.getRequestId());
}
}
/**
* https://help.aliyun.com/document_detail/59624.html?spm=a2c4g.11174283.6.678.4e66149buh5G0P
* @Title: getVideoSourceFile
* @Description: 获取视频源文件地址
* @param:
* @return: void
* @throws
*/
public void getVideoSourceFile(String videoId) {
Map<String,String> publicParams = new HashMap<String,String>();
/* publicParams.put("Format", "JSON");
publicParams.put("Version", "2017-03-21");
publicParams.put("AccessKeyId", this.accessKeyId);
publicParams.put("SignatureMethod", "HMAC-SHA1");
publicParams.put("Timestamp", AliyunSign.generateTimestamp());
publicParams.put("SignatureVersion", "1.0");
publicParams.put("SignatureNonce", StringUtil.getNonceStr()); */
publicParams.put("Format", "JSON");
publicParams.put("Version", "2017-03-21");
publicParams.put("AccessKeyId", "111");
publicParams.put("SignatureMethod", "HMAC-SHA1");
publicParams.put("Timestamp","2018-11-09T08%3A14%3A30Z");
publicParams.put("SignatureVersion", "1.0");
publicParams.put("SignatureNonce", "f4291034-4f94-4dc2-bb67-02bbef57c46b");
Map<String,String> privateParams = new HashMap<String,String>();
/* privateParams.put("Action", "GetMezzanineInfo");
privateParams.put("VideoId", "818e5a5ce8b749d79ee61f3debed95bc");*/
// 视频ID
privateParams.put("VideoId", "5aed81b74ba84920be578cdfe004af4b");
// API名称
privateParams.put("Action", "GetVideoPlayAuth");
String url = AliyunSign.generateOpenAPIURL( publicParams, privateParams);
String result = HttpsUtil.doGet(url);
System.out.println(result);
}
public static void main(String[] args) {
AliyunUtil aliyunUtil = new AliyunUtil("111","9XTHW7P9TTRvCsBHBSclOue2tdWOoa");
//aliyunUtil.createSts();
aliyunUtil.getVideoSourceFile("d4b55faeb1b24fb4a4ee06e994e90b76");
}
}
......@@ -36,5 +36,6 @@ spring.datasource.min-idle=10
aliyun.sts.accessKeyId=LTAIOtHCCpDLXYp8
aliyun.sts.accessKeySecret=9XTHW7P9TTRvCsBHBSclOue2tdWOoa
#\u89C6\u9891\u8F6C\u7801ID
aliyun.video.templateId=d9f4a79cba14ce4cbc98d6516d35bf37
opt.project.type=1
\ No newline at end of file
......@@ -35,5 +35,6 @@ spring.datasource.min-idle=10
aliyun.sts.accessKeyId=LTAIOtHCCpDLXYp8
aliyun.sts.accessKeySecret=9XTHW7P9TTRvCsBHBSclOue2tdWOoa
#\u89C6\u9891\u8F6C\u7801ID
aliyun.video.templateId=d9f4a79cba14ce4cbc98d6516d35bf37
opt.project.type=1
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment