Commit e3025edb authored by Quxl's avatar Quxl
parents 363940c8 e9e40a82
...@@ -12,12 +12,16 @@ import org.springframework.web.bind.annotation.RequestMapping; ...@@ -12,12 +12,16 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody; 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.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse; import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse; import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import com.egolm.common.HttpUtil;
import com.egolm.common.StringUtil; import com.egolm.common.StringUtil;
import com.egolm.common.bean.Rjx; import com.egolm.common.bean.Rjx;
import com.egolm.film.api.service.Messages; import com.egolm.film.api.service.Messages;
import com.egolm.film.util.AliyunSign;
import com.egolm.film.util.AliyunUtil; import com.egolm.film.util.AliyunUtil;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
...@@ -36,6 +40,10 @@ public class AliyunApiController { ...@@ -36,6 +40,10 @@ public class AliyunApiController {
@Value("${aliyun.sts.accessKeySecret}") @Value("${aliyun.sts.accessKeySecret}")
private String accessKeySecret; private String accessKeySecret;
@Value("${aliyun.video.templateId}")
private String templateId;
@Autowired @Autowired
private Messages messages; private Messages messages;
...@@ -74,7 +82,7 @@ public class AliyunApiController { ...@@ -74,7 +82,7 @@ public class AliyunApiController {
return Rjx.jsonOk().set("RequestId", response.getRequestId()).set("UploadAuth", response.getUploadAuth()) return Rjx.jsonOk().set("RequestId", response.getRequestId()).set("UploadAuth", response.getUploadAuth())
.set("UploadAddress", response.getUploadAddress()) .set("UploadAddress", response.getUploadAddress())
.set("VideoId", response.getVideoId()); .set("VideoId", response.getVideoId()).set("templateId", templateId);
} }
...@@ -93,7 +101,7 @@ public class AliyunApiController { ...@@ -93,7 +101,7 @@ public class AliyunApiController {
AliyunUtil aliyunUtil = new AliyunUtil(accessKeyId,accessKeySecret); AliyunUtil aliyunUtil = new AliyunUtil(accessKeyId,accessKeySecret);
RefreshUploadVideoResponse response = aliyunUtil.refreshUploadVideo(videoId); RefreshUploadVideoResponse response = aliyunUtil.refreshUploadVideo(videoId);
if(response != null) { 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 { }else {
return Rjx.jsonErr().setCode(-1).setMessage("InvalidVideo.NotFound : The video does not exist."); return Rjx.jsonErr().setCode(-1).setMessage("InvalidVideo.NotFound : The video does not exist.");
} }
...@@ -129,5 +137,109 @@ public class AliyunApiController { ...@@ -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; 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.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.security.SignatureException; import java.security.SignatureException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.*;
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.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import javax.crypto.Mac; /**
import javax.crypto.spec.SecretKeySpec; * 视频点播OpenAPI调用示例
* 以GetVideoPlayAuth接口为例,其他接口请替换相应接口名称及私有参数
import com.egolm.common.DateUtil; */
import com.egolm.common.StringUtil;
public class AliyunSign { public class AliyunSign {
private final static Logger LOG = Logger.getLogger(AliyunSign.class.getName()); //账号AK信息请填写(必选)
private final static String HMAC_SHA1_ALGORITHM = "HmacSHA1"; 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 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'"; 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);
}
/** /**
* 获取CQS 的字符串 * 生成视频点播OpenAPI私有参数
* 不同API需要修改此方法中的参数
* *
* @param allParams
* @return * @return
*/ */
private static String getCQS(List<String> allParams) { private static Map<String, String> generatePrivateParamters() {
ParamsComparator paramsComparator = new ParamsComparator(); // 接口私有参数列表, 不同API请替换相应参数
Collections.sort(allParams, paramsComparator); Map<String, String> privateParams = new HashMap<>();
String cqString = ""; // 视频ID
for (int i = 0; i < allParams.size(); i++) { privateParams.put("VideoId", "5aed81b74ba84920be578cdfe004af4b");
cqString += allParams.get(i); // API名称
if (i != allParams.size() - 1) { privateParams.put("Action", "GetVideoPlayAuth");
cqString += "&"; return privateParams;
}
} }
return cqString; /**
} * 生成视频点播OpenAPI公共参数
private static class ParamsComparator implements Comparator<String> { * 不需要修改
@Override *
public int compare(String lhs, String rhs) { * @return
return lhs.compareTo(rhs); */
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;
} }
/** /**
* 参数urlEncode * 生成OpenAPI地址
* * @param privateParams
* @param value
* @return * @return
* @throws Exception
*/ */
private static String percentEncode(String value) { public static String generateOpenAPIURL(Map<String, String> publicParams, Map<String, String> privateParams) {
try { return generateURL(VOD_DOMAIN, HTTP_METHOD, publicParams, privateParams);
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;
/**
* @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) { private static List<String> getAllParams(Map<String, String> publicParams, Map<String, String> privateParams) {
...@@ -96,6 +135,51 @@ public class AliyunSign { ...@@ -96,6 +135,51 @@ public class AliyunSign {
return encodeParams; 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) { private static String hmacSHA1Signature(String accessKeySecret, String stringtoSign) {
try { try {
...@@ -106,7 +190,7 @@ public class AliyunSign { ...@@ -106,7 +190,7 @@ public class AliyunSign {
mac.init(signKey); mac.init(signKey);
byte[] rawHmac = mac.doFinal(stringtoSign.getBytes()); byte[] rawHmac = mac.doFinal(stringtoSign.getBytes());
//按照Base64 编码规则把上面的 HMAC 值编码成字符串,即得到签名值(Signature) //按照Base64 编码规则把上面的 HMAC 值编码成字符串,即得到签名值(Signature)
return StringUtil.encodeBase64String(rawHmac); return new String(new BASE64Encoder().encode(rawHmac));
} catch (Exception e) { } catch (Exception e) {
throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
} }
...@@ -115,26 +199,15 @@ public class AliyunSign { ...@@ -115,26 +199,15 @@ public class AliyunSign {
} }
return ""; return "";
} }
private static void out(String newLine) {
LOG.log(Level.INFO, newLine);
}
/** /**
* @param domain 请求地址 * 生成随机数
* @param httpMethod HTTP请求方式GET,POST等 *
* @param publicParams 公共参数 * @return
* @param privateParams 接口的私有参数
* @return 最后的url
*/ */
public static String generateURL(String httpMethod,String access_key_secret, Map<String, String> publicParams, Map<String, String> privateParams) { private static String generateRandom() {
List<String> allEncodeParams = getAllParams(publicParams, privateParams); String signatureNonce = UUID.randomUUID().toString();
String cqsString = getCQS(allEncodeParams); return signatureNonce;
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);
} }
/** /**
...@@ -149,21 +222,25 @@ public class AliyunSign { ...@@ -149,21 +222,25 @@ public class AliyunSign {
return df.format(date); return df.format(date);
} }
public static void main(String[] args) { private static String httpGet(String url) throws IOException {
Map<String,String> publicParams = new HashMap<String,String>(); /*
publicParams.put("Format", "JSON"); * Read and covert a inputStream to a String.
publicParams.put("Version", "2017-03-21"); * Referred this:
publicParams.put("AccessKeyId", "LTAIOtHCCpDLXYp8"); * http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string
publicParams.put("SignatureMethod", "HMAC-SHA1"); */
publicParams.put("Timestamp", DateUtil.format(new Date(), DateUtil.FMT_UTC_ALIYUN)); out("URL = " + url);
publicParams.put("SignatureVersion", "1.0"); @SuppressWarnings("resource")
publicParams.put("SignatureNonce", StringUtil.getNonceStr()); Scanner s = new Scanner(new URL(url).openStream(), UTF_8).useDelimiter("\\A");
try {
Map<String,String> privateParams = new HashMap<String,String>(); String resposne = s.hasNext() ? s.next() : "true";
privateParams.put("Action", "GetMezzanineInfo"); out("Response = " + resposne);
privateParams.put("VideoId", "818e5a5ce8b749d79ee61f3debed95bc"); return resposne;
} finally {
System.out.println(generateURL( HTTP_METHOD, "LTAIOtHCCpDLXYp8", publicParams, privateParams)); s.close();
}
}
private static void out(String newLine) {
LOG.log(Level.INFO, newLine);
} }
} }
\ No newline at end of file
...@@ -213,7 +213,7 @@ public class AliyunUtil { ...@@ -213,7 +213,7 @@ public class AliyunUtil {
// API名称 // API名称
privateParams.put("Action", "GetVideoPlayAuth"); privateParams.put("Action", "GetVideoPlayAuth");
String url = AliyunSign.generateURL("GET", this.accessKeyId, publicParams, privateParams); String url = AliyunSign.generateOpenAPIURL( publicParams, privateParams);
String result = HttpsUtil.doGet(url); String result = HttpsUtil.doGet(url);
System.out.println(result); System.out.println(result);
......
...@@ -36,5 +36,6 @@ spring.datasource.min-idle=10 ...@@ -36,5 +36,6 @@ spring.datasource.min-idle=10
aliyun.sts.accessKeyId=LTAIOtHCCpDLXYp8 aliyun.sts.accessKeyId=LTAIOtHCCpDLXYp8
aliyun.sts.accessKeySecret=9XTHW7P9TTRvCsBHBSclOue2tdWOoa aliyun.sts.accessKeySecret=9XTHW7P9TTRvCsBHBSclOue2tdWOoa
#\u89C6\u9891\u8F6C\u7801ID
aliyun.video.templateId=d9f4a79cba14ce4cbc98d6516d35bf37
opt.project.type=1 opt.project.type=1
\ No newline at end of file
...@@ -35,5 +35,6 @@ spring.datasource.min-idle=10 ...@@ -35,5 +35,6 @@ spring.datasource.min-idle=10
aliyun.sts.accessKeyId=LTAIOtHCCpDLXYp8 aliyun.sts.accessKeyId=LTAIOtHCCpDLXYp8
aliyun.sts.accessKeySecret=9XTHW7P9TTRvCsBHBSclOue2tdWOoa aliyun.sts.accessKeySecret=9XTHW7P9TTRvCsBHBSclOue2tdWOoa
#\u89C6\u9891\u8F6C\u7801ID
aliyun.video.templateId=d9f4a79cba14ce4cbc98d6516d35bf37
opt.project.type=1 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