package com.cnd3b.restcontroller.enterprise.datacenter; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.aliyun.oss.OSSClient; import com.aliyun.oss.common.utils.BinaryUtil; import com.aliyun.oss.model.*; import com.cnd3b.common.Controller; import com.cnd3b.common.data.Rows; import com.cnd3b.common.data.SQLFactory; import com.cnd3b.utility.aliyun.oss.AliyunOSSConfigConstant; import com.cnd3b.utility.aliyun.oss.AliyunOSSUtil; import org.bytedeco.javacpp.presets.opencv_core; import p2.common.parse.A; import p2.common.parse.S; import p2.pao.PaoRemote; import p2.pao.PaoSetRemote; import p2.pao.SqlFormat; import p2.util.P2Exception; import java.io.ByteArrayInputStream; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.*; import static com.cnd3b.service.GetWechatData.sortByStartDigits; import static com.cnd3b.utility.aliyun.oss.AliyunOSSUtil.*; public class datacenter extends Controller { // String url = BUCKE_NAME_1 + "." + AliyunOSSConfigConstant.END_POINT; //根目录 String rootpath = "资料中心/"; /** * 构造函数 * * @param content */ public datacenter(JSONObject content) { super(content); } /** * 创建文件夹(OSS) * * @return */ public String createFolder() { String folderName = content.getString("folderName"); if (folderName.equals("") || folderName == null) { return getErrReturnObject().setErrMsg("文件夹名称不能为空").toString(); } ossClient.putObject(new PutObjectRequest(BUCKE_NAME_1, rootpath + folderName, new ByteArrayInputStream("".getBytes()))); ossClient.shutdown(); return getSucReturnObject().toString(); } /** * 删除文件夹(OSS) * * @return */ public String deleteFolder() { JSONArray jsonArray = content.getJSONArray("folderName"); if (jsonArray == null || jsonArray.size() == 0) { return getErrReturnObject().setErrMsg("文件夹名称不能为空").toString(); } ArrayList keysList = new ArrayList<>(); for (Object obj : jsonArray) { keysList.add(obj.toString()); ListObjectsRequest listObjectsRequest = new ListObjectsRequest(BUCKE_NAME_1); // 设置prefix参数来获取fun目录下的所有文件。 listObjectsRequest.setPrefix(obj.toString()); // 递归列举目录下的所有文件。 ObjectListing listing = ossClient.listObjects(listObjectsRequest); // 遍历所有文件。 for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) { String key = objectSummary.getKey(); keysList.add(key); } } DeleteObjectsRequest request = new DeleteObjectsRequest(BUCKE_NAME_1); request.setKeys(keysList); // 发起deleteObjects请求。 ossClient.deleteObjects(request); // // 查看删除结果。 // for (String o : delObjResult.getDeletedObjects()) { // String keyName = null; // try { // keyName = URLDecoder.decode(o, "UTF-8"); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // System.out.println("delete key name: " + keyName); // } ossClient.shutdown(); SQLFactory sqlFactory = new SQLFactory(this, "删除文件夹"); sqlFactory.addParameter_in("fpath", keysList); String sql = sqlFactory.getSQL(); dbConnect.runSqlUpdate(sql); return getSucReturnObject().toString(); } /** * 上传文件(OSS) * * @return */ public String uploadFile() { // String filePath = content.getString("filePath"); String folderPath = content.getString("folderPath"); String name = content.getString("filename"); String base64Str = content.getString("byteStr"); byte[] byteStr = Base64.getDecoder().decode(base64Str); // if (filePath.equals("") || filePath == null) { // return getErrReturnObject().setErrMsg("文件路径不能为空").toString(); // } // if (folderPath.equals("") || folderPath == null) { // folderPath = ""; // } // File file = new File(filePath); // if (!file.exists()) { // return getErrReturnObject().setErrMsg("文件不存在").toString(); // } String key = folderPath + name; System.err.println(key); ossClient.putObject(new PutObjectRequest(BUCKE_NAME_1, rootpath + key, new ByteArrayInputStream(byteStr))); ossClient.shutdown(); return getSucReturnObject().toString(); } /** * 删除文件(OSS) * * @return */ public String deleteFile() { JSONArray jsonArray = content.getJSONArray("folderName"); if (jsonArray == null || jsonArray.size() == 0) { return getErrReturnObject().setErrMsg("文件夹名称不能为空").toString(); } List keysList = new ArrayList<>(); for (Object obj : jsonArray) { keysList.add(obj.toString()); } DeleteObjectsRequest request = new DeleteObjectsRequest(BUCKE_NAME_1); request.setKeys(keysList); // 发起deleteObjects请求。 DeleteObjectsResult delObjResult = ossClient.deleteObjects(request); // 查看删除结果。 for (String o : delObjResult.getDeletedObjects()) { String keyName = null; try { keyName = URLDecoder.decode(o, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } System.out.println("delete key name: " + keyName); } ossClient.shutdown(); return getSucReturnObject().toString(); } /** * 获取根目录 * * @return */ public String getFolders() { // 构造ListObjectsRequest请求。 ListObjectsRequest listObjectsRequest = new ListObjectsRequest(BUCKE_NAME_1); // 设置正斜线(/)为文件夹的分隔符。 listObjectsRequest.setDelimiter("/"); // 列出fun目录下的所有文件和文件夹。 listObjectsRequest.setPrefix("资料中心/"); ObjectListing listing = ossClient.listObjects(listObjectsRequest); // 遍历所有commonPrefix。 ArrayList commonPrefixList = new ArrayList<>(); for (String commonPrefix : listing.getCommonPrefixes()) { String selectSql = "SELECT*FROM tfolder WHERE fpath='" + commonPrefix + "'"; Rows rows = dbConnect.runSqlQuery(selectSql); if (rows.isEmpty()) { inseretTfolder(commonPrefix); } commonPrefixList.add(commonPrefix); } // 关闭OSSClient。 ossClient.shutdown(); JSONObject object = new JSONObject(); object.put("folder", commonPrefixList); SQLFactory sqlFactory = new SQLFactory(this, "查询根目录"); sqlFactory.addParameter_in("fpath", commonPrefixList); String sql = sqlFactory.getSQL(); Rows rows = dbConnect.runSqlQuery(sql); return getSucReturnObject().setData(rows).toString(); } /** * 获取指定目录下的文件和文件夹 * * @return */ public String getFilesOfPath() { String folderPath = content.getString("folderPath"); // 构造ListObjectsRequest请求。 ListObjectsRequest listObjectsRequest = new ListObjectsRequest(BUCKE_NAME_1); // 设置正斜线(/)为文件夹的分隔符。 listObjectsRequest.setDelimiter("/"); // 列出fun目录下的所有文件和文件夹。 listObjectsRequest.setPrefix(folderPath); ObjectListing listing = ossClient.listObjects(listObjectsRequest); // 遍历所有文件。 System.out.println("Objects:"); List objectSummaryList = new ArrayList<>(); List sums = listing.getObjectSummaries(); //按照时间排序 Collections.sort(sums, (o1, o2) -> { // TODO Auto-generated method stub long dateTime1 = o1.getLastModified().getTime(); long dateTime2 = o2.getLastModified().getTime(); if (dateTime1 == dateTime2) { return 0; } else { //时间正序 // return dateTime1 > dateTime2 ? 1 : -1; //时间倒序 return dateTime1 > dateTime2 ? -1 : 1; } }); for (OSSObjectSummary objectSummary : sums) { if (!objectSummary.getKey().equals(folderPath)) { JSONObject object = new JSONObject(); object.put("key", objectSummary.getKey()); object.put("name", objectSummary.getKey().replace(folderPath, "")); object.put("size", objectSummary.getSize() / 1024); object.put("time", getDateTime_Str(objectSummary.getLastModified())); object.put("url", file_url + "/" + objectSummary.getKey()); objectSummaryList.add(object); } } // 遍历所有commonPrefix。 String newName = ""; Rows tempRows = dbConnect.runSqlQuery("SELECT tfilename from tfolder WHERE fpath = '" + folderPath + "'"); if (!tempRows.isEmpty()) { newName = tempRows.get(0).getString("tfilename"); } ArrayList commonPrefixList = new ArrayList<>(); ArrayList sqlList = new ArrayList<>(); for (String commonPrefix : listing.getCommonPrefixes()) { String selectSql = "SELECT tfilename FROM tfolder WHERE fpath='" + commonPrefix + "'"; Rows rows = dbConnect.runSqlQuery(selectSql); String[] tfilename; if (rows.isEmpty()) { tfilename = commonPrefix.split("/"); } else { tfilename = rows.get(0).getString("tfilename").split("/"); } sqlList.add(inseretOrUpdateTfolder(commonPrefix, newName + tfilename[tfilename.length - 1] + "/")); commonPrefixList.add(commonPrefix); } dbConnect.runSqlUpdate(sqlList); // 关闭OSSClient。 ossClient.shutdown(); SQLFactory sqlFactory = new SQLFactory(this, "查询根目录"); sqlFactory.addParameter_in("fpath", commonPrefixList); String sql = sqlFactory.getSQL(); Rows rows = dbConnect.runSqlQuery(sql); sortByStartDigits(objectSummaryList, "name"); sortByStartDigits(rows, "tfilename", newName); JSONObject object = new JSONObject(); object.put("files", objectSummaryList); object.put("folder", rows); return getSucReturnObject().setData(object).toString(); } /** * 更新文件夹名称 * * @return */ public String updateFolderName() { String oldName = content.get("oldName").toString(); String newName = content.get("newName").toString(); String sqlSelect = "SELECT*FROM tfolder WHERE tfilename='" + oldName + "'"; Rows rowsSelect = dbConnect.runSqlQuery(sqlSelect); if (rowsSelect.isEmpty()) { return getErrReturnObject().setErrMsg("未找到修改项").toString(); } String sqlCheck = "SELECT*FROM tfolder WHERE tfilename='" + newName + "'"; Rows rowsCheck = dbConnect.runSqlQuery(sqlCheck); if (!rowsCheck.isEmpty()) { return getErrReturnObject().setErrMsg("文件名称不能重名").toString(); } String sql = "update tfolder set tfilename=replace(tfilename,'" + oldName + "','" + newName + "') where tfilename like '" + oldName + "%'"; String res = dbConnect.runSqlUpdate(sql); return getSucReturnObject().setData(res).toString(); } //批量设置是否可下载,包含下级文件夹 public String isDownload() { JSONArray tfolderids = content.getJSONArray("tfolderids"); Boolean isdownload = content.getBooleanValue("isdownload"); String sql = ""; ArrayList sqlList = new ArrayList<>(); for (Object obj : tfolderids) { Long tfolderid = Long.valueOf(obj.toString()); String fpath = ""; Rows rows = dbConnect.runSqlQuery("SELECT fpath from tfolder WHERE tfolderid=" + tfolderid); if (!rows.isEmpty()) { fpath = rows.get(0).getString("fpath"); if (isdownload) { sql = "update tfolder set isdownload=" + 1 + " WHERE fpath like '" + fpath + "%'"; } else { sql = "update tfolder set isdownload=" + 0 + " WHERE fpath like '" + fpath + "%'"; } sqlList.add(sql); } } String res = dbConnect.runSqlUpdate(sqlList); return getSucReturnObject().setData(res).toString(); } public String inseretOrUpdateTfolder(String name, String name2) { Long id = createTableID("tfolder", "tfolderid"); // String sql = "INSERT INTO tfolder(tfolderid,rmkenable,fpath,createdate,tfilename) VALUES(" + id + ", 0,'" + name + "','" + getDateTime_Str() + "','" + name2 + "')"; SQLFactory sqlFactory = new SQLFactory(this, "插入文件夹"); sqlFactory.addParameter("tfolderid", id); sqlFactory.addParameter("fpath", name); sqlFactory.addParameter("tfilename", name2); return sqlFactory.getSQL(); } public void inseretTfolder(String name) { Long id = createTableID("tfolder", "tfolderid"); String sql = "INSERT INTO tfolder(tfolderid,rmkenable,fpath,createdate,tfilename) VALUES(" + id + ", 0,'" + name + "','" + getDateTime_Str() + "','" + name + "')"; dbConnect.runSqlUpdate(sql); } /** * 申请视频转码 * * @return */ public String applyTranscoding() throws P2Exception { //阿里云视频转码模板 String templateId = "S00000001-200030"; //大于这个码率进行视频转码,mov格式的直接转码 int tempBitrate = 1800; //获取支持的视频格式列表 ArrayList listVideo = getSupportVieoList(); String type = content.getString("type"); String key = content.getString("key"); String outKey = ""; if (type.equals("1")) { outKey = key; } else { outKey = "转码视频/" + key; } if (key.toLowerCase().contains("mov")) { AliyunOSSUtil.transcoding(templateId, key, outKey); if (type.equals("2")) { addTranscodingLog(key, outKey); } return getSucReturnObject().setData("MOV转码成功").toString(); } //查询是否是可支持转码的视频 boolean isVideo = false; for (String str : listVideo) { if (key.toLowerCase().contains(str.toLowerCase())) { isVideo = true; break; } } if (isVideo) { String res = AliyunOSSUtil.submitMediaInfoJob(key); JSONObject jsonObject = JSONObject.parseObject(res); //码率 String bitrate = "0"; if (jsonObject.containsKey("mediaInfoJob")) { JSONObject mediaInfoJob_jsonObject = jsonObject.getJSONObject("mediaInfoJob"); if (mediaInfoJob_jsonObject.containsKey("properties")) { JSONObject properties_jsonObject = mediaInfoJob_jsonObject.getJSONObject("properties"); bitrate = properties_jsonObject.getString("bitrate"); } } System.err.println(bitrate); if (Double.parseDouble(bitrate) > tempBitrate) { AliyunOSSUtil.transcoding(templateId, key, outKey); if (type.equals("2")) { addTranscodingLog(key, outKey); } return getSucReturnObject().setData("转码成功").toString(); } else { return getSucReturnObject().setData("码率低于" + tempBitrate + ",无须转码").toString(); } } else { return getSucReturnObject().setData("非视频格式,无法转码").toString(); } } // public String applyTranscodingOfPath() throws P2Exception { // String folderPath = content.getString("folderPath"); // List list = getOssFileList(folderPath); // //阿里云视频转码模板 // String templateId = "S00000001-200030"; // //大于这个码率进行视频转码,mov格式的直接转码 // int tempBitrate = 1800; // // for (String keyPath : list) { // // String key = keyPath; // if (key.toLowerCase().contains("mov")) { // AliyunOSSUtil.transcoding(templateId, key, key); // addTranscodingLog(key, key); // System.err.println("MOV转码成功:" + keyPath); // } else { // ArrayList listVideo = getSupportVieoList(); // //查询是否是可支持转码的视频 // boolean isVideo = false; // for (String str : listVideo) { // if (key.toLowerCase().contains(str.toLowerCase())) { // isVideo = true; // break; // } // } // if (isVideo) { // String res = AliyunOSSUtil.submitMediaInfoJob(key); // JSONObject jsonObject = JSONObject.parseObject(res); // //码率 // String bitrate = "0"; // if (jsonObject.containsKey("mediaInfoJob")) { // JSONObject mediaInfoJob_jsonObject = jsonObject.getJSONObject("mediaInfoJob"); // if (mediaInfoJob_jsonObject.containsKey("properties")) { // JSONObject properties_jsonObject = mediaInfoJob_jsonObject.getJSONObject("properties"); // bitrate = properties_jsonObject.getString("bitrate"); // } // } // System.err.println(bitrate); // if (Double.parseDouble(bitrate) > tempBitrate) { // AliyunOSSUtil.transcoding(templateId, key, key); // addTranscodingLog(key, key); // System.err.println("转码成功:" + keyPath); // // } else { // System.err.println("码率低于" + tempBitrate + ",无须转码"); // // } // } else { // System.err.println("非视频格式,无法转码"); // // } // } // // } // return getSucReturnObject().toString(); // } //支持转转码的格式 public ArrayList getSupportVieoList() { //3GP、AVI、FLV、MP4、M3U8、MPG、ASF、WMV、MKV、MOV、TS、WebM、MXF ArrayList list = new ArrayList<>(); list.add("3GP"); list.add("AVI"); list.add("FLV"); list.add("MP4"); list.add("M3U8"); list.add("MPG"); list.add("ASF"); list.add("WMV"); list.add("MKV"); list.add("MOV"); list.add("TS"); list.add("WebM"); list.add("MXF"); return list; } /** * 添加转码记录 * * @return */ public void addTranscodingLog(String tkey, String tkey_new) throws P2Exception { PaoSetRemote paoSetRemote = getP2ServerSystemPaoSet("TTRANSCODINGLOG", "tkey = '" + tkey + "'"); if (paoSetRemote.isEmpty()) { PaoRemote paoRemote = paoSetRemote.addAtEnd(); paoRemote.setValue("tkey", tkey, 11L); paoRemote.setValue("tkey_new", tkey_new, 11L); } else { PaoRemote paoRemote = paoSetRemote.getPao(0); paoRemote.setValue("tkey_new", tkey_new, 11L); } paoSetRemote.save(); } /** * 获取OSS上传签名信息 * * @return */ public String getOssSignature() { String key = content.getString("key"); // host的格式为 bucketname.endpoint String host = "https://" + BUCKE_NAME_1 + "." + END_POINT; // callbackUrl为 上传回调服务器的URL,请将下面的IP和Port配置为您自己的真实信息。 // String callbackUrl = "http://88.88.88.88:8888"; // 每一天产生一个文件夹 // 用户上传文件时指定的前缀,如果是 / 则自动检测为文件夹。 String dir = key; JSONObject jsonObject = new JSONObject(); //过期时间 100 秒 long expireTime = 600; long expireEndTime = System.currentTimeMillis() + expireTime * 1000; Date expiration = new Date(expireEndTime); // PostObject请求最大可支持的文件大小为5 GB,即CONTENT_LENGTH_RANGE为5*1024*1024*1024。 PolicyConditions policyConds = new PolicyConditions(); policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, Long.MAX_VALUE); policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir); String postPolicy = ossClient.generatePostPolicy(expiration, policyConds); byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8); String encodedPolicy = BinaryUtil.toBase64String(binaryData); String postSignature = ossClient.calculatePostSignature(postPolicy); jsonObject.put("OSSAccessKeyId", AccessKey_ID); jsonObject.put("policy", encodedPolicy); jsonObject.put("signature", postSignature); jsonObject.put("dir", dir); jsonObject.put("host", host); jsonObject.put("expire", String.valueOf(expireEndTime / 1000)); return getSucReturnObject().setData(jsonObject).toString(); } }