├── README.md ├── RESTful service ├── UploadAudios.cs ├── UploadAudios.java ├── audio.js ├── audio.py ├── audio_erl ├── audios.rb ├── bucket.py ├── channel.py ├── channel_playback.py ├── delete_audios.php ├── get_ads.js ├── get_buckets.js ├── get_channel.js ├── get_channels.js ├── get_channels.php ├── get_monitor_stream.php ├── get_project.js ├── get_projects.js ├── list_buckets.php ├── monitor_add.js ├── monitor_add.py ├── monitor_api_for_broadcast_database.py ├── monitor_api_for_custom_streams.py ├── monitor_callback.php ├── monitor_callback.py ├── monitor_del.py ├── monitor_get.php ├── monitor_get.py ├── monitor_pause.php ├── monitor_pause.py ├── monitor_update.java ├── monitor_update.php ├── monitor_update.py ├── offlinedb.py ├── project.py ├── upload_audio.js └── upload_audios.php ├── identify protocol 1 (recommended) ├── IdentifyProtocolV1.cs ├── IdentifyProtocolV1.java ├── IdentifyProtocolV1.js ├── IdentifyProtocolV1.php ├── IdentifyProtocolV1.rb ├── IdentifyProtocolV1_1.py ├── IdentifyProtocolV1_2.py └── reactnative_ios.js └── identify protocol 2 ├── IdentifyProtocolV2.cs ├── IdentifyProtocolV2.java ├── IdentifyProtocolV2.js ├── IdentifyProtocolV2.php └── IdentifyProtocolV2.py /README.md: -------------------------------------------------------------------------------- 1 | # How to Use ACRCloud Web API 2 | 3 | 4 | ## Overview 5 | [ACRCloud](https://www.acrcloud.com/) provides cloud [Automatic Content Recognition](https://www.acrcloud.com/docs/introduction/automatic-content-recognition/) services for [Audio Fingerprinting](https://www.acrcloud.com/docs/introduction/audio-fingerprinting/) based applications such as **[Audio Recognition](https://www.acrcloud.com/music-recognition)** (supports music, video, ads for both online and offline), **[Broadcast Monitoring](https://www.acrcloud.com/broadcast-monitoring)**, **[Second Screen](https://www.acrcloud.com/second-screen-synchronization)**, **[Copyright Protection](https://www.acrcloud.com/copyright-protection-de-duplication)** and etc.
6 | 7 | ## Audio Recognition Web API 8 | [Identify Protocol 1](https://github.com/acrcloud/webapi_example/tree/master/identify%20protocol%201%20(recommended)) and [Identify Protocol 2](https://github.com/acrcloud/webapi_example/tree/master/identify%20protocol%202) shows how to use [Identify API](https://www.acrcloud.com/docs/audio-fingerprinting-api/audio-identification-api/). 9 | 10 | ## ACRCloud Console Management API 11 | [Restful Service](https://github.com/acrcloud/webapi_example/tree/master/RESTful%20service) shows how to manage your project, bucket with [Console API](https://www.acrcloud.com/docs/audio-fingerprinting-api/console-api/). 12 | -------------------------------------------------------------------------------- /RESTful service/UploadAudios.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | 7 | using System.Diagnostics; 8 | using System.IO; 9 | 10 | using System.Web; 11 | using System.Security.Cryptography; 12 | using System.Net; 13 | 14 | namespace ACRCloudUploadFile 15 | { 16 | class ACRCloudUploadFile 17 | { 18 | public static string PostHttp(string url, IDictionary headerParams, IDictionary postParams, int timeoutSecond) 19 | { 20 | string result = ""; 21 | string BOUNDARYSTR = "acrcloud***copyright***2015***" + DateTime.Now.Ticks.ToString("x"); 22 | string BOUNDARY = "--" + BOUNDARYSTR + "\r\n"; 23 | var ENDBOUNDARY = Encoding.ASCII.GetBytes("--" + BOUNDARYSTR + "--\r\n\r\n"); 24 | 25 | var stringKeyHeader = BOUNDARY + 26 | "Content-Disposition: form-data; name=\"{0}\"" + 27 | "\r\n\r\n{1}\r\n"; 28 | var filePartHeader = BOUNDARY + 29 | "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" + 30 | "Content-Type: application/octet-stream\r\n\r\n"; 31 | 32 | var memStream = new MemoryStream(); 33 | foreach (var item in postParams) 34 | { 35 | if (item.Value is string) 36 | { 37 | string tmpStr = string.Format(stringKeyHeader, item.Key, item.Value); 38 | byte[] tmpBytes = Encoding.UTF8.GetBytes(tmpStr); 39 | memStream.Write(tmpBytes, 0, tmpBytes.Length); 40 | } 41 | else if (item.Value is byte[]) 42 | { 43 | var header = string.Format(filePartHeader, "audio_file", "audio_file"); 44 | var headerbytes = Encoding.UTF8.GetBytes(header); 45 | memStream.Write(headerbytes, 0, headerbytes.Length); 46 | byte[] sample = (byte[])item.Value; 47 | memStream.Write(sample, 0, sample.Length); 48 | memStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, 2); 49 | } 50 | } 51 | memStream.Write(ENDBOUNDARY, 0, ENDBOUNDARY.Length); 52 | 53 | HttpWebRequest request = null; 54 | HttpWebResponse response = null; 55 | Stream writer = null; 56 | StreamReader myReader = null; 57 | try 58 | { 59 | request = (HttpWebRequest)WebRequest.Create(url); 60 | request.Timeout = timeoutSecond * 1000; 61 | request.Method = "POST"; 62 | foreach (var item in headerParams) 63 | { 64 | if (item.Value is string) 65 | { 66 | request.Headers.Add(item.Key+":"+item.Value); 67 | } 68 | } 69 | request.ContentType = "multipart/form-data; boundary=" + BOUNDARYSTR; 70 | 71 | memStream.Position = 0; 72 | byte[] tempBuffer = new byte[memStream.Length]; 73 | memStream.Read(tempBuffer, 0, tempBuffer.Length); 74 | 75 | writer = request.GetRequestStream(); 76 | writer.Write(tempBuffer, 0, tempBuffer.Length); 77 | writer.Flush(); 78 | writer.Close(); 79 | writer = null; 80 | 81 | response = (HttpWebResponse)request.GetResponse(); 82 | myReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); 83 | result = myReader.ReadToEnd(); 84 | } 85 | catch (WebException e) 86 | { 87 | Console.WriteLine("timeout:\n" + e.ToString()); 88 | } 89 | catch (Exception e) 90 | { 91 | Console.WriteLine("other excption:" + e.ToString()); 92 | } 93 | finally 94 | { 95 | if (memStream != null) 96 | { 97 | memStream.Close(); 98 | memStream = null; 99 | } 100 | if (writer != null) 101 | { 102 | writer.Close(); 103 | writer = null; 104 | } 105 | if (myReader != null) 106 | { 107 | myReader.Close(); 108 | myReader = null; 109 | } 110 | if (request != null) 111 | { 112 | request.Abort(); 113 | request = null; 114 | } 115 | if (response != null) 116 | { 117 | response.Close(); 118 | response = null; 119 | } 120 | } 121 | 122 | return result; 123 | } 124 | 125 | public static string EncryptByHMACSHA1(string input, string key) 126 | { 127 | HMACSHA1 hmac = new HMACSHA1(System.Text.Encoding.UTF8.GetBytes(key)); 128 | byte[] stringBytes = Encoding.UTF8.GetBytes(input); 129 | byte[] hashedValue = hmac.ComputeHash(stringBytes); 130 | return EncodeToBase64(hashedValue); 131 | } 132 | 133 | public static string EncodeToBase64(byte[] input) 134 | { 135 | string res = Convert.ToBase64String(input, 0, input.Length); 136 | return res; 137 | } 138 | 139 | public static string Upload(IDictionary audioParams, IDictionary userParams, int timeoutSecond) 140 | { 141 | string reqUrl = "https://api.acrcloud.com/v1/audios"; 142 | string httpMethod = "POST"; 143 | string httpAction = "/v1/audios"; 144 | string signatureVersion = "1"; 145 | string accessKey = (string)audioParams["access_key"]; 146 | string accessSecret = (string)audioParams["access_secret"]; 147 | string audioId = (string)audioParams["audio_id"]; 148 | string audioTitle = (string)audioParams["audio_title"]; 149 | string bucketName = (string)audioParams["bucket_name"]; 150 | string dataType = (string)audioParams["data_type"]; 151 | byte[] audioData = (byte[])audioParams["audio_data"]; 152 | string timestamp = ((int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds).ToString(); 153 | 154 | string sigStr = httpMethod + "\n" + httpAction + "\n" + accessKey + "\n" + signatureVersion + "\n" + timestamp; 155 | string signature = EncryptByHMACSHA1(sigStr, accessSecret); 156 | 157 | Console.WriteLine(signature); 158 | 159 | var headerParams = new Dictionary(); 160 | headerParams.Add("access-key", accessKey); 161 | headerParams.Add("signature-version", signatureVersion); 162 | headerParams.Add("signature", signature); 163 | headerParams.Add("timestamp", timestamp); 164 | 165 | var postParams = new Dictionary(); 166 | postParams.Add("title", audioTitle); 167 | postParams.Add("audio_id", audioId); 168 | postParams.Add("bucket_name", bucketName); 169 | postParams.Add("data_type", dataType); 170 | postParams.Add("audio_file", audioData); 171 | 172 | if (userParams != null) { 173 | int i = 0; 174 | foreach (var item in userParams) 175 | { 176 | postParams.Add("custom_key[" + i + "]", item.Key); 177 | postParams.Add("custom_value[" + i + "]", item.Value); 178 | i++; 179 | } 180 | } 181 | 182 | string res = PostHttp(reqUrl, headerParams, postParams, timeoutSecond); 183 | 184 | return res; 185 | } 186 | 187 | static void Main(string[] args) 188 | { 189 | string audioId = "XXX"; 190 | string audioTitle = "xxx"; 191 | string dataPath = "./a.mp3"; 192 | string dataType = "audio"; // audio & fingerprint 193 | string bucketName = ""; 194 | string accessKey = ""; 195 | string accessSecret = ""; 196 | 197 | var userParams = new Dictionary(); 198 | userParams.Add("", ""); 199 | userParams.Add("", ""); 200 | 201 | var audioParams = new Dictionary(); 202 | audioParams.Add("access_key", accessKey); 203 | audioParams.Add("access_secret", accessSecret); 204 | audioParams.Add("audio_id", audioId); 205 | audioParams.Add("audio_title", audioTitle); 206 | audioParams.Add("bucket_name", bucketName); 207 | audioParams.Add("data_type", dataType); 208 | 209 | 210 | using (FileStream fs = new FileStream(dataPath, FileMode.Open)) 211 | { 212 | using (BinaryReader reader = new BinaryReader(fs)) 213 | { 214 | byte[] datas = reader.ReadBytes((int)fs.Length); 215 | audioParams.Add("audio_data", datas); 216 | 217 | // default timeout 10 seconds 218 | string result = ACRCloudUploadFile.Upload(audioParams, userParams, 10); 219 | Console.WriteLine(result); 220 | Console.ReadLine(); 221 | } 222 | } 223 | } 224 | } 225 | } 226 | -------------------------------------------------------------------------------- /RESTful service/UploadAudios.java: -------------------------------------------------------------------------------- 1 | 2 | import java.io.File; 3 | import java.io.IOException; 4 | import java.util.Calendar; 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | import javax.crypto.Mac; 9 | import javax.crypto.spec.SecretKeySpec; 10 | 11 | // import commons-codec-.jar, download from http://commons.apache.org/proper/commons-codec/download_codec.cgi 12 | import org.apache.commons.codec.binary.Base64; 13 | 14 | // import HttpClient, download from http://hc.apache.org/downloads.cgi 15 | /** 16 | * 17 | * commons-codec-1.1*.jar 18 | * commons-logging-1.*.jar 19 | * httpclient-4.*.jar 20 | * httpcore-4.*.jar 21 | * httpmime-4.*.jar 22 | * 23 | * */ 24 | import org.apache.http.HttpEntity; 25 | import org.apache.http.HttpResponse; 26 | import org.apache.http.HttpStatus; 27 | import org.apache.http.client.config.RequestConfig; 28 | import org.apache.http.client.methods.HttpPost; 29 | import org.apache.http.entity.mime.MultipartEntityBuilder; 30 | import org.apache.http.entity.mime.content.StringBody; 31 | import org.apache.http.entity.ContentType; 32 | import org.apache.http.impl.client.CloseableHttpClient; 33 | import org.apache.http.impl.client.HttpClients; 34 | import org.apache.http.util.EntityUtils; 35 | 36 | public class UploadAudios { 37 | 38 | private String encodeBase64(byte[] bstr) { 39 | Base64 base64 = new Base64(); 40 | return new String(base64.encode(bstr)); 41 | } 42 | 43 | private String encryptByHMACSHA1(byte[] data, byte[] key) { 44 | try { 45 | SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA1"); 46 | Mac mac = Mac.getInstance("HmacSHA1"); 47 | mac.init(signingKey); 48 | byte[] rawHmac = mac.doFinal(data); 49 | return encodeBase64(rawHmac); 50 | } catch (Exception e) { 51 | e.printStackTrace(); 52 | } 53 | return ""; 54 | } 55 | 56 | private String getUTCTimeSeconds() { 57 | Calendar cal = Calendar.getInstance(); 58 | int zoneOffset = cal.get(Calendar.ZONE_OFFSET); 59 | int dstOffset = cal.get(Calendar.DST_OFFSET); 60 | cal.add(Calendar.MILLISECOND, -(zoneOffset + dstOffset)); 61 | return cal.getTimeInMillis() / 1000 + ""; 62 | } 63 | 64 | private String postHttp(String url, Map postParams, 65 | Map headerParams, int timeout) { 66 | String result = null; 67 | 68 | if (postParams == null) { 69 | return result; 70 | } 71 | 72 | CloseableHttpClient httpClient = HttpClients.createDefault(); 73 | try { 74 | HttpPost httpPost = new HttpPost(url); 75 | 76 | if (headerParams != null) { 77 | for (String key : headerParams.keySet()) { 78 | String value = headerParams.get(key); 79 | httpPost.addHeader(key, value); 80 | } 81 | } 82 | 83 | MultipartEntityBuilder mEntityBuilder = MultipartEntityBuilder 84 | .create(); 85 | for (String key : postParams.keySet()) { 86 | Object value = postParams.get(key); 87 | if (value instanceof String || value instanceof Integer) { 88 | ContentType contentType = ContentType.create("text/plain", "UTF-8"); 89 | StringBody stringBody = new StringBody(value+"", contentType); 90 | mEntityBuilder.addPart(key, stringBody); 91 | } else if (value instanceof File) { 92 | mEntityBuilder.addBinaryBody(key, (File) value); 93 | } 94 | } 95 | 96 | httpPost.setEntity(mEntityBuilder.build()); 97 | 98 | RequestConfig requestConfig = RequestConfig.custom() 99 | .setConnectionRequestTimeout(timeout) 100 | .setConnectTimeout(timeout).setSocketTimeout(timeout) 101 | .build(); 102 | httpPost.setConfig(requestConfig); 103 | 104 | HttpResponse response = httpClient.execute(httpPost); 105 | 106 | System.out.println(response.getStatusLine().getStatusCode()); 107 | 108 | HttpEntity entity = response.getEntity(); 109 | result = EntityUtils.toString(entity); 110 | } catch (Exception e) { 111 | e.printStackTrace(); 112 | } finally { 113 | try { 114 | httpClient.close(); 115 | } catch (IOException e) { 116 | } 117 | } 118 | return result; 119 | } 120 | 121 | public String upload(String audioId, String audioTitle, String dataPath, 122 | String dataType, String bucketName, String accessKey, 123 | String accessSecret, Map userParams) { 124 | String result = null; 125 | String reqUrl = "https://api.acrcloud.com/v1/audios"; 126 | String htttMethod = "POST"; 127 | String httpAction = "/v1/audios"; 128 | String signatureVersion = "1"; 129 | String timestamp = this.getUTCTimeSeconds(); 130 | 131 | File file = new File(dataPath); 132 | if (!file.exists()) { 133 | return null; 134 | } 135 | 136 | String sigStr = htttMethod + "\n" + httpAction + "\n" + accessKey 137 | + "\n" + signatureVersion + "\n" + timestamp; 138 | String signature = encryptByHMACSHA1(sigStr.getBytes(), 139 | accessSecret.getBytes()); 140 | 141 | Map headerParams = new HashMap(); 142 | headerParams.put("access-key", accessKey); 143 | headerParams.put("signature-version", signatureVersion); 144 | headerParams.put("signature", signature); 145 | headerParams.put("timestamp", timestamp); 146 | 147 | Map postParams = new HashMap(); 148 | postParams.put("title", audioTitle); 149 | postParams.put("audio_id", audioId); 150 | postParams.put("bucket_name", bucketName); 151 | postParams.put("data_type", dataType); 152 | postParams.put("audio_file", file); 153 | 154 | if (userParams != null) { 155 | int i = 0; 156 | for (String key : userParams.keySet()) { 157 | String value = userParams.get(key); 158 | postParams.put("custom_key[" + i + "]", key); 159 | postParams.put("custom_value[" + i + "]", value); 160 | i++; 161 | } 162 | } 163 | 164 | result = this.postHttp(reqUrl, postParams, headerParams, 8000); 165 | 166 | return result; 167 | } 168 | 169 | /** 170 | * @param args 171 | */ 172 | public static void main(String[] args) { 173 | String audioId = "XXX"; 174 | String audioTitle = "xxx"; 175 | String dataPath = "./a.mp3"; 176 | String dataType = "audio"; // audio & fingerprint 177 | String bucketName = ""; 178 | String accessKey = ""; 179 | String accessSecret = ""; 180 | 181 | Map userParams = new HashMap(); 182 | userParams.put("", ""); 183 | userParams.put("", ""); 184 | 185 | UploadAudios ua = new UploadAudios(); 186 | 187 | String result = ua.upload(audioId, audioTitle, dataPath, dataType, 188 | bucketName, accessKey, accessSecret, userParams); 189 | if (result == null) { 190 | System.out.println("upload error"); 191 | } 192 | 193 | System.out.println(result); 194 | } 195 | 196 | } 197 | -------------------------------------------------------------------------------- /RESTful service/audio.js: -------------------------------------------------------------------------------- 1 | var url = require('url'); 2 | var path = require('path'); 3 | var fs = require('fs'); 4 | var crypto = require('crypto'); 5 | //npm install request 6 | var request = require('request'); 7 | 8 | var defaultOptions = { 9 | host: 'api.acrcloud.com', 10 | endpoint: '/v1/audios', 11 | signature_version: '1', 12 | secure: true, 13 | access_key: 'xxx', 14 | access_secret: 'xxxxx' 15 | }; 16 | 17 | function buildStringToSign(method, uri, accessKey, signatureVersion, timestamp) { 18 | return [method, uri, accessKey, signatureVersion, timestamp].join('\n'); 19 | } 20 | 21 | function sign(signString, accessSecret) { 22 | return crypto.createHmac('sha1', accessSecret) 23 | .update(Buffer.from(signString, 'utf-8')) 24 | .digest().toString('base64'); 25 | } 26 | 27 | /** 28 | * Identifies a sample of bytes 29 | */ 30 | function upload(file_path, bucket, title, audio_id, data_type="fingerprint", custom_fields=None, cb) { 31 | var current_data = new Date(); 32 | var timestamp = current_data.getTime()/1000; 33 | 34 | var stringToSign = buildStringToSign('POST', 35 | defaultOptions.endpoint, 36 | defaultOptions.access_key, 37 | defaultOptions.signature_version, 38 | timestamp); 39 | console.log(stringToSign) 40 | 41 | var signature = sign(stringToSign, defaultOptions.access_secret); 42 | console.log(signature) 43 | 44 | var headers = { 45 | 'access-key': defaultOptions.access_key, 46 | 'signature-version': defaultOptions.signature_version, 47 | 'signature': signature, 48 | 'timestamp':timestamp 49 | }; 50 | var formData = { 51 | 'audio_file': { 52 | 'value': fs.createReadStream(file_path), 53 | 'options': { 54 | 'filename': path.basename(file_path), 55 | 'contentType': 'fingerprint/lo' 56 | } 57 | }, 58 | 'data_type':data_type, 59 | 'bucket_name':bucket, 60 | 'title':title, 61 | 'audio_id':audio_id, 62 | } 63 | if (custom_fields) { 64 | keys = [] 65 | values = [] 66 | for (var k in custom_fields) { 67 | keys.push(k) 68 | values.push(custom_fields[k]) 69 | } 70 | formData['custom_key[]'] = keys 71 | formData['custom_value[]'] = values 72 | } 73 | 74 | request.post({ 75 | url: "https://"+defaultOptions.host + defaultOptions.endpoint, 76 | method: 'POST', 77 | headers: headers, 78 | formData: formData 79 | }, cb); 80 | } 81 | 82 | function get_audio(acr_id, cb) { 83 | var current_data = new Date(); 84 | var timestamp = current_data.getTime()/1000; 85 | 86 | var endpoint = defaultOptions.endpoint+"/"+acr_id 87 | 88 | var stringToSign = buildStringToSign('GET', 89 | endpoint, 90 | defaultOptions.access_key, 91 | defaultOptions.signature_version, 92 | timestamp); 93 | 94 | var signature = sign(stringToSign, defaultOptions.access_secret); 95 | 96 | var headers = { 97 | 'access-key': defaultOptions.access_key, 98 | 'signature-version': defaultOptions.signature_version, 99 | 'signature': signature, 100 | 'timestamp':timestamp 101 | }; 102 | 103 | request.get({ 104 | url: "https://"+defaultOptions.host + endpoint, 105 | method: 'GET', 106 | headers: headers, 107 | }, cb); 108 | } 109 | 110 | var title = "test" 111 | var audio_id = "test" 112 | var bucket_name = "eu-test" 113 | var data_type = "fingerprint" 114 | var file_path = '1040210008.mp3.wav.lo'; 115 | var custom_fields = {"key1":"value1"} 116 | 117 | upload(file_path, bucket_name, title, audio_id, data_type, custom_fields , function (err, httpResponse, body) { 118 | if (err) console.log(err); 119 | console.log(body); 120 | }); 121 | 122 | get_audio("4b616d1b695bf4c35ed5103f9cbdd507", function(err, httpResponse, body){ 123 | console.log(body); 124 | }); 125 | -------------------------------------------------------------------------------- /RESTful service/audio.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding:utf-8 -*- 3 | import sys 4 | import os 5 | import base64 6 | import hmac 7 | import hashlib 8 | import urllib 9 | import time 10 | import requests 11 | 12 | ''' 13 | This demo shows how to use the RESTful API to upload an audio file ( "data_type":"audio" ) into your bucket. 14 | You can find account_access_key and account_access_secret in your account page. 15 | Log into http://console.acrcloud.com -> "Your Name"(top right corner) -> "Account" -> "Console API Keys" -> "Create Key Pair". 16 | Be Careful, they are different with access_key and access_secret of your project. 17 | ''' 18 | option = { 19 | 'host': 'api.acrcloud.com', 20 | 'signature_version': '1', 21 | 'access_key': '', 22 | 'access_secret': '', 23 | }; 24 | 25 | 26 | def sign(string_to_sign, access_secret): 27 | return base64.b64encode( 28 | hmac.new(access_secret.encode(), string_to_sign.encode(), digestmod=hashlib.sha1) 29 | .digest()) 30 | 31 | def upload_audio(path, bucket, title, audio_id, data_type="audio", custom_fields=None): 32 | http_method = "POST" 33 | timestamp = str(time.time()) 34 | http_uri = "/v1/audios" 35 | 36 | string_to_sign = '\n'.join((http_method, http_uri, option['access_key'], option['signature_version'], str(timestamp))) 37 | 38 | signature = sign(string_to_sign, option['access_secret']) 39 | 40 | f = open(path, "rb") 41 | 42 | files = {'audio_file':("audio_file", f)} 43 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 44 | #if you uplaod fingerprint file , please set "data_type":"fingerprint" 45 | data = {'title':title, "audio_id":audio_id, "bucket_name":bucket, "data_type":data_type} 46 | if custom_fields: 47 | keys = [] 48 | values = [] 49 | for k in custom_fields: 50 | keys.append(k) 51 | values.append(custom_fields[k]) 52 | data['custom_key[]'] = keys 53 | data['custom_value[]'] = values 54 | 55 | requrl = "https://"+option['host'] + http_uri 56 | r = requests.post(requrl, files=files, data=data, headers=headers, verify=True) 57 | r.encoding = "utf-8" 58 | print r.text 59 | 60 | def get_audios(bucket, page=1,search=''): 61 | http_method = "GET" 62 | timestamp = str(time.time()) 63 | http_uri = "/v1/audios" 64 | 65 | string_to_sign = '\n'.join((http_method, http_uri, option['access_key'], option['signature_version'], str(timestamp))) 66 | signature = sign(string_to_sign, option['access_secret']) 67 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 68 | 69 | requrl = "https://"+option['host'] + http_uri+"?bucket_name="+bucket+"&page="+str(page) 70 | if search: 71 | requrl = requrl+'&search='+search 72 | r = requests.get(requrl, headers=headers, verify=True) 73 | r.encoding = "utf-8" 74 | print r.text 75 | 76 | def get_audio(acr_id): 77 | http_method = "GET" 78 | timestamp = time.time() 79 | http_uri = "/v1/audios/"+acr_id 80 | 81 | string_to_sign = '\n'.join((http_method, http_uri, option['access_key'], option['signature_version'], str(timestamp))) 82 | signature = sign(string_to_sign, option['access_secret']) 83 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 84 | 85 | requrl = "https://"+option['host'] + http_uri 86 | r = requests.get(requrl, headers=headers, verify=True) 87 | r.encoding = "utf-8" 88 | print r.text 89 | 90 | def update_audio_with_file(path, bucket, acr_id, title, audio_id, custom_fields=None): 91 | http_method = "POST" 92 | timestamp = time.time() 93 | http_uri = "/v1/audios/"+acr_id 94 | 95 | string_to_sign = '\n'.join((http_method, http_uri, option['access_key'], option['signature_version'], str(timestamp))) 96 | signature = sign(string_to_sign, option['access_secret']) 97 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 98 | 99 | data = {'title':title, "audio_id":audio_id, "bucket_name":bucket, "data_type":"fingerprint"} 100 | if custom_fields: 101 | keys = [] 102 | values = [] 103 | for k in custom_fields: 104 | keys.append(k) 105 | values.append(custom_fields[k]) 106 | data['custom_key[]'] = keys 107 | data['custom_value[]'] = values 108 | 109 | requrl = "https://"+option['host'] + http_uri 110 | 111 | f = open(path, "r") 112 | files = {'audio_file':f} 113 | r = requests.post(requrl, files=files, data=data, headers=headers, verify=True) 114 | r.encoding = "utf-8" 115 | print r.text 116 | 117 | def update_audio(bucket, acr_id, title, audio_id, custom_fields=None): 118 | http_method = "PUT" 119 | timestamp = str(time.time()) 120 | http_uri = "/v1/audios/"+acr_id 121 | 122 | string_to_sign = '\n'.join((http_method, http_uri, option['access_key'], option['signature_version'], str(timestamp))) 123 | signature = sign(string_to_sign, option['access_secret']) 124 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 125 | 126 | data = {'title':title, "audio_id":audio_id, "bucket_name":bucket} 127 | if custom_fields: 128 | keys = [] 129 | values = [] 130 | for k in custom_fields: 131 | keys.append(k) 132 | values.append(custom_fields[k]) 133 | data['custom_key[]'] = keys 134 | data['custom_value[]'] = values 135 | 136 | requrl = "https://"+option['host'] + http_uri 137 | r = requests.put(requrl, data=data, headers=headers, verify=True) 138 | r.encoding = "utf-8" 139 | print r.text 140 | 141 | def delete_audio(acr_id): 142 | http_method = "DELETE" 143 | timestamp = str(time.time()) 144 | http_uri = "/v1/audios/"+acr_id 145 | 146 | string_to_sign = '\n'.join((http_method, http_uri, option['access_key'], option['signature_version'], str(timestamp))) 147 | signature = sign(string_to_sign, option['access_secret']) 148 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 149 | 150 | requrl = "https://"+option['host'] + http_uri 151 | r = requests.delete(requrl, headers=headers, verify=True) 152 | r.encoding = "utf-8" 153 | if r.status_code == 204: 154 | print "deleted" 155 | 156 | def move_audio(acr_id, new_bucket_name): 157 | http_method = "PUT" 158 | timestamp = str(time.time()) 159 | http_uri = "/v1/audios/"+acr_id 160 | 161 | string_to_sign = '\n'.join((http_method, http_uri, option['access_key'], option['signature_version'], str(timestamp))) 162 | signature = sign(string_to_sign, option['access_secret']) 163 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 164 | 165 | data = {'action':'move', 'new_bucket':new_bucket_name} 166 | requrl = "https://"+option['host'] + http_uri 167 | 168 | r = requests.put(requrl, data=data, headers=headers, verify=True) 169 | r.encoding = "utf-8" 170 | print r.text 171 | 172 | if __name__ == "__main__": 173 | #update_audio('eu-test', 'db397154fb9858f17373b5bf66be875a', 'Hiding my heart - Adele', '12345', {"artist":"Adele", "title":"Hiding my heart"}) 174 | #delete_audio("07221fadacc359fdb0744cd28b7b0ce9") 175 | #get_audios('eu-test', 1) 176 | upload_audio(sys.argv[1], 'eu-test', 'test-title', '1212', 'fingerprint') 177 | #move_audio('db397154fb9858f17373b5bf66be875a', 'new_bucket_name') 178 | -------------------------------------------------------------------------------- /RESTful service/audio_erl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env escript 2 | %% -*- erlang -*- 3 | 4 | 5 | %% @doc 6 | %%this escript demo shows how to use erlang to work with acrcloud api 7 | %%it is loosely based on the audio.py python examples 8 | %%ideally the various functions can be put in an erlang library which can be exposed through an api 9 | %%it depends on the inets application and the ssl application so those have to be started first. 10 | %% 11 | %% @end 12 | %%%------------------------------------------------------------------- 13 | 14 | 15 | 16 | %% Main entry point. 17 | %%please fill in all required values in xxx with real values 18 | %%to run make sure erlang is installed with support for openssl and run ./audio_erl 19 | main(_) -> 20 | ok = start_apps(), 21 | Acr_Host = "api.acrcloud.com", 22 | Acr_Secret_key = "xxx", 23 | Acr_key = "xxx", 24 | Api_version = "1", 25 | Path_file = "xxx",%%file should be placed in current folder for testing 26 | Bucket_name = "xxx", 27 | Audio_title = "xxx", 28 | Audio_id = "xxx", 29 | Data_type = "xxx",%%audio or fingerprint 30 | Custom_fields = [{fname,"fname"},{lname,"lname"}],%%first value of tuple should be atom,second value should be string 31 | upload_audio(Acr_Host,Acr_Secret_key,Acr_key,Api_version,Path_file,Bucket_name,Audio_title,Audio_id,Data_type,Custom_fields). 32 | 33 | 34 | 35 | 36 | %%for starting apps needed for application to work 37 | start_apps()-> 38 | {ok,_} = application:ensure_all_started(inets), 39 | {ok,_} = application:ensure_all_started(ssl), 40 | httpc:set_options([{proxy, {{"localhost", 8084},["abc.com"]}}]), 41 | ok. 42 | 43 | 44 | %% for signing 45 | sign(String_to_sign,Access_secret)-> 46 | String_binary = erlang:list_to_binary(String_to_sign), 47 | Access_binary = erlang:list_to_binary(Access_secret), 48 | Res = crypto:hmac(sha,Access_binary,String_binary), 49 | base64:encode_to_string(Res). 50 | 51 | 52 | %%for creating a signature 53 | create_signature(Http_method,Http_uri,Access_key,Access_secret,Sig_version,Timestamp)-> 54 | String_to_sign = [Http_method,Http_uri,Access_key,Sig_version,Timestamp], 55 | String_to_sign_join = string:join(String_to_sign,"\n"), 56 | sign(String_to_sign_join, Access_secret). 57 | 58 | 59 | %%%for uploading audio 60 | upload_audio(URl_host,Access_secret,Access_key,Sig_version,Path_file,Bucket_name,Title,Audio_id,Data_type,Custom_fields)-> 61 | Http_method = "POST", 62 | Http_uri = "/v1/audios", 63 | Timestamp = erlang:integer_to_list(calendar:datetime_to_gregorian_seconds(calendar:universal_time())-62167219200), 64 | Signature = create_signature(Http_method,Http_uri,Access_key,Access_secret,Sig_version,Timestamp), 65 | {ok, Audio_binary} = file:read_file(Path_file), 66 | Requrl = lists:append(["https://",URl_host,Http_uri]), 67 | Boundary = "AaB03xXcvfbghy65", 68 | Data = [{audio_id,Audio_id}, {title, Title},{bucket_name,Bucket_name},{data_type,Data_type}], 69 | [Key_accum_final,Value_accum_final] = create_custom_fields(Custom_fields), 70 | Data_send = lists:append([Data,Key_accum_final,Value_accum_final]), 71 | Body = format_multipart_formdata(Boundary,Data_send,[{audio_file, "audio_file", Audio_binary}]), 72 | ContentType = lists:concat(["multipart/form-data; boundary=", Boundary]), 73 | Headers=[ 74 | {"Content-length", integer_to_list(size(Body))},{"access-key",Access_key}, 75 | {"signature-version",Sig_version},{"signature",Signature},{"timestamp",Timestamp},{"Accept","*/*"} 76 | ], 77 | 78 | Result = httpc:request(post, {Requrl, Headers,ContentType, Body}, [], [{sync,true}]), 79 | result_to_terms(Result). 80 | 81 | 82 | %%for creating custom fields 83 | create_custom_fields(Custom_fields)-> 84 | [Key_accum_final,Value_accum_final] = 85 | lists:foldl( 86 | fun({Key,Value},[Key_accum,Value_acccum])-> 87 | New_Key_Accum = [{'custom_key[]',atom_to_list(Key)}|Key_accum], 88 | New_Value_Accum = [{'custom_value[]',Value}|Value_acccum], 89 | [New_Key_Accum,New_Value_Accum] 90 | end, 91 | [[],[]],Custom_fields). 92 | 93 | 94 | %%for formatting form-data 95 | format_multipart_formdata(Boundary, Fields, Files) -> 96 | FieldParts = 97 | lists:map( 98 | fun({FieldName, FieldContent}) -> 99 | [lists:concat(["--", Boundary]), 100 | lists:concat(["Content-Disposition: form-data; name=\"",atom_to_list(FieldName),"\""]), 101 | "", 102 | FieldContent] 103 | end, Fields), 104 | FieldParts2 = lists:append(FieldParts), 105 | FileParts = 106 | lists:map( 107 | fun({FieldName, FileName, FileContent}) -> 108 | [lists:concat(["--", Boundary]), 109 | lists:concat(["Content-Disposition: form-data; name=\"",atom_to_list(FieldName),"\"; filename=\"",FileName,"\""]), 110 | "", 111 | FileContent] 112 | end, Files), 113 | FileParts2 = lists:append(FileParts), 114 | EndingParts = [lists:concat(["--", Boundary,"--"])], 115 | Parts = lists:append([FieldParts2,FileParts2,EndingParts]), 116 | Fold_part = lists:foldr(fun(X,Accum)-> [X,"\r\n"|Accum] end,[],Parts), 117 | erlang:list_to_binary(Fold_part). 118 | 119 | 120 | %%for parsing request response and getting response code 121 | result_to_terms(Result) -> 122 | {ok, {{_Version,Response_code, _ReasonPhrase},Headers, ResultBody}} = Result, 123 | io:format("~nresponse code is ~p~nHeaders are ~p~nBod is ~p",[Response_code,Headers,ResultBody]), 124 | {Response_code,Headers}. 125 | -------------------------------------------------------------------------------- /RESTful service/audios.rb: -------------------------------------------------------------------------------- 1 | require 'openssl' 2 | require 'base64' 3 | require 'net/http/post/multipart' 4 | 5 | # Replace "###...###" below with your account access_key and access_secret. 6 | requrl = "https://api.acrcloud.com/v1/audios" 7 | access_key = "###YOUR_ACCESS_KEY###" 8 | access_secret = "###YOUR_ACCESS_SECRET###" 9 | 10 | http_method = "POST" 11 | http_uri = "/v1/audios" 12 | data_type = "audio" 13 | signature_version = "1" 14 | timestamp = Time.now.utc().to_i.to_s 15 | 16 | string_to_sign = http_method+"\n"+http_uri+"\n"+access_key+"\n"+signature_version+"\n"+timestamp 17 | 18 | digest = OpenSSL::Digest.new('sha1') 19 | signature = Base64.encode64(OpenSSL::HMAC.digest(digest, access_secret, string_to_sign)) 20 | 21 | file_name = ARGV[0] 22 | sample_bytes = File.size(file_name) 23 | title = "TEST" 24 | audio_id = "123" 25 | bucket = "Your bucket name" 26 | 27 | header = {:signature => signature, "access-key" => access_key, :timestamp => timestamp, "signature-version" => "1"} 28 | 29 | url = URI.parse(requrl) 30 | puts(url.path) 31 | File.open(file_name) do |file| 32 | req = Net::HTTP::Post::Multipart.new url.path, 33 | "audio_file" => UploadIO.new(file, "audio/mp3", file_name), 34 | "title" =>title, 35 | "audio_id"=>audio_id, 36 | "bucket_name"=>bucket, 37 | "data_type"=> "audio" 38 | req.add_field(:signature, signature.strip) 39 | req.add_field("access-key", access_key) 40 | req.add_field(:timestamp, timestamp) 41 | req.add_field("signature-version", "1") 42 | 43 | res = Net::HTTP.start(url.host, url.port, use_ssl: true) do |http| 44 | http.request(req) 45 | end 46 | puts(res.body) 47 | end 48 | -------------------------------------------------------------------------------- /RESTful service/bucket.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import base64 4 | import hmac 5 | import hashlib 6 | import time 7 | import requests 8 | 9 | option = { 10 | 'host': 'api.acrcloud.com', 11 | 'signature_version': '1', 12 | 'access_key': '', 13 | 'access_secret': '' 14 | }; 15 | 16 | 17 | def sign(string_to_sign, access_secret): 18 | return base64.b64encode( 19 | hmac.new(access_secret.encode(), string_to_sign.encode(), digestmod=hashlib.sha1) 20 | .digest()) 21 | 22 | def create_bucket(name, type, scale, content_type): 23 | http_method = "POST" 24 | timestamp = str(time.time()) 25 | uri = '/v1/buckets' 26 | 27 | string_to_sign = '\n'.join((http_method, uri, option['access_key'], option['signature_version'], timestamp)) 28 | 29 | signature = sign(string_to_sign, option['access_secret']) 30 | 31 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 32 | 33 | data = {'name':name, 'type':type, 'scale':scale,'content_type':content_type} 34 | 35 | requrl = "https://"+option['host'] + uri 36 | r = requests.post(requrl, data=data, headers=headers, verify=True) 37 | r.encoding = "utf-8" 38 | print r.text 39 | 40 | def delete_bucket(name): 41 | http_method = "DELETE" 42 | timestamp = str(time.time()) 43 | uri = '/v1/buckets'+"/"+name 44 | 45 | string_to_sign = '\n'.join((http_method, uri, option['access_key'], option['signature_version'], timestamp)) 46 | 47 | signature = sign(string_to_sign, option['access_secret']) 48 | 49 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 50 | 51 | data = {'name':name} 52 | 53 | requrl = "https://"+option['host'] + uri 54 | r = requests.delete(requrl, data=data, headers=headers, verify=True) 55 | r.encoding = "utf-8" 56 | print r.text 57 | def list_buckets(per_page=50): 58 | http_method = "GET" 59 | timestamp = str(time.time()) 60 | uri = '/v1/buckets' 61 | 62 | string_to_sign = '\n'.join((http_method, uri, option['access_key'], option['signature_version'], timestamp)) 63 | 64 | signature = sign(string_to_sign, option['access_secret']) 65 | 66 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 67 | 68 | requrl = "https://"+option['host'] + uri+"?per_page="+str(per_page) 69 | r = requests.get(requrl, headers=headers, verify=True) 70 | r.encoding = "utf-8" 71 | print r.text 72 | 73 | def get_bucket(id): 74 | http_method = "GET" 75 | timestamp = time.time() 76 | uri = '/v1/buckets/'+str(id) 77 | 78 | string_to_sign = '\n'.join((http_method, uri, option['access_key'], option['signature_version'], str(timestamp))) 79 | 80 | signature = sign(string_to_sign, option['access_secret']) 81 | 82 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':str(timestamp)} 83 | 84 | requrl = "https://"+option['host'] + uri 85 | r = requests.get(requrl, headers=headers, verify=True) 86 | r.encoding = "utf-8" 87 | print r.text 88 | 89 | if __name__ == "__main__": 90 | create_bucket('test_api_bucket', 'File', 100, "Music") 91 | #list_buckets(50) 92 | #delete_bucket('test_api_bucket') 93 | #get_bucket(123) 94 | -------------------------------------------------------------------------------- /RESTful service/channel.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import base64 4 | import hmac 5 | import hashlib 6 | import urllib 7 | import time 8 | import requests 9 | 10 | ''' 11 | This demo shows how to use the RESTful API to upload an audio file ( "data_type":"audio" ) into your bucket. 12 | You can find account_access_key and account_access_secret in your account page. 13 | Log into http://console.acrcloud.com -> "Your Name"(top right corner) -> "Account" -> "Console API Keys" -> "Create Key Pair". 14 | Be Careful, they are different with access_key and access_secret of your project. 15 | ''' 16 | option = { 17 | 'host': 'api.acrcloud.com', 18 | 'signature_version': '1', 19 | 'access_key': 'your console access key', 20 | 'access_secret': 'your console access scret', 21 | }; 22 | 23 | 24 | def sign(string_to_sign, access_secret): 25 | return base64.b64encode( 26 | hmac.new(access_secret.encode(), string_to_sign.encode(), digestmod=hashlib.sha1) 27 | .digest()) 28 | 29 | def create_channel(bucket, channel_url, title, channel_id, custom_fields=None): 30 | http_method = "POST" 31 | timestamp = str(time.time()) 32 | http_uri = "/v1/channels" 33 | 34 | string_to_sign = '\n'.join((http_method, http_uri, option['access_key'], option['signature_version'], timestamp)) 35 | 36 | signature = sign(string_to_sign, option['access_secret']) 37 | 38 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 39 | data = {'url':channel_url,'title':title, "channel_id":channel_id, "bucket_name":bucket} 40 | if custom_fields: 41 | keys = [] 42 | values = [] 43 | for k in custom_fields: 44 | keys.append(k) 45 | values.append(custom_fields[k]) 46 | data['custom_key[]'] = keys 47 | data['custom_value[]'] = values 48 | 49 | requrl = "https://"+option['host'] + http_uri 50 | r = requests.post(requrl, data=data, headers=headers, verify=True) 51 | r.encoding = "utf-8" 52 | print r.text 53 | 54 | def get_all_channels(bucket, page=1): 55 | http_method = "GET" 56 | timestamp = str(time.time()) 57 | http_uri = "/v1/buckets/"+bucket+"/channels" 58 | 59 | string_to_sign = '\n'.join((http_method, http_uri, option['access_key'], option['signature_version'], timestamp)) 60 | signature = sign(string_to_sign, option['access_secret']) 61 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 62 | 63 | requrl = "https://"+option['host'] + http_uri+"?page="+str(page) 64 | r = requests.get(requrl, headers=headers, verify=True) 65 | r.encoding = "utf-8" 66 | print r.text 67 | 68 | def get_channel(acr_id): 69 | http_method = "GET" 70 | timestamp = str(time.time()) 71 | http_uri = "/v1/channels/"+acr_id 72 | 73 | string_to_sign = '\n'.join((http_method, http_uri, option['access_key'], option['signature_version'], timestamp)) 74 | signature = sign(string_to_sign, option['access_secret']) 75 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 76 | 77 | requrl = "https://"+option['host'] + http_uri 78 | r = requests.get(requrl, headers=headers, verify=True) 79 | r.encoding = "utf-8" 80 | print r.text 81 | 82 | def delete_channel(acr_id): 83 | http_method = "DELETE" 84 | timestamp = str(time.time()) 85 | http_uri = "/v1/channels/"+acr_id 86 | 87 | string_to_sign = '\n'.join((http_method, http_uri, option['access_key'], option['signature_version'], timestamp)) 88 | signature = sign(string_to_sign, option['access_secret']) 89 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 90 | 91 | requrl = "https://"+option['host'] + http_uri 92 | r = requests.delete(requrl, headers=headers, verify=True) 93 | r.encoding = "utf-8" 94 | if r.status_code == 204: 95 | print "deleted" 96 | 97 | def update_channel(acr_id, channel_url, title, channel_id, custom_fields=None): 98 | http_method = "PUT" 99 | timestamp = str(time.time()) 100 | http_uri = "/v1/channels/"+acr_id 101 | 102 | string_to_sign = '\n'.join((http_method, http_uri, option['access_key'], option['signature_version'], timestamp)) 103 | 104 | signature = sign(string_to_sign, option['access_secret']) 105 | 106 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 107 | data = {'url':channel_url,'title':title, "channel_id":channel_id} 108 | if custom_fields: 109 | keys = [] 110 | values = [] 111 | for k in custom_fields: 112 | keys.append(k) 113 | values.append(custom_fields[k]) 114 | data['custom_key[]'] = keys 115 | data['custom_value[]'] = values 116 | 117 | requrl = "https://"+option['host'] + http_uri 118 | r = requests.put(requrl, data=data, headers=headers, verify=True) 119 | r.encoding = "utf-8" 120 | print r.text 121 | 122 | if __name__ == "__main__": 123 | #create_channel('eu_test', 'http://127.0.0.1', 'channel 1', '12345') 124 | update_channel("722ad0163be810eb972c1f619aa1f1b3", 'http://127.0.0.1', 'channel 1', '12345', {"aaa":"223", "bbb":"222"}) 125 | delete_channel("722ad0163be810eb972c1f619aa1f1b3") 126 | #get_all_channels('eu_test', 1) 127 | #get_channel('b6c9985babb2e9ecb1642d04a7b149d8') 128 | -------------------------------------------------------------------------------- /RESTful service/channel_playback.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import base64 4 | import hmac 5 | import hashlib 6 | import urllib 7 | import time 8 | import requests 9 | 10 | ''' 11 | This demo shows how to use the RESTful API to upload an audio file ( "data_type":"audio" ) into your bucket. 12 | You can find account_access_key and account_access_secret in your account page. 13 | Log into http://console.acrcloud.com -> "Your Name"(top right corner) -> "Account" -> "Console API Keys" -> "Create Key Pair". 14 | Be Careful, they are different with access_key and access_secret of your project. 15 | ''' 16 | option = { 17 | 'host': 'api.acrcloud.com', 18 | 'signature_version': '1', 19 | 'access_key': 'your_account_access_key(not project key)', 20 | 'access_secret': 'your_account_access_secret' 21 | }; 22 | 23 | 24 | def sign(string_to_sign, access_secret): 25 | return base64.b64encode( 26 | hmac.new(access_secret.encode(), string_to_sign.encode(), digestmod=hashlib.sha1) 27 | .digest()) 28 | 29 | def create_channel_playback(bucket_id, channel_id, time_length): 30 | http_method = "POST" 31 | timestamp = str(time.time()) 32 | http_uri = "/v1/channel-playback" 33 | 34 | string_to_sign = '\n'.join((http_method, http_uri, option['access_key'], option['signature_version'], str(timestamp))) 35 | 36 | signature = sign(string_to_sign, option['access_secret']) 37 | 38 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 39 | data = {"bucket_id":bucket_id, "channel_id":channel_id, "time":int(time_length)} 40 | 41 | requrl = "https://"+option['host'] + http_uri 42 | r = requests.post(requrl, data=data, headers=headers, verify=True) 43 | r.encoding = "utf-8" 44 | print r.text 45 | 46 | def update_channel_playback(id, bucket_id, channel_id, time_length): 47 | http_method = "PUT" 48 | timestamp = str(time.time()) 49 | http_uri = "/v1/channel-playback/"+str(id) 50 | 51 | string_to_sign = '\n'.join((http_method, http_uri, option['access_key'], option['signature_version'], str(timestamp))) 52 | 53 | signature = sign(string_to_sign, option['access_secret']) 54 | 55 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 56 | data = {"bucket_id":bucket_id, "channel_id":channel_id, "time":int(time_length)} 57 | 58 | requrl = "https://"+option['host'] + http_uri 59 | r = requests.put(requrl, data=data, headers=headers, verify=True) 60 | r.encoding = "utf-8" 61 | print r.text 62 | 63 | def get_all_channel_playback(bucket_id, page=1): 64 | http_method = "GET" 65 | timestamp = str(time.time()) 66 | http_uri = "/v1/buckets/"+str(bucket_id)+"/channel-playback" 67 | 68 | string_to_sign = '\n'.join((http_method, http_uri, option['access_key'], option['signature_version'], str(timestamp))) 69 | signature = sign(string_to_sign, option['access_secret']) 70 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 71 | 72 | requrl = "https://"+option['host'] + http_uri+"?page="+str(page) 73 | r = requests.get(requrl, headers=headers, verify=True) 74 | r.encoding = "utf-8" 75 | print r.text 76 | 77 | def get_channel_playback(id): 78 | http_method = "GET" 79 | timestamp = str(time.time()) 80 | http_uri = "/v1/channel-playback/"+str(id) 81 | 82 | string_to_sign = '\n'.join((http_method, http_uri, option['access_key'], option['signature_version'], str(timestamp))) 83 | signature = sign(string_to_sign, option['access_secret']) 84 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 85 | 86 | requrl = "https://"+option['host'] + http_uri 87 | r = requests.get(requrl, headers=headers, verify=True) 88 | r.encoding = "utf-8" 89 | print r.text 90 | 91 | def delete_channel_playback(id): 92 | http_method = "DELETE" 93 | timestamp = str(time.time()) 94 | http_uri = "/v1/channel-playback/"+str(id) 95 | 96 | string_to_sign = '\n'.join((http_method, http_uri, option['access_key'], option['signature_version'], str(timestamp))) 97 | signature = sign(string_to_sign, option['access_secret']) 98 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 99 | 100 | requrl = "https://"+option['host'] + http_uri 101 | r = requests.delete(requrl, headers=headers, verify=True) 102 | r.encoding = "utf-8" 103 | if r.status_code == 204: 104 | print "deleted" 105 | 106 | def upload_audio(path, channel_id, data_type): 107 | http_method = "POST" 108 | timestamp = time.time() 109 | http_uri = "/v1/channels/"+str(channel_id)+"/playback-audios" 110 | 111 | string_to_sign = '\n'.join((http_method, http_uri, option['access_key'], option['signature_version'], str(timestamp))) 112 | 113 | signature = sign(string_to_sign, option['access_secret']) 114 | 115 | f = open(path, "r") 116 | 117 | files = {'audio_file':f} 118 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 119 | data = {"data_type":data_type} 120 | 121 | requrl = "https://"+option['host'] + http_uri 122 | r = requests.post(requrl, files=files, data=data, headers=headers, verify=True) 123 | r.encoding = "utf-8" 124 | print r.status_code 125 | 126 | if __name__ == "__main__": 127 | timestamp = time.time() 128 | create_channel_playback(3833, 666, 7*24*3600) 129 | #update_channel_playback(1, 3833, 666, 30*24*3600); 130 | #get_all_channel_playback(3833) 131 | #get_channel_playback(1) 132 | #delete_channel_playback(1) 133 | upload_audio(sys.argv[1], 666, "fingerprint") 134 | -------------------------------------------------------------------------------- /RESTful service/delete_audios.php: -------------------------------------------------------------------------------- 1 | "Account" (top right corner) -> "RESTful API Keys" -> "Create Key Pair". 12 | Be Careful, they are different with access_key and access_secret of your project. 13 | */ 14 | $account_access_key = 'xxxxxx'; 15 | $account_access_secret = 'xxxxxx'; 16 | 17 | $string_to_sign = $http_method . "\n" . 18 | $http_uri ."\n" . 19 | $account_access_key . "\n" . 20 | $signature_version . "\n" . 21 | $timestamp; 22 | $signature = hash_hmac("sha1",$string_to_sign,$account_access_secret,true); 23 | $signature = base64_encode($signature); 24 | $headerArray = array(); 25 | $headers = array( 26 | 'access-key' => $account_access_key, 27 | 'timestamp' => $timestamp, 28 | 'signature-version' => '1', 29 | 'signature' => $signature 30 | ); 31 | foreach( $headers as $n => $v ) { 32 | $headerArr[] = $n .':' . $v; 33 | } 34 | $ch = curl_init(); 35 | curl_setopt($ch, CURLOPT_URL, $request_url); 36 | curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); 37 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 38 | curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr); 39 | $response = curl_exec($ch); 40 | var_dump($response); 41 | curl_close($ch); 42 | ?> 43 | -------------------------------------------------------------------------------- /RESTful service/get_ads.js: -------------------------------------------------------------------------------- 1 | var url = require('url'); 2 | var path = require('path'); 3 | var fs = require('fs'); 4 | var crypto = require('crypto'); 5 | var express = require('express'); 6 | //npm install request 7 | var request = require('request'); 8 | 9 | 10 | const app = express(); 11 | 12 | 13 | var defaultOptions = { 14 | host: 'api.acrcloud.com', 15 | endpoint: '/v1/audios', 16 | signature_version: '1', 17 | secure: true, 18 | access_key: '#ACCESS_KEY#', 19 | access_secret: '#ACCESS_SECRET#' 20 | }; 21 | 22 | function buildStringToSign(method, uri, accessKey, signatureVersion, timestamp) { 23 | return [method, uri, accessKey, signatureVersion, timestamp].join('\n'); 24 | } 25 | 26 | function sign(signString, accessSecret) { 27 | return crypto.createHmac('sha1', accessSecret) 28 | .update(new Buffer.from(signString, 'utf-8')) 29 | .digest().toString('base64'); 30 | } 31 | 32 | function get_audios(bucket, page, cb) { 33 | var current_data = new Date(); 34 | var timestamp = current_data.getTime() / 1000; 35 | 36 | var endpoint = defaultOptions.endpoint 37 | 38 | var stringToSign = buildStringToSign('GET', 39 | endpoint, 40 | defaultOptions.access_key, 41 | defaultOptions.signature_version, 42 | timestamp); 43 | 44 | var signature = sign(stringToSign, defaultOptions.access_secret); 45 | 46 | var headers = { 47 | 'access-key': defaultOptions.access_key, 48 | 'signature-version': defaultOptions.signature_version, 49 | 'signature': signature, 50 | 'timestamp': timestamp 51 | }; 52 | 53 | var requrl = "https://" + defaultOptions.host + endpoint + "?bucket_name=" + bucket + "&page=" + page 54 | 55 | request.get({ 56 | url: requrl, 57 | method: 'GET', 58 | headers: headers, 59 | }, cb); 60 | 61 | } 62 | 63 | 64 | app.get('/ads', (req, res) => { 65 | 66 | 67 | get_audios("#PROJECT_NAME#", 1, function(err, httpResponse, body) { 68 | res.send(body); 69 | }); 70 | 71 | }); 72 | 73 | 74 | module.exports = app; -------------------------------------------------------------------------------- /RESTful service/get_buckets.js: -------------------------------------------------------------------------------- 1 | var url = require('url'); 2 | var path = require('path'); 3 | var fs = require('fs'); 4 | var crypto = require('crypto'); 5 | var express = require('express'); 6 | //npm install request 7 | var request = require('request'); 8 | 9 | 10 | const app = express(); 11 | 12 | 13 | var defaultOptions = { 14 | host: 'api.acrcloud.com', 15 | endpoint: '/v1/buckets', 16 | signature_version: '1', 17 | secure: true, 18 | access_key: '#ACCESS_KEY#', 19 | access_secret: '#ACCESS_SECRET#' 20 | }; 21 | 22 | function buildStringToSign(method, uri, accessKey, signatureVersion, timestamp) { 23 | return [method, uri, accessKey, signatureVersion, timestamp].join('\n'); 24 | } 25 | 26 | function sign(signString, accessSecret) { 27 | return crypto.createHmac('sha1', accessSecret) 28 | .update(new Buffer.from(signString, 'utf-8')) 29 | .digest().toString('base64'); 30 | } 31 | 32 | function get_buckets(cb) { 33 | var current_data = new Date(); 34 | var timestamp = current_data.getTime() / 1000; 35 | 36 | var endpoint = defaultOptions.endpoint 37 | 38 | var stringToSign = buildStringToSign('GET', 39 | endpoint, 40 | defaultOptions.access_key, 41 | defaultOptions.signature_version, 42 | timestamp); 43 | 44 | var signature = sign(stringToSign, defaultOptions.access_secret); 45 | 46 | var headers = { 47 | 'access-key': defaultOptions.access_key, 48 | 'signature-version': defaultOptions.signature_version, 49 | 'signature': signature, 50 | 'timestamp': timestamp 51 | }; 52 | 53 | var requrl = "https://" + defaultOptions.host + endpoint; 54 | 55 | request.get({ 56 | url: requrl, 57 | method: 'GET', 58 | headers: headers, 59 | }, cb); 60 | 61 | } 62 | 63 | 64 | get_buckets(function(err, httpResponse, body) { 65 | 66 | console.log(body); 67 | 68 | }); -------------------------------------------------------------------------------- /RESTful service/get_channel.js: -------------------------------------------------------------------------------- 1 | var url = require('url'); 2 | var path = require('path'); 3 | var fs = require('fs'); 4 | var crypto = require('crypto'); 5 | var express = require('express'); 6 | //npm install request 7 | var request = require('request'); 8 | 9 | 10 | const app = express(); 11 | 12 | 13 | var defaultOptions = { 14 | host: 'api.acrcloud.com', 15 | endpoint: '/v1/buckets/', 16 | signature_version: '1', 17 | secure: true, 18 | access_key: '#ACCESS_KEY#', 19 | access_secret: '#ACCESS_SECRET#' 20 | }; 21 | 22 | function buildStringToSign(method, uri, accessKey, signatureVersion, timestamp) { 23 | return [method, uri, accessKey, signatureVersion, timestamp].join('\n'); 24 | } 25 | 26 | function sign(signString, accessSecret) { 27 | return crypto.createHmac('sha1', accessSecret) 28 | .update(new Buffer.from(signString, 'utf-8')) 29 | .digest().toString('base64'); 30 | } 31 | 32 | function get_channels(acrid, cb) { 33 | var current_data = new Date(); 34 | var timestamp = current_data.getTime() / 1000; 35 | 36 | var endpoint = defaultOptions.endpoint + acrid 37 | 38 | var stringToSign = buildStringToSign('GET', 39 | endpoint, 40 | defaultOptions.access_key, 41 | defaultOptions.signature_version, 42 | timestamp); 43 | 44 | var signature = sign(stringToSign, defaultOptions.access_secret); 45 | 46 | var headers = { 47 | 'access-key': defaultOptions.access_key, 48 | 'signature-version': defaultOptions.signature_version, 49 | 'signature': signature, 50 | 'timestamp': timestamp 51 | }; 52 | 53 | var requrl = "https://" + defaultOptions.host + endpoint; 54 | 55 | request.get({ 56 | url: requrl, 57 | method: 'GET', 58 | headers: headers, 59 | }, cb); 60 | 61 | } 62 | 63 | 64 | get_channels("#BUCKET_ID#", function(err, httpResponse, body) { 65 | 66 | console.log(body); 67 | 68 | }); -------------------------------------------------------------------------------- /RESTful service/get_channels.js: -------------------------------------------------------------------------------- 1 | var url = require('url'); 2 | var path = require('path'); 3 | var fs = require('fs'); 4 | var crypto = require('crypto'); 5 | var express = require('express'); 6 | //npm install request 7 | var request = require('request'); 8 | 9 | 10 | const app = express(); 11 | 12 | 13 | var defaultOptions = { 14 | host: 'api.acrcloud.com', 15 | endpoint: '/v1/buckets/', 16 | signature_version: '1', 17 | secure: true, 18 | access_key: '#ACCESS_KEY#', 19 | access_secret: '#ACCESS_SECRET#' 20 | }; 21 | 22 | function buildStringToSign(method, uri, accessKey, signatureVersion, timestamp) { 23 | return [method, uri, accessKey, signatureVersion, timestamp].join('\n'); 24 | } 25 | 26 | function sign(signString, accessSecret) { 27 | return crypto.createHmac('sha1', accessSecret) 28 | .update(new Buffer.from(signString, 'utf-8')) 29 | .digest().toString('base64'); 30 | } 31 | 32 | function get_channels(bucket, cb) { 33 | var current_data = new Date(); 34 | var timestamp = current_data.getTime() / 1000; 35 | 36 | var endpoint = defaultOptions.endpoint + bucket + "/channels" 37 | 38 | var stringToSign = buildStringToSign('GET', 39 | endpoint, 40 | defaultOptions.access_key, 41 | defaultOptions.signature_version, 42 | timestamp); 43 | 44 | var signature = sign(stringToSign, defaultOptions.access_secret); 45 | 46 | var headers = { 47 | 'access-key': defaultOptions.access_key, 48 | 'signature-version': defaultOptions.signature_version, 49 | 'signature': signature, 50 | 'timestamp': timestamp 51 | }; 52 | 53 | var requrl = "https://" + defaultOptions.host + endpoint; 54 | 55 | request.get({ 56 | url: requrl, 57 | method: 'GET', 58 | headers: headers, 59 | }, cb); 60 | 61 | } 62 | 63 | 64 | get_channels("#AUDIO_TITLE#", function(err, httpResponse, body) { 65 | 66 | console.log(body); 67 | 68 | }); -------------------------------------------------------------------------------- /RESTful service/get_channels.php: -------------------------------------------------------------------------------- 1 | $account_access_key, 23 | 'timestamp' => $timestamp, 24 | 'signature-version' => '1', 25 | 'signature' => $signature 26 | ); 27 | foreach( $headers as $n => $v ) { 28 | $headerArr[] = $n .':' . $v; 29 | } 30 | $ch = curl_init(); 31 | curl_setopt($ch, CURLOPT_URL, $request_url); 32 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 33 | curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr); 34 | $response = curl_exec($ch); 35 | var_dump($response); 36 | curl_close($ch); 37 | ?> 38 | -------------------------------------------------------------------------------- /RESTful service/get_monitor_stream.php: -------------------------------------------------------------------------------- 1 | $account_access_key, 23 | 'timestamp' => $timestamp, 24 | 'signature-version' => '1', 25 | 'signature' => $signature 26 | ); 27 | foreach( $headers as $n => $v ) { 28 | $headerArr[] = $n .':' . $v; 29 | } 30 | 31 | $ch = curl_init(); 32 | curl_setopt($ch, CURLOPT_URL, $request_url); 33 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 34 | curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr); 35 | $response = curl_exec($ch); 36 | var_dump($response); 37 | curl_close($ch); 38 | ?> 39 | -------------------------------------------------------------------------------- /RESTful service/get_project.js: -------------------------------------------------------------------------------- 1 | var url = require('url'); 2 | var path = require('path'); 3 | var fs = require('fs'); 4 | var crypto = require('crypto'); 5 | var express = require('express'); 6 | //npm install request 7 | var request = require('request'); 8 | 9 | 10 | const app = express(); 11 | 12 | 13 | var defaultOptions = { 14 | host: 'api.acrcloud.com', 15 | endpoint: '/v1/projects/', 16 | signature_version: '1', 17 | secure: true, 18 | access_key: '#ACCESS_KEY#', 19 | access_secret: '#ACCESS_SECRET#' 20 | }; 21 | 22 | function buildStringToSign(method, uri, accessKey, signatureVersion, timestamp) { 23 | return [method, uri, accessKey, signatureVersion, timestamp].join('\n'); 24 | } 25 | 26 | function sign(signString, accessSecret) { 27 | return crypto.createHmac('sha1', accessSecret) 28 | .update(new Buffer.from(signString, 'utf-8')) 29 | .digest().toString('base64'); 30 | } 31 | 32 | function get_project(project_name, cb) { 33 | var current_data = new Date(); 34 | var timestamp = current_data.getTime() / 1000; 35 | 36 | var endpoint = defaultOptions.endpoint + project_name 37 | 38 | var stringToSign = buildStringToSign('GET', 39 | endpoint, 40 | defaultOptions.access_key, 41 | defaultOptions.signature_version, 42 | timestamp); 43 | 44 | var signature = sign(stringToSign, defaultOptions.access_secret); 45 | 46 | var headers = { 47 | 'access-key': defaultOptions.access_key, 48 | 'signature-version': defaultOptions.signature_version, 49 | 'signature': signature, 50 | 'timestamp': timestamp 51 | }; 52 | 53 | var requrl = "https://" + defaultOptions.host + endpoint; 54 | 55 | request.get({ 56 | url: requrl, 57 | method: 'GET', 58 | headers: headers, 59 | }, cb); 60 | 61 | } 62 | 63 | 64 | get_project("#PROJECT_NAME#", function(err, httpResponse, body) { 65 | 66 | console.log(body); 67 | 68 | }); -------------------------------------------------------------------------------- /RESTful service/get_projects.js: -------------------------------------------------------------------------------- 1 | var url = require('url'); 2 | var path = require('path'); 3 | var fs = require('fs'); 4 | var crypto = require('crypto'); 5 | var express = require('express'); 6 | //npm install request 7 | var request = require('request'); 8 | 9 | 10 | const app = express(); 11 | 12 | 13 | var defaultOptions = { 14 | host: 'api.acrcloud.com', 15 | endpoint: '/v1/projects', 16 | signature_version: '1', 17 | secure: true, 18 | access_key: '#ACCESS_KEY#', 19 | access_secret: '#ACCESS_SECRET#' 20 | }; 21 | 22 | function buildStringToSign(method, uri, accessKey, signatureVersion, timestamp) { 23 | return [method, uri, accessKey, signatureVersion, timestamp].join('\n'); 24 | } 25 | 26 | function sign(signString, accessSecret) { 27 | return crypto.createHmac('sha1', accessSecret) 28 | .update(new Buffer.from(signString, 'utf-8')) 29 | .digest().toString('base64'); 30 | } 31 | 32 | function get_projects(cb) { 33 | var current_data = new Date(); 34 | var timestamp = current_data.getTime() / 1000; 35 | 36 | var endpoint = defaultOptions.endpoint 37 | 38 | var stringToSign = buildStringToSign('GET', 39 | endpoint, 40 | defaultOptions.access_key, 41 | defaultOptions.signature_version, 42 | timestamp); 43 | 44 | var signature = sign(stringToSign, defaultOptions.access_secret); 45 | 46 | var headers = { 47 | 'access-key': defaultOptions.access_key, 48 | 'signature-version': defaultOptions.signature_version, 49 | 'signature': signature, 50 | 'timestamp': timestamp 51 | }; 52 | 53 | var requrl = "https://" + defaultOptions.host + endpoint; 54 | 55 | request.get({ 56 | url: requrl, 57 | method: 'GET', 58 | headers: headers, 59 | }, cb); 60 | 61 | } 62 | 63 | 64 | get_projects(function(err, httpResponse, body) { 65 | 66 | console.log(body); 67 | 68 | }); 69 | 70 | module.exports = app; -------------------------------------------------------------------------------- /RESTful service/list_buckets.php: -------------------------------------------------------------------------------- 1 | "Account" (top right corner) -> "RESTful API Keys" -> "Create Key Pair". 11 | Be Careful, they are different with access_key and access_secret of your project. 12 | */ 13 | $account_access_key = 'xxx'; 14 | $account_access_secret = 'xxxx'; 15 | 16 | $string_to_sign = $http_method . "\n" . 17 | $http_uri ."\n" . 18 | $account_access_key . "\n" . 19 | $signature_version . "\n" . 20 | $timestamp; 21 | $signature = hash_hmac("sha1",$string_to_sign,$account_access_secret,true); 22 | $signature = base64_encode($signature); 23 | 24 | $headerArray = array(); 25 | $headers = array( 26 | 'access-key' => $account_access_key, 27 | 'timestamp' => $timestamp, 28 | 'signature-version' => '1', 29 | 'signature' => $signature 30 | ); 31 | foreach( $headers as $n => $v ) { 32 | $headerArr[] = $n .':' . $v; 33 | } 34 | $ch = curl_init(); 35 | curl_setopt($ch, CURLOPT_URL, $request_url); 36 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 37 | curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr); 38 | $response = curl_exec($ch); 39 | var_dump($response); 40 | curl_close($ch); 41 | ?> 42 | -------------------------------------------------------------------------------- /RESTful service/monitor_add.js: -------------------------------------------------------------------------------- 1 | var url = require('url'); 2 | var crypto = require('crypto'); 3 | //npm install request 4 | var request = require('request'); 5 | 6 | var defaultOptions = { 7 | host: 'api.acrcloud.com', 8 | endpoint: '/v1/monitor-streams', 9 | signature_version: '1', 10 | access_key: '', 11 | access_secret: '' 12 | }; 13 | 14 | function buildStringToSign(method, uri, accessKey, signatureVersion, timestamp) { 15 | return [method, uri, accessKey, signatureVersion, timestamp].join('\n'); 16 | } 17 | 18 | function sign(signString, accessSecret) { 19 | return crypto.createHmac('sha1', accessSecret) 20 | .update(new Buffer(signString, 'utf-8')) 21 | .digest().toString('base64'); 22 | } 23 | 24 | function add_stream(stream_url, stream_name, project_name, options, cb) { 25 | 26 | var current_data = new Date(); 27 | var timestamp = current_data.getTime()/1000; 28 | 29 | var stringToSign = buildStringToSign('POST', 30 | options.endpoint, 31 | options.access_key, 32 | options.signature_version, 33 | timestamp); 34 | 35 | var signature = sign(stringToSign, options.access_secret); 36 | 37 | var form = { 38 | url:stream_url, 39 | stream_name:stream_name, 40 | project_name:project_name, 41 | }; 42 | var headers = { 43 | 'access-key': options.access_key, 44 | 'signature-version': options.signature_version, 45 | 'signature': signature, 46 | 'timestamp':timestamp 47 | }; 48 | request.post({ 49 | url: "https://"+options.host + options.endpoint, 50 | method: 'POST', 51 | form: form, 52 | headers: headers 53 | }, cb); 54 | } 55 | 56 | 57 | add_stream("http://127.0.0.1", "test", "monitor_test", defaultOptions, function (err, httpResponse, body) { 58 | if (err) console.log(err); 59 | console.log(body); 60 | }); 61 | -------------------------------------------------------------------------------- /RESTful service/monitor_add.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import base64 4 | import hmac 5 | import hashlib 6 | import urllib 7 | import time 8 | import requests 9 | 10 | ''' 11 | This demo shows how to use the RESTful API to upload an audio file ( "data_type":"audio" ) into your bucket. 12 | You can find account_access_key and account_access_secret in your account page. 13 | Log into http://console.acrcloud.com -> "Account" (top right corner) -> "RESTful API Keys" -> "Create Key Pair". 14 | Be Careful, they are different with access_key and access_secret of your project. 15 | ''' 16 | account_access_key = "xxxxxx" 17 | account_access_secret = "xxxxxx" 18 | 19 | requrl = "https://api.acrcloud.com/v1/monitor-streams" 20 | http_method = "POST" 21 | http_uri = "/v1/monitor-streams" 22 | signature_version = "1" 23 | timestamp = str(time.time()) 24 | 25 | string_to_sign = http_method+"\n"+http_uri+"\n"+account_access_key+"\n"+signature_version+"\n"+str(timestamp) 26 | 27 | sign = base64.b64encode( 28 | hmac.new(account_access_secret.encode(), string_to_sign.encode(), digestmod=hashlib.sha1) 29 | .digest()) 30 | 31 | headers = {'access-key': account_access_key, 'signature-version': signature_version, 'signature': sign, 'timestamp':timestamp} 32 | data = {'url':'http://rs.xxxxxxxx.com/r_11/11.m3u8', 'stream_name':'test_cn', 'project_name':"asdfsdf", "region":"us-west-2"} 33 | 34 | r = requests.post(requrl, data=data, headers=headers, verify=True) 35 | r.encoding = "utf-8" 36 | print r.text 37 | -------------------------------------------------------------------------------- /RESTful service/monitor_api_for_broadcast_database.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #-*- coding:utf-8 -*- 3 | 4 | import os 5 | import sys 6 | import time 7 | import hmac 8 | import json 9 | import base64 10 | import hashlib 11 | import requests 12 | import traceback 13 | 14 | reload(sys) 15 | sys.setdefaultencoding("utf8") 16 | 17 | """ 18 | This demo shows how to use the RESTful API to operate ACRCloud Broadcast Database Monitoring(project, channel, results) 19 | You can find account_access_key and account_access_secret in your account page. 20 | Log into http://console.acrcloud.com -> "Your Name"(top right corner) -> "Account" -> "Console API Keys" -> "Create Key Pair". 21 | Be Careful, they are different with access_key and access_secret of your project. 22 | """ 23 | 24 | 25 | class Acrcloud_Monitor_API: 26 | 27 | def __init__(self, account_access_key, account_access_secret): 28 | self.account_access_key = account_access_key 29 | self.account_access_secret = account_access_secret 30 | 31 | def create_headers(self, http_uri, http_method, signature_version): 32 | timestamp = time.time() 33 | string_to_sign = "\n".join([http_method, http_uri, self.account_access_key, signature_version, str(timestamp)]) 34 | sign = base64.b64encode(hmac.new(self.account_access_secret, string_to_sign, digestmod=hashlib.sha1).digest()) 35 | headers = { 36 | "access-key": self.account_access_key, 37 | "signature-version": signature_version, 38 | "signature": sign, 39 | "timestamp": timestamp 40 | } 41 | return headers 42 | 43 | def get_projects(self): 44 | requrl = "https://api.acrcloud.com/v1/acrcloud-monitor-streams/projects" 45 | http_uri = requrl[requrl.find("/v1/"):] 46 | http_method = "GET" 47 | signature_version = "1" 48 | 49 | headers = self.create_headers(http_uri, http_method, signature_version) 50 | r = requests.get(requrl, headers=headers, verify=True) 51 | r.encoding = "utf-8" 52 | return r.text 53 | 54 | def set_result_callback(self, project_name, result_callback_url, send_noresult=False, post_data_type="json", result_type="realtime"): 55 | requrl = "https://api.acrcloud.com/v1/acrcloud-monitor-streams/projects/result_callback" 56 | http_uri = requrl[requrl.find("/v1/"):] 57 | http_method = "POST" 58 | signature_version = "1" 59 | 60 | headers = self.create_headers(http_uri, http_method, signature_version) 61 | data = { 62 | "project_name":project_name, 63 | "url":result_callback_url, 64 | "send_noresult":send_noresult, 65 | "post_data_type":post_data_type, 66 | "result_type":result_type, 67 | } 68 | r = requests.post(requrl, data=data, headers=headers, verify=True) 69 | r.encoding = "utf-8" 70 | return r.text 71 | 72 | def set_state_callback(self, project_name, state_callback_url, post_data_type="json"): 73 | requrl = "https://api.acrcloud.com/v1/acrcloud-monitor-streams/projects/state_callback" 74 | http_uri = requrl[requrl.find("/v1/"):] 75 | http_method = "POST" 76 | signature_version = "1" 77 | 78 | headers = self.create_headers(http_uri, http_method, signature_version) 79 | data = { 80 | "project_name":project_name, 81 | "url":state_callback_url, 82 | "post_data_type":post_data_type, 83 | } 84 | r = requests.post(requrl, data=data, headers=headers, verify=True) 85 | r.encoding = "utf-8" 86 | return r.text 87 | 88 | def get_project_channels(self, project_name, page_num=1): 89 | requrl = "https://api.acrcloud.com/v1/acrcloud-monitor-streams" 90 | http_uri = requrl[requrl.find("/v1/"):] 91 | http_method = "GET" 92 | signature_version = "1" 93 | 94 | headers = self.create_headers(http_uri, http_method, signature_version) 95 | params = {"project_name":project_name, "page":page_num} 96 | r = requests.get(requrl, params=params, headers=headers, verify=True) 97 | r.encoding = "utf-8" 98 | return r.text 99 | 100 | def get_channel_info(self, channel_id): 101 | requrl = "https://api.acrcloud.com/v1/acrcloud-monitor-streams/{0}".format(channel_id) 102 | http_uri = requrl[requrl.find("/v1/"):] 103 | http_method = "GET" 104 | signature_version = "1" 105 | 106 | headers = self.create_headers(http_uri, http_method, signature_version) 107 | r = requests.get(requrl, headers=headers, verify=True) 108 | r.encoding = "utf-8" 109 | return r.text 110 | 111 | def get_channel_results(self, project_name, channel_id, date): 112 | requrl = "https://api.acrcloud.com/v1/acrcloud-monitor-streams/{0}/results".format(channel_id) 113 | http_uri = requrl[requrl.find("/v1/"):] 114 | http_method = "GET" 115 | signature_version = "1" 116 | 117 | headers = self.create_headers(http_uri, http_method, signature_version) 118 | params = {"project_name":project_name, "date":date} 119 | r = requests.get(requrl, params=params, headers=headers, verify=True) 120 | r.encoding = "utf-8" 121 | return r.text 122 | 123 | def get_channel_urls(self, channel_id): 124 | requrl = "https://api.acrcloud.com/v1/acrcloud-monitor-streams/{0}/urls".format(channel_id) 125 | http_uri = requrl[requrl.find("/v1/"):] 126 | http_method = "GET" 127 | signature_version = "1" 128 | 129 | headers = self.create_headers(http_uri, http_method, signature_version) 130 | r = requests.get(requrl, headers=headers, verify=True) 131 | r.encoding = "utf-8" 132 | return r.text 133 | 134 | def del_channel_urls(self, channel_id, del_url_list): 135 | requrl = "https://api.acrcloud.com/v1/acrcloud-monitor-streams/{0}/urls".format(channel_id) 136 | http_uri = requrl[requrl.find("/v1/"):] 137 | http_method = "DELETE" 138 | signature_version = "1" 139 | 140 | headers = self.create_headers(http_uri, http_method, signature_version) 141 | data = {"del_urls":json.dumps(del_url_list)} 142 | r = requests.delete(requrl, data=data, headers=headers, verify=True) 143 | r.encoding = "utf-8" 144 | return r.text 145 | 146 | def add_channel_urls(self, channel_id, add_url_list): 147 | requrl = "https://api.acrcloud.com/v1/acrcloud-monitor-streams/{0}/urls".format(channel_id) 148 | http_uri = requrl[requrl.find("/v1/"):] 149 | http_method = "POST" 150 | signature_version = "1" 151 | 152 | headers = self.create_headers(http_uri, http_method, signature_version) 153 | params = {"add_urls":json.dumps(add_url_list)} 154 | r = requests.post(requrl, data=data, headers=headers, verify=True) 155 | r.encoding = "utf-8" 156 | return r.text 157 | 158 | def download_rec_recording(self, access_key, channel_id, record_timestamp, played_duration): 159 | "GET,HEAD /acrcloud-monitor-streams/recording/" 160 | requrl = "https://api.acrcloud.com/v1/acrcloud-monitor-streams/recording/{0}/{1}".format(access_key, channel_id) 161 | http_uri = requrl[requrl.find("/v1/"):] 162 | http_method = "GET" 163 | signature_version = "1" 164 | 165 | headers = self.create_headers(http_uri, http_method, signature_version) 166 | params = {"record_timestamp":record_timestamp, "played_duration":played_duration} 167 | r = requests.get(requrl, params=params, headers=headers, verify=True) 168 | try: 169 | d = r.headers['content-disposition'] 170 | fname = d[ (d.find('filename="') + len('filename="')) : d.find('";') ] 171 | fname = fname.replace(":", "_") 172 | except Exception as e: 173 | fname = "acrcloud_{0}_{1}_{2}.failed".format(channel_id, record_timestamp, played_duration) 174 | return fname, r.content 175 | 176 | def get_day_recording_list(self, project_access_key, channel_id, date): 177 | "GET,HEAD /acrcloud-monitor-streams/recording_list/" 178 | requrl = "https://api.acrcloud.com/v1/acrcloud-monitor-streams/recording_list/{0}/{1}".format(project_access_key, channel_id) 179 | http_uri = requrl[requrl.find("/v1/"):] 180 | http_method = "GET" 181 | signature_version = "1" 182 | 183 | headers = self.create_headers(http_uri, http_method, signature_version) 184 | params = {"date":date} 185 | r = requests.get(requrl, params=params, headers=headers, verify=True) 186 | r.encoding = "utf-8" 187 | return r.text 188 | 189 | def download_hour_recording(self, project_access_key, channel_id, timestamp, duration, file_type): 190 | "GET,HEAD /acrcloud-monitor-streams/recording_download/" 191 | requrl = "https://api.acrcloud.com/v1/acrcloud-monitor-streams/recording_download/{0}/{1}".format(project_access_key, channel_id) 192 | http_uri = requrl[requrl.find("/v1/"):] 193 | http_method = "GET" 194 | signature_version = "1" 195 | 196 | headers = self.create_headers(http_uri, http_method, signature_version) 197 | params = {"timestamp":timestamp, "duration": duration, "type": file_type} 198 | r = requests.get(requrl, params=params, headers=headers, verify=True) 199 | try: 200 | d = r.headers['content-disposition'] 201 | fname = d[ (d.find('filename="') + len('filename="')) : d.find('";') ] 202 | fname = fname.replace(":", "_") 203 | except Exception as e: 204 | timestamp_f = datetime.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S').strftime('%Y%m%d%H%M%S') 205 | fname = "acrcloud_{0}_{1}_{2}.failed".format(channel_id, timestamp_f, duration) 206 | return fname, r.content 207 | 208 | class Acrcloud_Monitor_Demo: 209 | 210 | def __init__(self, config): 211 | self.config = config 212 | self.api = Acrcloud_Monitor_API(self.config["account_access_key"], self.config["account_access_secret"]) 213 | 214 | def projects(self): 215 | try: 216 | info = self.api.get_projects() 217 | jinfo = json.loads(info) 218 | return jinfo["data"] 219 | except Exception as e: 220 | traceback.print_exc() 221 | return [] 222 | 223 | def set_state_callback(self, project_name, state_callback_url, post_data_type="json"): 224 | """ 225 | post_data_type: "json" or "form" 226 | """ 227 | try: 228 | if state_callback_url: 229 | return self.api.set_state_callback(project_name, state_callback_url, post_data_type) 230 | except Exception as e: 231 | traceback.print_exc() 232 | return None 233 | 234 | def set_result_callback(self, project_name, result_callback_url, send_noresult=False, post_data_type="json", result_type="realtime"): 235 | """ 236 | send_noresult: True or False 237 | post_data_type: "json" or "form" 238 | result_type: "realtime" or "delay" 239 | """ 240 | try: 241 | if result_callback_url: 242 | return self.api.set_result_callback(project_name, result_callback_url, send_noresult, post_data_type, result_type) 243 | except Exception as e: 244 | traceback.print_exc() 245 | return None 246 | 247 | def all_project_channels(self, project_name): 248 | try: 249 | stream_list = [] 250 | page_num = 1 251 | while 1: 252 | info = self.api.get_project_channels(project_name, page_num) 253 | jsoninfo = json.loads(info) 254 | for item in jsoninfo["items"]: 255 | stream_list.append(item) 256 | #print jsoninfo["_meta"] 257 | if jsoninfo["_meta"]["currentPage"] == jsoninfo["_meta"]["pageCount"] : 258 | break 259 | page_num += 1 260 | #print "Project:{0}, Total number of channels: {1}".format(project_name, len(stream_list)) 261 | except Exception as e: 262 | traceback.print_exc() 263 | return stream_list 264 | 265 | def channel_info(self, channel_id): 266 | return self.api.get_channel_info(channel_id) 267 | 268 | def channel_results(self, project_name, channel_id, date): 269 | results = self.api.get_channel_results(project_name, channel_id, date) 270 | jresults = json.loads(results) 271 | return jresults 272 | 273 | def get_channel_urls(self, channel_id): 274 | urls = self.api.get_channel_urls(channel_id) 275 | jurls = json.loads(urls) 276 | return jurls 277 | 278 | def add_channel_urls(self, channel_id, add_urls): 279 | ret = self.api.add_channel_urls(channel_id, add_urls) 280 | return ret 281 | 282 | def del_channel_urls(self, channel_id, del_urls): 283 | ret = self.api.del_channel_urls(channel_id, del_urls) 284 | return ret 285 | 286 | def download_rec_recording(self, access_key, channel_id, record_timestamp, played_duration): 287 | fname, content = self.api.download_rec_recording(access_key, channel_id, record_timestamp, played_duration) 288 | return fname, content 289 | 290 | def get_day_recording_list(self, access_key, channel_id, date): 291 | ret = self.api.get_day_recording_list(access_key, channel_id, date) 292 | recording_list = json.loads(ret) 293 | return recording_list 294 | 295 | def download_hour_recording(self, access_key, channel_id, timestamp, duration, file_type): 296 | fname, content = self.api.download_hour_recording(access_key, channel_id, timestamp, duration, file_type) 297 | return fname, content 298 | 299 | if __name__ == "__main__": 300 | config = { 301 | "account_access_key" : "XXXX", 302 | "account_access_secret" : "XXXXXXXXXX", 303 | } 304 | 305 | ams = Acrcloud_Monitor_Demo(config) 306 | 307 | """ 308 | #Get all the projects 309 | project_list = ams.projects() 310 | """ 311 | 312 | """ 313 | #Set State Callback_URL 314 | #post_data_type: "json" or "form" 315 | ams.set_state_callback("", "", "json") 316 | """ 317 | 318 | """ 319 | #Set Result Callback_URL 320 | #send_noresult: True or False 321 | #post_data_type: "json" or "form" 322 | #result_type: "realtime" or "delay" 323 | print ams.set_result_callback("", "", False, "form", "realtime") 324 | """ 325 | 326 | """ 327 | project_name = "" 328 | print ams.all_project_channels(project_name) 329 | 330 | channel_id = "" 331 | print ams.channel_info(channel_id) 332 | """ 333 | 334 | """ 335 | channel_id = "XXXXX" 336 | print ams.get_channel_urls(channel_id) 337 | add_url_list = ["url1"] 338 | print ams.add_channel_urls(channel_id, add_url_list) 339 | print ams.get_channel_urls(channel_id) 340 | del_url_list = ["url1"] 341 | print ams.del_channel_urls(channel_id, del_url_list) 342 | """ 343 | 344 | """ 345 | # download rec recording 346 | access_key = "" 347 | channel_id = "" 348 | record_timestamp = "20191203131312" 349 | played_duration = 100 350 | fname, fcontent = ams.download_rec_recording(access_key, channel_id, record_timestamp, played_duration) 351 | if not fname.endswith("failed"): 352 | with open(fname, "wb") as wfile: 353 | wfile.write(fcontent) 354 | """ 355 | 356 | """ 357 | # download hour recording 358 | access_key = "" 359 | channel_id = "" 360 | date = "" 361 | jinfo = ams.get_day_recording_list(access_key, channel_id, date) 362 | for item in jinfo["data"]: 363 | print item 364 | timestamp = item["timestamp"] 365 | duration = item["duration"] 366 | file_type = item["type"] 367 | fname, fcontent = ams.download_hour_recording(access_key, channel_id, timestamp, duration, file_type) 368 | print fname 369 | with open(fname, "wb") as wfile: 370 | wfile.write(fcontent) 371 | """ 372 | -------------------------------------------------------------------------------- /RESTful service/monitor_api_for_custom_streams.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #-*- coding:utf-8 -*- 3 | 4 | import os 5 | import sys 6 | import time 7 | import hmac 8 | import json 9 | import base64 10 | import hashlib 11 | import requests 12 | import traceback 13 | 14 | reload(sys) 15 | sys.setdefaultencoding("utf8") 16 | 17 | """ 18 | This demo shows how to use the RESTful API to operate Broadcast Monitoring(Custom Streams) 19 | You can find account_access_key and account_access_secret in your account page. 20 | Log into http://console.acrcloud.com -> "Your Name"(top right corner) -> "Account" -> "Console API Keys" -> "Create Key Pair". 21 | Be Careful, they are different with access_key and access_secret of your project. 22 | """ 23 | 24 | 25 | class Acrcloud_Monitor_API_for_custom_streams: 26 | 27 | def __init__(self, account_access_key, account_access_secret): 28 | self.account_access_key = account_access_key 29 | self.account_access_secret = account_access_secret 30 | 31 | def create_headers(self, http_uri, http_method, signature_version): 32 | timestamp = time.time() 33 | string_to_sign = "\n".join([http_method, http_uri, self.account_access_key, signature_version, str(timestamp)]) 34 | sign = base64.b64encode(hmac.new(self.account_access_secret, string_to_sign, digestmod=hashlib.sha1).digest()) 35 | headers = { 36 | "access-key": self.account_access_key, 37 | "signature-version": signature_version, 38 | "signature": sign, 39 | "timestamp": str(timestamp) 40 | } 41 | return headers 42 | 43 | def get_project_channels(self, project_name, page_num=1): 44 | requrl = "https://api.acrcloud.com/v1/monitor-streams" 45 | http_uri = requrl[requrl.find("/v1/"):] 46 | http_method = "GET" 47 | signature_version = "1" 48 | 49 | headers = self.create_headers(http_uri, http_method, signature_version) 50 | params = {"project_name":project_name, "page":page_num} 51 | r = requests.get(requrl, params=params, headers=headers, verify=True) 52 | r.encoding = "utf-8" 53 | return r.text 54 | 55 | def add_channel(self, project_name, stream_name, region, config_name, url): 56 | requrl = "https://api.acrcloud.com/v1/monitor-streams" 57 | http_uri = requrl[requrl.find("/v1/"):] 58 | http_method = "POST" 59 | signature_version = "1" 60 | 61 | headers = self.create_headers(http_uri, http_method, signature_version) 62 | data = { 63 | "project_name" : project_name, 64 | "stream_name": stream_name, 65 | "region": region, 66 | "stream_config": config_name, 67 | "url": url 68 | } 69 | r = requests.post(requrl, data=data, headers=headers, verify=True) 70 | r.encoding = "utf-8" 71 | return r.text 72 | 73 | def delete_channel(self, stream_id): 74 | requrl = "https://api.acrcloud.com/v1/monitor-streams/{0}".format(stream_id) 75 | http_uri = requrl[requrl.find("/v1/"):] 76 | http_method = "DELETE" 77 | signature_version = "1" 78 | 79 | headers = self.create_headers(http_uri, http_method, signature_version) 80 | r = requests.delete(requrl, headers=headers, verify=True) 81 | r.encoding = "utf-8" 82 | return r.text 83 | 84 | def pause_restart_channel(self, stream_id, action_type="pause"): 85 | #action_type: 1. pause, 2. restart 86 | requrl = "https://api.acrcloud.com/v1/monitor-streams/{0}/{1}".format(stream_id, action_type) 87 | http_uri = requrl[requrl.find("/v1/"):] 88 | http_method = "PUT" 89 | signature_version = "1" 90 | 91 | headers = self.create_headers(http_uri, http_method, signature_version) 92 | r = requests.put(requrl, headers=headers, verify=True) 93 | r.encoding = "utf-8" 94 | return r.text 95 | 96 | def update_channel(self, stream_id, update_info): 97 | requrl = "https://api.acrcloud.com/v1/monitor-streams/{0}".format(stream_id) 98 | http_uri = requrl[requrl.find("/v1/"):] 99 | http_method = "PUT" 100 | signature_version = "1" 101 | 102 | headers = self.create_headers(http_uri, http_method, signature_version) 103 | """ 104 | update_info = { 105 | "stream_name":"xxx", 106 | "url":"xxxx", 107 | "region":"xxxx", 108 | "realtime":0, #0-realtime, 1-delay 109 | } 110 | """ 111 | r = requests.put(requrl, data=update_info, headers=headers, verify=True) 112 | r.encoding = "utf-8" 113 | return r.text 114 | 115 | def set_callback(self, project_access_key, callback_url, post_type="json", send_noresult=0): 116 | requrl = "https://ap-api.acrcloud.com/v1/monitors/{0}/callback".format(project_access_key) 117 | http_uri = requrl[requrl.find("/v1/"):] 118 | http_method = "POST" 119 | signature_version = "1" 120 | 121 | headers = self.create_headers(http_uri, http_method, signature_version) 122 | data = { 123 | "callback_url": callback_url, 124 | "post_type": post_type, #json or form 125 | "send_noresult": send_noresult, 126 | } 127 | 128 | r = requests.post(requrl, data=data, headers=headers, verify=True) 129 | r.encoding = "utf-8" 130 | return r.text 131 | 132 | def get_recording(self, project_access_key, stream_id, record_timestamp, played_duration): 133 | requrl = "https://api.acrcloud.com/v1/monitor-streams/{0}/record".format(stream_id) 134 | http_uri = requrl[requrl.find("/v1/"):] 135 | http_method = "GET" 136 | signature_version = "1" 137 | 138 | headers = self.create_headers(http_uri, http_method, signature_version) 139 | params = {"access_key":project_access_key, "record_time":record_timestamp, "record_duration":played_duration} 140 | r = requests.get(requrl, params=params, headers=headers, verify=True) 141 | try: 142 | d = r.headers['content-disposition'] 143 | fname = d[ (d.find('filename="') + len('filename="')) : d.find('";') ] 144 | fname = fname.replace(":", "_") 145 | except Exception as e: 146 | #print ("Error@get_recording: {0}".format(str(e))) 147 | traceback.print_exc() 148 | fname = "acrcloud_{0}_{1}_{2}.failed".format(stream_id, record_timestamp, played_duration) 149 | return fname, r.content 150 | 151 | 152 | class Custom_Monitor_Demo: 153 | 154 | def __init__(self, config): 155 | self.config = config 156 | self.project_name = self.config["project_name"] 157 | self.project_access_key = self.config["project_access_key"] 158 | self.api = Acrcloud_Monitor_API_for_custom_streams(self.config["account_access_key"], self.config["account_access_secret"]) 159 | 160 | def all_project_channels(self): 161 | try: 162 | stream_list = [] 163 | page_num = 1 164 | while 1: 165 | info = self.api.get_project_channels(self.project_name, page_num) 166 | jsoninfo = json.loads(info) 167 | for item in jsoninfo["items"]: 168 | stream_list.append(item) 169 | #print jsoninfo["_meta"] 170 | if jsoninfo["_meta"]["currentPage"] == jsoninfo["_meta"]["pageCount"] : 171 | break 172 | page_num += 1 173 | print "Project:{0}, Total number of channels: {1}".format(self.project_name, len(stream_list)) 174 | except Exception as e: 175 | traceback.print_exc() 176 | return stream_list 177 | 178 | def add_monitor(self, stream_name, region, config_name, url): 179 | print "Add stream: {0}, {1}, {2}, {3}".format(stream_name, region, config_name, self.api.add_channel(self.project_name, stream_name, region, config_name, url)) 180 | 181 | def del_monitor(self, stream_id): 182 | print "Delete stream: {0}, {1}".format(stream_id, self.api.delete_channel(stream_id)) 183 | 184 | def pause_restart_monitor(self, stream_id, action_type="pause"): 185 | print "{0} stream: {1}, {2}".format(action_type, stream_id, self.api.pause_restart_channel(stream_id, action_type)) 186 | 187 | def update_monitor(self, stream_id, update_info): 188 | if update_info: 189 | print "update stream: {0}, {1}".format(stream_id, self.api.update_channel(stream_id, update_info)) 190 | else: 191 | print "update info is None, ", stream_id 192 | 193 | def set_callback(self, callback_url, post_type, send_noresult=0): 194 | print "set callback: ", callback_url, self.api.set_callback(self.project_access_key, callback_url, post_type, send_noresult) 195 | 196 | def get_recording(self, stream_id, record_timestamp, played_duration): 197 | fname, fcontent = self.api.get_recording(self.project_access_key, stream_id, record_timestamp, played_duration) 198 | with open(fname, "wb") as wfile: 199 | wfile.write(fcontent) 200 | return fname 201 | 202 | 203 | if __name__ == "__main__": 204 | config = { 205 | "account_access_key" : "<<< your account access_key >>>", 206 | "account_access_secret" : "<<< your account access_secret >>>", 207 | "project_name":"<<>>", 208 | "project_access_key":"<<< your project access_key >>>", 209 | } 210 | 211 | ams = Custom_Monitor_Demo(config) 212 | print ams.all_project_channels() 213 | #print ams.add_monitor("stream_id", "ap-northeast-1", "non-realtime", "http://xxxx") 214 | 215 | #stream_id="XXXX" 216 | #ams.pause_restart_monitor(stream_id, "restart") #pause or restart 217 | #ams.update_monitor(stream_id, {"stream_name":"xxxx"}) 218 | 219 | #callback_url = "www.xxxx.com" 220 | #ams.set_callback(callback_url, "form") 221 | 222 | #stream_id = "<<< your stream_id >>>" 223 | #record_timestamp = "<<< YYYYmmddHHMMSS >>>" #for example: 20200601101215 224 | #played_duration = 30 # seconds 225 | #ams.get_recording(stream_id, record_timestamp, played_duration) 226 | -------------------------------------------------------------------------------- /RESTful service/monitor_callback.php: -------------------------------------------------------------------------------- 1 | "Account" (top right corner) -> "RESTful API Keys" -> "Create Key Pair". 11 | Be Careful, they are different with access_key and access_secret of your project. 12 | */ 13 | $account_access_key = 'xxxxxxx'; 14 | $account_access_secret = 'xxxxxxxx'; 15 | 16 | $string_to_sign = $http_method . "\n" . 17 | $http_uri ."\n" . 18 | $account_access_key . "\n" . 19 | $signature_version . "\n" . 20 | $timestamp; 21 | $signature = hash_hmac("sha1",$string_to_sign,$account_access_secret,true); 22 | $signature = base64_encode($signature); 23 | 24 | $postfields = array( 25 | 'callback_url' => 'http://www.your_url.com', 26 | 'post_type' =>'json', 27 | 'send_noresult' => 0 28 | ); 29 | $headerArray = array(); 30 | $headers = array( 31 | 'access-key' => $account_access_key, 32 | 'timestamp' => $timestamp, 33 | 'signature-version' => '1', 34 | 'signature' => $signature 35 | ); 36 | foreach( $headers as $n => $v ) { 37 | $headerArr[] = $n .':' . $v; 38 | } 39 | $ch = curl_init(); 40 | curl_setopt($ch, CURLOPT_URL, $request_url); 41 | curl_setopt($ch, CURLOPT_POST, true); 42 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 43 | curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); 44 | curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr); 45 | $response = curl_exec($ch); 46 | var_dump($response); 47 | curl_close($ch); 48 | ?> 49 | -------------------------------------------------------------------------------- /RESTful service/monitor_callback.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import base64 4 | import hmac 5 | import hashlib 6 | import urllib 7 | import time 8 | import requests 9 | 10 | ''' 11 | This demo shows how to use the RESTful API to upload an audio file ( "data_type":"audio" ) into your bucket. 12 | You can find account_access_key and account_access_secret in your account page. 13 | Log into http://console.acrcloud.com -> "Account" (top right corner) -> "RESTful API Keys" -> "Create Key Pair". 14 | Be Careful, they are different with access_key and access_secret of your project. 15 | ''' 16 | account_access_key = "account_access_key" 17 | account_access_secret = "account_secret_key" 18 | 19 | #replace "your_project_key" with your monitor project key 20 | requrl = "https://api.acrcloud.com/v1/monitors/your_project_key/callback" 21 | http_method = "POST" 22 | http_uri = "/v1/monitors/your_project_key/callback" 23 | signature_version = "1" 24 | timestamp = time.time() 25 | 26 | string_to_sign = http_method+"\n"+http_uri+"\n"+account_access_key+"\n"+signature_version+"\n"+str(timestamp) 27 | 28 | sign = base64.b64encode( 29 | hmac.new(account_access_secret, string_to_sign, digestmod=hashlib.sha1) 30 | .digest()) 31 | 32 | headers = {'access-key': account_access_key, 'signature-version': signature_version, 'signature': sign, 'timestamp':timestamp} 33 | data = {'callback_url':'http://www.your_url.com', 'post_type':'json', 'send_noresult':0} 34 | 35 | r = requests.post(requrl, data=data, headers=headers, verify=True) 36 | r.encoding = "utf-8" 37 | print r.text 38 | -------------------------------------------------------------------------------- /RESTful service/monitor_del.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import base64 4 | import hmac 5 | import hashlib 6 | import urllib 7 | import time 8 | import requests 9 | 10 | ''' 11 | This demo shows how to use the RESTful API to upload an audio file ( "data_type":"audio" ) into your bucket. 12 | You can find account_access_key and account_access_secret in your account page. 13 | Log into http://console.acrcloud.com -> "Account" (top right corner) -> "RESTful API Keys" -> "Create Key Pair". 14 | Be Careful, they are different with access_key and access_secret of your project. 15 | ''' 16 | account_access_key = "###YOUR_ACCESS_KEY###" 17 | account_access_secret = "###YOUR_ACCESS_SECRET###" 18 | 19 | requrl = "https://api.acrcloud.com/v1/monitor-streams/###STREAM_ID###" 20 | http_method = "DELETE" 21 | http_uri = "/v1/monitor-streams/###STREAM_ID###" 22 | signature_version = "1" 23 | timestamp = str(time.time()) 24 | 25 | string_to_sign = http_method+"\n"+http_uri+"\n"+account_access_key+"\n"+signature_version+"\n"+str(timestamp) 26 | 27 | sign = base64.b64encode( 28 | hmac.new(account_access_secret.encode(), string_to_sign.encode(), digestmod=hashlib.sha1) 29 | .digest()) 30 | 31 | headers = {'access-key': account_access_key, 'signature-version': signature_version, 'signature': sign, 'timestamp':timestamp} 32 | 33 | r = requests.delete(requrl, headers=headers, verify=True) 34 | r.encoding = "utf-8" 35 | print r.text 36 | -------------------------------------------------------------------------------- /RESTful service/monitor_get.php: -------------------------------------------------------------------------------- 1 | $account_access_key, 23 | 'timestamp' => $timestamp, 24 | 'signature-version' => '1', 25 | 'signature' => $signature 26 | ); 27 | foreach( $headers as $n => $v ) { 28 | $headerArr[] = $n .':' . $v; 29 | } 30 | 31 | $ch = curl_init(); 32 | curl_setopt($ch, CURLOPT_URL, $request_url); 33 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 34 | curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr); 35 | $response = curl_exec($ch); 36 | var_dump($response); 37 | curl_close($ch); 38 | ?> 39 | -------------------------------------------------------------------------------- /RESTful service/monitor_get.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #-*- coding:utf-8 -*- 3 | 4 | import sys 5 | import os 6 | import base64 7 | import hmac 8 | import hashlib 9 | import urllib 10 | import time 11 | import requests 12 | 13 | reload(sys) 14 | sys.setdefaultencoding("utf8") 15 | 16 | ''' 17 | This demo shows how to use the RESTful API to upload an audio file ( "data_type":"audio" ) into your bucket. 18 | You can find account_access_key and account_access_secret in your account page. 19 | Log into http://console.acrcloud.com -> "Account" (top right corner) -> "RESTful API Keys" -> "Create Key Pair". 20 | Be Careful, they are different with access_key and access_secret of your project. 21 | ''' 22 | account_access_key = "###YOUR_ACCESS_KEY###" 23 | account_access_secret = "###YOUR_ACCESS_SECRET###" 24 | 25 | requrl = "https://api.acrcloud.com/v1/monitor-streams" 26 | http_method = "GET" 27 | http_uri = "/v1/monitor-streams" 28 | signature_version = "1" 29 | timestamp = time.time() 30 | 31 | string_to_sign = http_method+"\n"+http_uri+"\n"+account_access_key+"\n"+signature_version+"\n"+str(timestamp) 32 | 33 | sign = base64.b64encode( 34 | hmac.new(account_access_secret, string_to_sign, digestmod=hashlib.sha1) 35 | .digest()) 36 | 37 | headers = {'access-key': account_access_key, 'signature-version': signature_version, 'signature': sign, 'timestamp':str(timestamp)} 38 | params = {'project_name':"monitor_test"} 39 | 40 | r = requests.get(requrl, params=params, headers=headers, verify=True) 41 | r.encoding = "utf-8" 42 | print r.text 43 | -------------------------------------------------------------------------------- /RESTful service/monitor_pause.php: -------------------------------------------------------------------------------- 1 | $account_access_key, 21 | 'timestamp' => $timestamp, 22 | 'signature-version' => '1', 23 | 'signature' => $signature 24 | ); 25 | foreach( $headers as $n => $v ) { 26 | $headerArr[] = $n .':' . $v; 27 | } 28 | 29 | $ch = curl_init(); 30 | curl_setopt($ch, CURLOPT_URL, $request_url); 31 | curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); 32 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 33 | curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr); 34 | $response = curl_exec($ch); 35 | var_dump($response); 36 | curl_close($ch); 37 | } 38 | 39 | $account_access_key = ''; 40 | $account_access_secret = ''; 41 | $stream_id = ''; 42 | $action_type = 'pause'; // pause or restart 43 | 44 | monitor_update($account_access_key, $account_access_secret, $stream_id, $action_type); 45 | ?> 46 | -------------------------------------------------------------------------------- /RESTful service/monitor_pause.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import base64 4 | import hmac 5 | import hashlib 6 | import urllib 7 | import time 8 | import requests 9 | 10 | ''' 11 | This demo shows how to use the RESTful API to upload an audio file ( "data_type":"audio" ) into your bucket. 12 | You can find account_access_key and account_access_secret in your account page. 13 | Log into http://console.acrcloud.com -> "Account" (top right corner) -> "RESTful API Keys" -> "Create Key Pair". 14 | Be Careful, they are different with access_key and access_secret of your project. 15 | ''' 16 | account_access_key = "###YOUR_ACCESS_KEY###" 17 | account_access_secret = "###YOUR_ACCESS_SECRET###" 18 | 19 | requrl = "https://api.acrcloud.com/v1/monitor-streams/###STREAM_ID###/pause" 20 | #requrl = "https://api.acrcloud.com/v1/monitor-streams/###STREAM_ID###/restart" 21 | http_method = "PUT" 22 | http_uri = "/v1/monitor-streams/###STREAM_ID###/pause" 23 | #http_uri = "/v1/monitor-streams/###STREAM_ID###/restart" 24 | signature_version = "1" 25 | timestamp = str(time.time()) 26 | 27 | string_to_sign = http_method+"\n"+http_uri+"\n"+account_access_key+"\n"+signature_version+"\n"+str(timestamp) 28 | 29 | sign = base64.b64encode( 30 | hmac.new(account_access_secret.encode(), string_to_sign.encode(), digestmod=hashlib.sha1) 31 | .digest()) 32 | 33 | headers = {'access-key': account_access_key, 'signature-version': signature_version, 'signature': sign, 'timestamp':timestamp} 34 | 35 | r = requests.put(requrl, headers=headers, verify=True) 36 | r.encoding = "utf-8" 37 | print r.text 38 | -------------------------------------------------------------------------------- /RESTful service/monitor_update.java: -------------------------------------------------------------------------------- 1 | 2 | import java.io.File; 3 | import java.io.IOException; 4 | import java.util.Calendar; 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | import javax.crypto.Mac; 9 | import javax.crypto.spec.SecretKeySpec; 10 | 11 | // import commons-codec-.jar, download from http://commons.apache.org/proper/commons-codec/download_codec.cgi 12 | import org.apache.commons.codec.binary.Base64; 13 | 14 | // import HttpClient, download from http://hc.apache.org/downloads.cgi 15 | /** 16 | * 17 | * commons-codec-1.1*.jar 18 | * commons-logging-1.*.jar 19 | * httpclient-4.*.jar 20 | * httpcore-4.*.jar 21 | * httpmime-4.*.jar 22 | * 23 | * */ 24 | import org.apache.http.HttpEntity; 25 | import org.apache.http.HttpResponse; 26 | import org.apache.http.HttpStatus; 27 | import org.apache.http.client.config.RequestConfig; 28 | import org.apache.http.client.methods.HttpPost; 29 | import org.apache.http.entity.mime.MultipartEntityBuilder; 30 | import org.apache.http.entity.mime.content.StringBody; 31 | import org.apache.http.entity.ContentType; 32 | import org.apache.http.impl.client.CloseableHttpClient; 33 | import org.apache.http.impl.client.HttpClients; 34 | import org.apache.http.util.EntityUtils; 35 | 36 | public class Update_monitor { 37 | 38 | private String encodeBase64(byte[] bstr) { 39 | Base64 base64 = new Base64(); 40 | return new String(base64.encode(bstr)); 41 | } 42 | 43 | private String encryptByHMACSHA1(byte[] data, byte[] key) { 44 | try { 45 | SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA1"); 46 | Mac mac = Mac.getInstance("HmacSHA1"); 47 | mac.init(signingKey); 48 | byte[] rawHmac = mac.doFinal(data); 49 | return encodeBase64(rawHmac); 50 | } catch (Exception e) { 51 | e.printStackTrace(); 52 | } 53 | return ""; 54 | } 55 | 56 | private String getUTCTimeSeconds() { 57 | Calendar cal = Calendar.getInstance(); 58 | int zoneOffset = cal.get(Calendar.ZONE_OFFSET); 59 | int dstOffset = cal.get(Calendar.DST_OFFSET); 60 | cal.add(Calendar.MILLISECOND, -(zoneOffset + dstOffset)); 61 | return cal.getTimeInMillis() / 1000 + ""; 62 | } 63 | 64 | private String putHttp(String url, Map putParams, 65 | Map headerParams, int timeout) { 66 | String result = null; 67 | 68 | CloseableHttpClient httpClient = HttpClients.createDefault(); 69 | try { 70 | HttpPut httPut = new HttpPut(url); 71 | 72 | if (headerParams != null) { 73 | for (String key : headerParams.keySet()) { 74 | String value = headerParams.get(key); 75 | httpPut.addHeader(key, value); 76 | } 77 | } 78 | 79 | JSONObject jsonObject = JSONObject.fromObject(putParams); 80 | String jsonString = jsonObject.toString(); 81 | 82 | StringEntity params = new StringEntity(jsonString, "UTF-8"); 83 | params.setContentType("application/json"); 84 | 85 | RequestConfig requestConfig = RequestConfig.custom() 86 | .setConnectionRequestTimeout(timeout) 87 | .setConnectTimeout(timeout).setSocketTimeout(timeout) 88 | .build(); 89 | httpPut.setConfig(requestConfig); 90 | 91 | HttpResponse response = httpClient.execute(httpPut); 92 | 93 | System.out.println(response.getStatusLine().getStatusCode()); 94 | 95 | HttpEntity entity = response.getEntity(); 96 | result = EntityUtils.toString(entity); 97 | } catch (Exception e) { 98 | e.printStackTrace(); 99 | } finally { 100 | try { 101 | httpClient.close(); 102 | } catch (IOException e) { 103 | } 104 | } 105 | return result; 106 | } 107 | 108 | public String update(String streamID, String streamUrl, String streamName, String region, String realtime, 109 | String record, String accessKey, String accessSecret){ 110 | String result = null; 111 | String reqUrl = "https://api.acrcloud.com/v1/monitor-streams/"+streamID; 112 | String htttMethod = "PUT"; 113 | String httpAction = "/v1/monitor-streams/"+streamID; 114 | String signatureVersion = "1"; 115 | String timestamp = this.getUTCTimeSeconds(); 116 | 117 | String sigStr = htttMethod + "\n" + httpAction + "\n" + accessKey 118 | + "\n" + signatureVersion + "\n" + timestamp; 119 | String signature = encryptByHMACSHA1(sigStr.getBytes(), 120 | accessSecret.getBytes()); 121 | 122 | Map headerParams = new HashMap(); 123 | headerParams.put("access-key", accessKey); 124 | headerParams.put("signature-version", signatureVersion); 125 | headerParams.put("signature", signature); 126 | headerParams.put("timestamp", timestamp); 127 | 128 | Map postParams = new HashMap(); 129 | postParams.put("stream_name", streamName); 130 | postParams.put("url", streamUrl); 131 | postParams.put("region", region); 132 | postParams.put("realtime", realtime); 133 | postParams.put("record", record); 134 | 135 | result = this.putHttp(reqUrl, postParams, headerParams, 8000); 136 | 137 | return result; 138 | } 139 | /** 140 | * @param args 141 | */ 142 | public static void main(String[] args) { 143 | String streamID = ""; 144 | String streamUrl = ""; 145 | String streamName = ""; 146 | String region = ""; 147 | String realtime = ""; 148 | String record = ""; 149 | String accessKey = ""; 150 | String accessSecret = ""; 151 | 152 | Update_monitor ua = new Update_monitor(); 153 | 154 | String result = ua.update(streamID, streamUrl, streamName, region, realtime, 155 | record, accessKey, accessSecret); 156 | if (result == null) { 157 | System.out.println("upload error"); 158 | } 159 | 160 | System.out.println(result); 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /RESTful service/monitor_update.php: -------------------------------------------------------------------------------- 1 | $account_access_key, 23 | 'timestamp' => $timestamp, 24 | 'signature-version' => '1', 25 | 'signature' => $signature 26 | ); 27 | foreach( $headers as $n => $v ) { 28 | $headerArr[] = $n .':' . $v; 29 | } 30 | 31 | $put_data = array('stream_name'=>$stream_name, 'url'=>$url, "region"=>$region, "realtime"=>$realtime); 32 | 33 | $ch = curl_init(); 34 | curl_setopt($ch, CURLOPT_URL, $request_url); 35 | curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); 36 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 37 | curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($put_data)); 38 | curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr); 39 | $response = curl_exec($ch); 40 | var_dump($response); 41 | curl_close($ch); 42 | } 43 | 44 | $stream_id = "STREAM_ID"; 45 | $stream_name = "stream name"; 46 | $url = "the stream url"; 47 | $region = "The stream region"; 48 | $realtime = 0; 49 | monitor_update($stream_id, $stream_name, $url, $region, $realtime); 50 | ?> 51 | -------------------------------------------------------------------------------- /RESTful service/monitor_update.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import base64 4 | import hmac 5 | import hashlib 6 | import urllib 7 | import time 8 | import requests 9 | 10 | ''' 11 | This demo shows how to use the RESTful API to upload an audio file ( "data_type":"audio" ) into your bucket. 12 | You can find account_access_key and account_access_secret in your account page. 13 | Log into http://console.acrcloud.com -> "Account" (top right corner) -> "RESTful API Keys" -> "Create Key Pair". 14 | Be Careful, they are different with access_key and access_secret of your project. 15 | ''' 16 | account_access_key = "###YOUR_ACCESS_KEY###" 17 | account_access_secret = "###YOUR_ACCESS_SECRET###" 18 | 19 | requrl = "https://api.acrcloud.com/v1/monitor-streams/###STREM_ID###" 20 | http_method = "PUT" 21 | http_uri = "/v1/monitor-streams/###STREAM_ID###" 22 | signature_version = "1" 23 | timestamp = str(time.time()) 24 | 25 | string_to_sign = http_method+"\n"+http_uri+"\n"+account_access_key+"\n"+signature_version+"\n"+str(timestamp) 26 | 27 | sign = base64.b64encode( 28 | hmac.new(account_access_secret.encode(), string_to_sign.encode(), digestmod=hashlib.sha1) 29 | .digest()) 30 | 31 | headers = {'access-key': account_access_key, 'signature-version': signature_version, 'signature': sign, 'timestamp':timestamp} 32 | data = {'url':'http://rs.ajmide.com/r_11/11.m3u8', 'stream_name':'test_cn', "region":"ap-northeast-1", "realtime":0} 33 | 34 | r = requests.put(requrl, data=data, headers=headers, verify=True) 35 | r.encoding = "utf-8" 36 | print r.text 37 | -------------------------------------------------------------------------------- /RESTful service/offlinedb.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import base64 4 | import hmac 5 | import hashlib 6 | import urllib 7 | import time 8 | import requests 9 | import json 10 | 11 | option = { 12 | 'host': 'api.acrcloud.com', 13 | 'signature_version': '1', 14 | 'access_key': '', 15 | 'access_secret': '' 16 | }; 17 | 18 | 19 | def sign(string_to_sign, access_secret): 20 | return base64.b64encode( 21 | hmac.new(access_secret.encode(), string_to_sign.encode(), digestmod=hashlib.sha1) 22 | .digest()) 23 | 24 | def create_offline(name, buckets, audio_type, region): 25 | http_method = "POST" 26 | timestamp = str(time.time()) 27 | uri = '/v1/offlinedbs' 28 | 29 | string_to_sign = '\n'.join((http_method, uri, option['access_key'], option['signature_version'], str(timestamp))) 30 | 31 | signature = sign(string_to_sign, option['access_secret']) 32 | 33 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 34 | 35 | data = {'name':name, 'buckets':json.dumps(buckets), 'audio_type':audio_type, 'region':region} 36 | 37 | requrl = "https://"+option['host'] + uri 38 | r = requests.post(requrl, data=data, headers=headers, verify=True) 39 | r.encoding = "utf-8" 40 | print r.text 41 | 42 | def rebuild_offline(name, buckets = None): 43 | http_method = "PUT" 44 | timestamp = time.time() 45 | uri = '/v1/offlinedbs/'+name 46 | 47 | string_to_sign = '\n'.join((http_method, uri, option['access_key'], option['signature_version'], str(timestamp))) 48 | 49 | signature = sign(string_to_sign, option['access_secret']) 50 | 51 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 52 | 53 | requrl = "https://"+option['host'] + uri 54 | if buckets: 55 | data = {'buckets':json.dumps(buckets)} 56 | r = requests.put(requrl, headers=headers, data=data, verify=True) 57 | r.encoding = "utf-8" 58 | print r.text 59 | else: 60 | r = requests.put(requrl, headers=headers, verify=True) 61 | r.encoding = "utf-8" 62 | print r.text 63 | 64 | def delete_offline(name): 65 | http_method = "DELETE" 66 | timestamp = str(time.time()) 67 | uri = '/v1/offlinedbs'+"/"+name 68 | 69 | string_to_sign = '\n'.join((http_method, uri, option['access_key'], option['signature_version'], str(timestamp))) 70 | 71 | signature = sign(string_to_sign, option['access_secret']) 72 | 73 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 74 | 75 | requrl = "https://"+option['host'] + uri 76 | r = requests.delete(requrl, headers=headers, verify=True) 77 | r.encoding = "utf-8" 78 | print r.text 79 | 80 | def get_offline(name, path): 81 | http_method = "GET" 82 | timestamp = str(time.time()) 83 | uri = '/v1/offlinedbs'+"/"+name 84 | 85 | string_to_sign = '\n'.join((http_method, uri, option['access_key'], option['signature_version'], str(timestamp))) 86 | signature = sign(string_to_sign, option['access_secret']) 87 | 88 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 89 | requrl = "https://"+option['host'] + uri 90 | r = requests.get(requrl, headers=headers, verify=True) 91 | if r.status_code == 200: 92 | f = open(path, 'wb') 93 | f.write(r.content) 94 | f.close() 95 | 96 | def rebuild_offline_with_files(name, file_list): 97 | http_method = "PUT" 98 | timestamp = str(time.time()) 99 | uri = '/v1/offlinedbs/'+name 100 | 101 | string_to_sign = '\n'.join((http_method, uri, option['access_key'], option['signature_version'], timestamp)) 102 | 103 | signature = sign(string_to_sign, option['access_secret']) 104 | 105 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 106 | 107 | requrl = "https://"+option['host'] + uri 108 | data = {'files':file_list} 109 | r = requests.put(requrl, headers=headers, json=data, verify=True) 110 | r.encoding = "utf-8" 111 | print r.text 112 | 113 | if __name__ == "__main__": 114 | create_offline('test_api_offline_project', [{"name":"offline-bucket", "id":333}], 1, "eu-west-1") 115 | #rebuild_offline('test_api_offline_project') 116 | #rebuild_offline('test_api_offline_project', [{"name":"offline-bucket", "id":333}]) 117 | #delete_offline('test_api_offline_project') 118 | #get_offline("test_api_offline_project", "./acrcloud_local_db.zip") 119 | #rebuild_offline_with_files("test_api_offline_project", ["c738810677f746de3d3800f7f95b9f64"]) 120 | -------------------------------------------------------------------------------- /RESTful service/project.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import base64 4 | import hmac 5 | import hashlib 6 | import time 7 | import requests 8 | import json 9 | 10 | option = { 11 | 'host': 'api.acrcloud.com', 12 | 'signature_version': '1', 13 | 'access_key': '', 14 | 'access_secret': '', 15 | }; 16 | 17 | 18 | def sign(string_to_sign, access_secret): 19 | return base64.b64encode( 20 | hmac.new(str(access_secret), str(string_to_sign), digestmod=hashlib.sha1) 21 | .digest()) 22 | 23 | def create_project(name, region, type, buckets, audio_type, external_id): 24 | http_method = "POST" 25 | timestamp = str(time.time()) 26 | uri = '/v1/projects' 27 | 28 | string_to_sign = '\n'.join((http_method, uri, option['access_key'], option['signature_version'], timestamp)) 29 | 30 | signature = sign(string_to_sign, option['access_secret']) 31 | 32 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 33 | 34 | data = {'name':name, 'region':region, 'type':type, 'buckets':json.dumps(buckets), 'audio_type':audio_type, 'external_id':external_id} 35 | 36 | requrl = "https://"+option['host'] + uri 37 | r = requests.post(requrl, data=data, headers=headers, verify=True) 38 | r.encoding = "utf-8" 39 | print r.text 40 | 41 | 42 | def update_project(name, buckets): 43 | http_method = "PUT" 44 | timestamp = str(time.time()) 45 | uri = '/v1/projects/'+name 46 | 47 | string_to_sign = '\n'.join((http_method, uri, option['access_key'], option['signature_version'], timestamp)) 48 | 49 | signature = sign(string_to_sign, option['access_secret']) 50 | 51 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 52 | 53 | data = {'buckets':json.dumps(buckets)} 54 | 55 | requrl = "https://"+option['host'] + uri 56 | r = requests.put(requrl, data=data, headers=headers, verify=True) 57 | r.encoding = "utf-8" 58 | print r.text 59 | 60 | def delete_project(name): 61 | http_method = "DELETE" 62 | timestamp = str(time.time()) 63 | uri = '/v1/projects'+"/"+name 64 | 65 | string_to_sign = '\n'.join((http_method, uri, option['access_key'], option['signature_version'], timestamp)) 66 | 67 | signature = sign(string_to_sign, option['access_secret']) 68 | 69 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 70 | 71 | data = {'name':name} 72 | 73 | requrl = "https://"+option['host'] + uri 74 | r = requests.delete(requrl, data=data, headers=headers, verify=True) 75 | r.encoding = "utf-8" 76 | print r.text 77 | 78 | def get_project(project_name): 79 | http_method = "GET" 80 | timestamp = str(time.time()) 81 | http_uri = "/v1/projects/"+project_name 82 | 83 | string_to_sign = '\n'.join((http_method, http_uri, option['access_key'], option['signature_version'], timestamp)) 84 | signature = sign(string_to_sign, option['access_secret']) 85 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 86 | 87 | requrl = "https://"+option['host'] + http_uri 88 | r = requests.get(requrl, headers=headers, verify=True) 89 | r.encoding = "utf-8" 90 | print r.text 91 | 92 | def list_projects(): 93 | http_method = "GET" 94 | timestamp = str(time.time()) 95 | http_uri = "/v1/projects" 96 | 97 | string_to_sign = '\n'.join((http_method, http_uri, option['access_key'], option['signature_version'], str(timestamp))) 98 | signature = sign(string_to_sign, option['access_secret']) 99 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 100 | 101 | requrl = "https://"+option['host'] + http_uri 102 | r = requests.get(requrl, headers=headers, verify=True) 103 | r.encoding = "utf-8" 104 | print r.text 105 | 106 | #return {"id":0, "name":"", "access_key":"", "access_secret":"", "access_secret_old":""} 107 | def update_secret(project_name): 108 | http_method = "PUT" 109 | timestamp = str(time.time()) 110 | http_uri = "/v1/projects/"+str(project_name)+"/update_secret" 111 | 112 | string_to_sign = '\n'.join((http_method, http_uri, option['access_key'], option['signature_version'], timestamp)) 113 | signature = sign(string_to_sign, option['access_secret']) 114 | headers = {'access-key': option['access_key'], 'signature-version': option['signature_version'], 'signature': signature, 'timestamp':timestamp} 115 | 116 | requrl = "https://"+option['host'] + http_uri 117 | 118 | r = requests.put(requrl, headers=headers, verify=True) 119 | r.encoding = "utf-8" 120 | print r.text 121 | 122 | if __name__ == "__main__": 123 | create_project('test_api_project', 'us-west-2', 'AVR', [{"name":"ACRCloud Music"}, {"name":"usbucket"}], 1, "") 124 | #get_project('test_api_project') 125 | #update_project('test_api_project5', [{"name":"ACRCloud Music"}, {"name":"us_bucket", "id":1159}]) 126 | #delete_project('test_api_project') 127 | #list_projects() 128 | -------------------------------------------------------------------------------- /RESTful service/upload_audio.js: -------------------------------------------------------------------------------- 1 | var url = require('url'); 2 | var path = require('path'); 3 | var fs = require('fs'); 4 | var crypto = require('crypto'); 5 | //npm install request 6 | var request = require('request'); 7 | 8 | var defaultOptions = { 9 | host: 'api.acrcloud.com', 10 | endpoint: '/v1/audios', 11 | signature_version: '1', 12 | secure: true, 13 | access_key: 'your account access key', 14 | access_secret: 'your account access secret' 15 | }; 16 | 17 | function buildStringToSign(method, uri, accessKey, signatureVersion, timestamp) { 18 | return [method, uri, accessKey, signatureVersion, timestamp].join('\n'); 19 | } 20 | 21 | function sign(signString, accessSecret) { 22 | return crypto.createHmac('sha1', accessSecret) 23 | .update(new Buffer(signString, 'utf-8')) 24 | .digest().toString('base64'); 25 | } 26 | 27 | /** 28 | * Identifies a sample of bytes 29 | */ 30 | function upload(file_path, bucket, title, audio_id, data_type="fingerprint", custom_fields=None, cb) { 31 | var current_data = new Date(); 32 | var timestamp = current_data.getTime()/1000; 33 | 34 | var stringToSign = buildStringToSign('POST', 35 | defaultOptions.endpoint, 36 | defaultOptions.access_key, 37 | defaultOptions.signature_version, 38 | timestamp); 39 | 40 | var signature = sign(stringToSign, defaultOptions.access_secret); 41 | 42 | var headers = { 43 | 'access-key': defaultOptions.access_key, 44 | 'signature-version': defaultOptions.signature_version, 45 | 'signature': signature, 46 | 'timestamp':timestamp 47 | }; 48 | var formData = { 49 | 'audio_file': { 50 | 'value': fs.createReadStream(file_path), 51 | 'options': { 52 | 'filename': path.basename(file_path), 53 | 'contentType': 'fingerprint/lo' 54 | } 55 | }, 56 | 'data_type':data_type, 57 | 'bucket_name':bucket, 58 | 'title':title, 59 | 'audio_id':audio_id, 60 | } 61 | if (custom_fields) { 62 | keys = [] 63 | values = [] 64 | for (var k in custom_fields) { 65 | keys.push(k) 66 | values.push(custom_fields[k]) 67 | } 68 | formData['custom_key[]'] = keys 69 | formData['custom_value[]'] = values 70 | } 71 | 72 | request.post({ 73 | url: "https://"+defaultOptions.host + defaultOptions.endpoint, 74 | method: 'POST', 75 | headers: headers, 76 | formData: formData 77 | }, cb); 78 | } 79 | 80 | var title = "test" 81 | var audio_id = "test" 82 | var bucket_name = "eu-test" 83 | var data_type = "fingerprint" 84 | var file_path = '1040210008.mp3.wav.lo'; 85 | var custom_fields = {"key1":"value1"} 86 | 87 | upload(file_path, bucket_name, title, audio_id, data_type, custom_fields , function (err, httpResponse, body) { 88 | if (err) console.log(err); 89 | console.log(body); 90 | }); 91 | -------------------------------------------------------------------------------- /RESTful service/upload_audios.php: -------------------------------------------------------------------------------- 1 | "Account" (top right corner) -> "RESTful API Keys" -> "Create Key Pair". 11 | Be Careful, they are different with access_key and access_secret of your project. 12 | */ 13 | $account_access_key = 'xxxxxxxxx'; 14 | $account_access_secret = 'xxxxxxxxx'; 15 | 16 | $string_to_sign = $http_method . "\n" . 17 | $http_uri ."\n" . 18 | $account_access_key . "\n" . 19 | $signature_version . "\n" . 20 | $timestamp; 21 | $signature = hash_hmac("sha1",$string_to_sign,$account_access_secret,true); 22 | $signature = base64_encode($signature); 23 | // suported file formats: mp3,wav,wma,amr,ogg, ape,acc,spx,m4a,mp4,FLAC, etc 24 | $file = $argv[1]; 25 | if(class_exists('\CURLFile')) 26 | $cfile = new CURLFile($file, "audio/mp3", basename($argv[1])); 27 | else 28 | $cfile = '@' . $file; 29 | $postfields = array( 30 | 'audio_file' => $cfile, 31 | 'title' => 'test', 32 | 'audio_id' => '1234', 33 | 'bucket_name' => '', 34 | 'data_type'=>'audio', // if you upload fingerprint file please set 'data_type'=>'fingerprint' 35 | 'custom_key[0]' => 'key1', 36 | 'custom_value[0]' => 'value1', 37 | 'custom_key[1]' => 'key2', 38 | 'custom_value[1]' => 'value2', 39 | ); 40 | $headerArray = array(); 41 | $headers = array( 42 | 'access-key' => $account_access_key, 43 | 'timestamp' => $timestamp, 44 | 'signature-version' => '1', 45 | 'signature' => $signature 46 | ); 47 | foreach( $headers as $n => $v ) { 48 | $headerArr[] = $n .':' . $v; 49 | } 50 | $ch = curl_init(); 51 | curl_setopt($ch, CURLOPT_URL, $request_url); 52 | curl_setopt($ch, CURLOPT_POST, true); 53 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 54 | curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); 55 | curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr); 56 | $response = curl_exec($ch); 57 | var_dump($response); 58 | curl_close($ch); 59 | ?> 60 | -------------------------------------------------------------------------------- /identify protocol 1 (recommended)/IdentifyProtocolV1.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Collections; 6 | using System.Net; 7 | using System.Web; 8 | using System.IO; 9 | using System.Security.Cryptography; 10 | using System.Diagnostics; 11 | 12 | namespace ACRCloudWebAPITest 13 | { 14 | class IdentifyProtocolV1 15 | { 16 | public static string postHttp(string url, IDictionary postParams, int timeout) 17 | { 18 | string result = ""; 19 | 20 | string BOUNDARYSTR = "acrcloud***copyright***2015***" + DateTime.Now.Ticks.ToString("x"); 21 | string BOUNDARY = "--" + BOUNDARYSTR + "\r\n"; 22 | var ENDBOUNDARY = Encoding.ASCII.GetBytes("--" + BOUNDARYSTR + "--\r\n\r\n"); 23 | 24 | var stringKeyHeader = BOUNDARY + 25 | "Content-Disposition: form-data; name=\"{0}\"" + 26 | "\r\n\r\n{1}\r\n"; 27 | var filePartHeader = BOUNDARY + 28 | "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" + 29 | "Content-Type: application/octet-stream\r\n\r\n"; 30 | 31 | var memStream = new MemoryStream(); 32 | foreach (var item in postParams) 33 | { 34 | if (item.Value is string) 35 | { 36 | string tmpStr = string.Format(stringKeyHeader, item.Key, item.Value); 37 | byte[] tmpBytes = Encoding.UTF8.GetBytes(tmpStr); 38 | memStream.Write(tmpBytes, 0, tmpBytes.Length); 39 | } 40 | else if (item.Value is byte[]) 41 | { 42 | var header = string.Format(filePartHeader, "sample", "sample"); 43 | var headerbytes = Encoding.UTF8.GetBytes(header); 44 | memStream.Write(headerbytes, 0, headerbytes.Length); 45 | byte[] sample = (byte[])item.Value; 46 | memStream.Write(sample, 0, sample.Length); 47 | memStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, 2); 48 | } 49 | } 50 | memStream.Write(ENDBOUNDARY, 0, ENDBOUNDARY.Length); 51 | 52 | HttpWebRequest request = null; 53 | HttpWebResponse response = null; 54 | Stream writer = null; 55 | StreamReader myReader = null; 56 | try 57 | { 58 | request = (HttpWebRequest)WebRequest.Create(url); 59 | request.Timeout = timeout; 60 | request.Method = "POST"; 61 | request.ContentType = "multipart/form-data; boundary=" + BOUNDARYSTR; 62 | 63 | memStream.Position = 0; 64 | byte[] tempBuffer = new byte[memStream.Length]; 65 | memStream.Read(tempBuffer, 0, tempBuffer.Length); 66 | 67 | writer = request.GetRequestStream(); 68 | writer.Write(tempBuffer, 0, tempBuffer.Length); 69 | writer.Close(); 70 | writer = null; 71 | 72 | response = (HttpWebResponse)request.GetResponse(); 73 | myReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); 74 | result = myReader.ReadToEnd(); 75 | } 76 | catch (WebException e) 77 | { 78 | Debug.WriteLine("timeout:\n" + e.ToString()); 79 | } 80 | catch (Exception e) 81 | { 82 | Debug.WriteLine("other excption:" + e.ToString()); 83 | } 84 | finally 85 | { 86 | if (memStream != null) 87 | { 88 | memStream.Close(); 89 | memStream = null; 90 | } 91 | if (writer != null) 92 | { 93 | writer.Close(); 94 | writer = null; 95 | } 96 | if (myReader != null) 97 | { 98 | myReader.Close(); 99 | myReader = null; 100 | } 101 | if (request != null) 102 | { 103 | request.Abort(); 104 | request = null; 105 | } 106 | if (response != null) 107 | { 108 | response.Close(); 109 | response = null; 110 | } 111 | } 112 | 113 | return result; 114 | } 115 | 116 | public static string encryptByHMACSHA1(string input, string key) 117 | { 118 | HMACSHA1 hmac = new HMACSHA1(System.Text.Encoding.UTF8.GetBytes(key)); 119 | byte[] stringBytes = Encoding.UTF8.GetBytes(input); 120 | byte[] hashedValue = hmac.ComputeHash(stringBytes); 121 | return encodeToBase64(hashedValue); 122 | } 123 | 124 | public static string encodeToBase64(byte[] input) 125 | { 126 | string res = Convert.ToBase64String(input, 0, input.Length); 127 | return res; 128 | } 129 | 130 | public static string recognize(string host, string accessKey, string secretKey, byte[] queryData, string queryType, int timeout = 8000) 131 | { 132 | string method = "POST"; 133 | string httpURL = "/v1/identify"; 134 | string dataType = queryType; 135 | string sigVersion = "1"; 136 | string timestamp = ((int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds).ToString(); 137 | 138 | string reqURL = "http://" + host + httpURL; 139 | 140 | string sigStr = method + "\n" + httpURL + "\n" + accessKey + "\n" + dataType + "\n" + sigVersion + "\n" + timestamp; 141 | string signature = encryptByHMACSHA1(sigStr, secretKey); 142 | 143 | var dict = new Dictionary(); 144 | dict.Add("access_key", accessKey); 145 | dict.Add("sample_bytes", queryData.Length.ToString()); 146 | dict.Add("sample", queryData); 147 | dict.Add("timestamp", timestamp); 148 | dict.Add("signature", signature); 149 | dict.Add("data_type", queryType); 150 | dict.Add("signature_version", sigVersion); 151 | 152 | string res = postHttp(reqURL, dict, timeout); 153 | 154 | return res; 155 | } 156 | } 157 | class Program 158 | { 159 | static void Main(string[] args) 160 | { 161 | using (FileStream fs = new FileStream(@"E:\sample.wav", FileMode.Open)) 162 | { 163 | using (BinaryReader reader = new BinaryReader(fs)) 164 | { 165 | byte[] datas = reader.ReadBytes((int)fs.Length); 166 | // Replace "###...###" below with your project's host, access_key and access_secret. 167 | string result = IdentifyProtocolV1.recognize("##YOUR_HOST###", "###YOUR_ACCESS_KEY###", "###YOUR_ACCESS_SECRET###", datas, "audio"); 168 | Console.WriteLine(result); 169 | } 170 | } 171 | 172 | Console.ReadLine(); 173 | } 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /identify protocol 1 (recommended)/IdentifyProtocolV1.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedOutputStream; 2 | import java.io.BufferedReader; 3 | import java.io.ByteArrayOutputStream; 4 | import java.io.File; 5 | import java.io.FileInputStream; 6 | import java.io.IOException; 7 | import java.io.InputStreamReader; 8 | import java.net.HttpURLConnection; 9 | import java.net.URL; 10 | import java.util.Calendar; 11 | import java.util.HashMap; 12 | import java.util.Map; 13 | import javax.crypto.Mac; 14 | import javax.crypto.spec.SecretKeySpec; 15 | 16 | // import commons-codec-.jar, download from http://commons.apache.org/proper/commons-codec/download_codec.cgi 17 | import org.apache.commons.codec.binary.Base64; 18 | 19 | public class IdentifyProtocolV1 { 20 | 21 | private String encodeBase64(byte[] bstr) { 22 | Base64 base64 = new Base64(); 23 | return new String(base64.encode(bstr)); 24 | } 25 | 26 | private String encryptByHMACSHA1(byte[] data, byte[] key) { 27 | try { 28 | SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA1"); 29 | Mac mac = Mac.getInstance("HmacSHA1"); 30 | mac.init(signingKey); 31 | byte[] rawHmac = mac.doFinal(data); 32 | return encodeBase64(rawHmac); 33 | } catch (Exception e) { 34 | e.printStackTrace(); 35 | } 36 | return ""; 37 | } 38 | 39 | private String getUTCTimeSeconds() { 40 | Calendar cal = Calendar.getInstance(); 41 | int zoneOffset = cal.get(Calendar.ZONE_OFFSET); 42 | int dstOffset = cal.get(Calendar.DST_OFFSET); 43 | cal.add(Calendar.MILLISECOND, -(zoneOffset + dstOffset)); 44 | return cal.getTimeInMillis()/1000 + ""; 45 | } 46 | 47 | private String postHttp(String posturl, Map params, int timeOut) { 48 | String res = ""; 49 | String BOUNDARYSTR = "*****2015.03.30.acrcloud.rec.copyright." + System.currentTimeMillis() + "*****"; 50 | String BOUNDARY = "--" + BOUNDARYSTR + "\r\n"; 51 | String ENDBOUNDARY = "--" + BOUNDARYSTR + "--\r\n\r\n"; 52 | 53 | String stringKeyHeader = BOUNDARY + 54 | "Content-Disposition: form-data; name=\"%s\"" + 55 | "\r\n\r\n%s\r\n"; 56 | String filePartHeader = BOUNDARY + 57 | "Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\n" + 58 | "Content-Type: application/octet-stream\r\n\r\n"; 59 | 60 | URL url = null; 61 | HttpURLConnection conn = null; 62 | BufferedOutputStream out = null; 63 | BufferedReader reader = null; 64 | ByteArrayOutputStream postBufferStream = new ByteArrayOutputStream(); 65 | try { 66 | for (String key : params.keySet()) { 67 | Object value = params.get(key); 68 | if (value instanceof String || value instanceof Integer) { 69 | postBufferStream.write(String.format(stringKeyHeader, key, (String)value).getBytes()); 70 | } else if (value instanceof byte[]) { 71 | postBufferStream.write(String.format(filePartHeader, key, key).getBytes()); 72 | postBufferStream.write((byte[]) value); 73 | postBufferStream.write("\r\n".getBytes()); 74 | } 75 | } 76 | postBufferStream.write(ENDBOUNDARY.getBytes()); 77 | 78 | url = new URL(posturl); 79 | conn = (HttpURLConnection) url.openConnection(); 80 | conn.setConnectTimeout(timeOut); 81 | conn.setReadTimeout(timeOut); 82 | conn.setRequestMethod("POST"); 83 | conn.setDoOutput(true); 84 | conn.setDoInput(true); 85 | conn.setRequestProperty("Accept-Charset", "utf-8"); 86 | conn.setRequestProperty("Content-type", "multipart/form-data;boundary=" + BOUNDARYSTR); 87 | 88 | conn.connect(); 89 | out = new BufferedOutputStream(conn.getOutputStream()); 90 | out.write(postBufferStream.toByteArray()); 91 | out.flush(); 92 | int response = conn.getResponseCode(); 93 | if (response == HttpURLConnection.HTTP_OK) { 94 | reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); 95 | String tmpRes = ""; 96 | while ((tmpRes = reader.readLine()) != null) { 97 | if (tmpRes.length() > 0) 98 | res = res + tmpRes; 99 | } 100 | } 101 | } catch (Exception e) { 102 | e.printStackTrace(); 103 | } finally { 104 | try { 105 | if (postBufferStream != null) { 106 | postBufferStream.close(); 107 | postBufferStream = null; 108 | } 109 | if (out != null) { 110 | out.close(); 111 | out = null; 112 | } 113 | if (reader != null) { 114 | reader.close(); 115 | reader = null; 116 | } 117 | if (conn != null) { 118 | conn.disconnect(); 119 | conn = null; 120 | } 121 | } catch (IOException e) { 122 | e.printStackTrace(); 123 | } 124 | } 125 | return res; 126 | } 127 | 128 | public String recognize(String host, String accessKey, String secretKey, byte[] queryData, String queryType, int timeout) 129 | { 130 | String method = "POST"; 131 | String httpURL = "/v1/identify"; 132 | String dataType = queryType; 133 | String sigVersion = "1"; 134 | String timestamp = getUTCTimeSeconds(); 135 | 136 | String reqURL = "http://" + host + httpURL; 137 | 138 | String sigStr = method + "\n" + httpURL + "\n" + accessKey + "\n" + dataType + "\n" + sigVersion + "\n" + timestamp; 139 | String signature = encryptByHMACSHA1(sigStr.getBytes(), secretKey.getBytes()); 140 | 141 | Map postParams = new HashMap(); 142 | postParams.put("access_key", accessKey); 143 | postParams.put("sample_bytes", queryData.length + ""); 144 | postParams.put("sample", queryData); 145 | postParams.put("timestamp", timestamp); 146 | postParams.put("signature", signature); 147 | postParams.put("data_type", queryType); 148 | postParams.put("signature_version", sigVersion); 149 | 150 | String res = postHttp(reqURL, postParams, timeout); 151 | 152 | return res; 153 | } 154 | 155 | public static void main(String[] args) { 156 | File file = new File("E://sample.wav"); 157 | byte[] buffer = new byte[1024 * 1024]; 158 | if (!file.exists()) { 159 | return; 160 | } 161 | FileInputStream fin = null; 162 | int bufferLen = 0; 163 | try { 164 | fin = new FileInputStream(file); 165 | bufferLen = fin.read(buffer, 0, buffer.length); 166 | } catch (Exception e) { 167 | e.printStackTrace(); 168 | } finally { 169 | try { 170 | if (fin != null) { 171 | fin.close(); 172 | } 173 | } catch (IOException e) { 174 | e.printStackTrace(); 175 | } 176 | } 177 | System.out.println("bufferLen=" + bufferLen); 178 | 179 | if (bufferLen <= 0) 180 | return; 181 | 182 | byte[] postDatas = new byte[bufferLen]; 183 | System.arraycopy(buffer, 0, postDatas, 0, bufferLen); 184 | IdentifyProtocolV1 a = new IdentifyProtocolV1(); 185 | 186 | // Replace "###...###" below with your project's host, access_key and access_secret. 187 | // recognize(String host, String accessKey, String secretKey, byte[] queryData, String queryType, int timeout) 188 | String result = a.recognize("###YOUR_HOST###", "###YOUR_KEY###", "###YOUR_SECRET###", postDatas, "audio", 10000); 189 | System.out.println(result); 190 | } 191 | } 192 | -------------------------------------------------------------------------------- /identify protocol 1 (recommended)/IdentifyProtocolV1.js: -------------------------------------------------------------------------------- 1 | var url = require('url'); 2 | var fs = require('fs'); 3 | var crypto = require('crypto'); 4 | //npm install request 5 | var request = require('request'); 6 | 7 | // Replace "###...###" below with your project's host, access_key and access_secret. 8 | var defaultOptions = { 9 | host: '###YOUR_HOST###', 10 | endpoint: '/v1/identify', 11 | signature_version: '1', 12 | data_type:'audio', 13 | secure: true, 14 | access_key: '###YOUR_ACCESS_KEY###', 15 | access_secret: '###YOUR_ACCESS_SECRET###' 16 | }; 17 | 18 | function buildStringToSign(method, uri, accessKey, dataType, signatureVersion, timestamp) { 19 | return [method, uri, accessKey, dataType, signatureVersion, timestamp].join('\n'); 20 | } 21 | 22 | function sign(signString, accessSecret) { 23 | return crypto.createHmac('sha1', accessSecret) 24 | .update(Buffer.from(signString, 'utf-8')) 25 | .digest().toString('base64'); 26 | } 27 | 28 | /** 29 | * Identifies a sample of bytes 30 | */ 31 | function identify(data, options, cb) { 32 | 33 | var current_data = new Date(); 34 | var timestamp = current_data.getTime()/1000; 35 | 36 | var stringToSign = buildStringToSign('POST', 37 | options.endpoint, 38 | options.access_key, 39 | options.data_type, 40 | options.signature_version, 41 | timestamp); 42 | 43 | var signature = sign(stringToSign, options.access_secret); 44 | 45 | var formData = { 46 | sample: data, 47 | access_key:options.access_key, 48 | data_type:options.data_type, 49 | signature_version:options.signature_version, 50 | signature:signature, 51 | sample_bytes:data.length, 52 | timestamp:timestamp, 53 | } 54 | request.post({ 55 | url: "http://"+options.host + options.endpoint, 56 | method: 'POST', 57 | formData: formData 58 | }, cb); 59 | } 60 | 61 | function identify_v2(data, options, cb) { 62 | //npm install form-data 63 | var FormData = require('form-data'); 64 | //npm install node-fetch 65 | var fetch = require('node-fetch'); 66 | 67 | var current_data = new Date(); 68 | var timestamp = current_data.getTime()/1000; 69 | 70 | var stringToSign = buildStringToSign('POST', 71 | options.endpoint, 72 | options.access_key, 73 | options.data_type, 74 | options.signature_version, 75 | timestamp); 76 | 77 | var signature = sign(stringToSign, options.access_secret); 78 | 79 | var form = new FormData(); 80 | form.append('sample', data); 81 | form.append('sample_bytes', data.length); 82 | form.append('access_key', options.access_key); 83 | form.append('data_type', options.data_type); 84 | form.append('signature_version', options.signature_version); 85 | form.append('signature', signature); 86 | form.append('timestamp', timestamp); 87 | 88 | fetch("http://"+options.host + options.endpoint, 89 | {method: 'POST', body: form }) 90 | .then((res) => {return res.text()}) 91 | .then((res) => {cb(res, null)}) 92 | .catch((err) => {cb(null, err)}); 93 | } 94 | 95 | var bitmap = fs.readFileSync('sample.wav'); 96 | 97 | identify(Buffer.from(bitmap), defaultOptions, function (err, httpResponse, body) { 98 | if (err) console.log(err); 99 | console.log(body); 100 | }); 101 | 102 | //identify_v2(Buffer.from(bitmap), defaultOptions, function (res, err) { 103 | // if (!err) { 104 | // console.log(res); 105 | // } else { 106 | // console.log(err); 107 | // } 108 | //}); 109 | -------------------------------------------------------------------------------- /identify protocol 1 (recommended)/IdentifyProtocolV1.php: -------------------------------------------------------------------------------- 1 | $content, 35 | "sample_bytes"=>$filesize, 36 | "access_key"=>$access_key, 37 | "data_type"=>$data_type, 38 | "signature"=>$signature, 39 | "signature_version"=>$signature_version, 40 | "timestamp"=>$timestamp); 41 | 42 | $ch = curl_init(); 43 | curl_setopt($ch, CURLOPT_URL, $requrl); 44 | curl_setopt($ch, CURLOPT_POST, true); 45 | curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); 46 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 47 | 48 | $result = curl_exec($ch); 49 | echo $result; 50 | //$response = curl_exec($ch); 51 | //if ($response == true) { 52 | // $info = curl_getinfo($ch); 53 | //} else { 54 | // $errmsg = curl_error($ch); 55 | // print $errmsg; 56 | //} 57 | curl_close($ch); 58 | ?> 59 | -------------------------------------------------------------------------------- /identify protocol 1 (recommended)/IdentifyProtocolV1.rb: -------------------------------------------------------------------------------- 1 | require 'openssl' 2 | require 'base64' 3 | require 'net/http/post/multipart' 4 | 5 | # Replace "###...###" below with your project's host, access_key and access_secret. 6 | requrl = "http://###YOUR_HOST###/v1/identify" 7 | access_key = "###YOUR_ACCESS_KEY###" 8 | access_secret = "###YOUR_ACCESS_SECRET###" 9 | 10 | http_method = "POST" 11 | http_uri = "/v1/identify" 12 | data_type = "audio" 13 | signature_version = "1" 14 | timestamp = Time.now.utc().to_i.to_s 15 | 16 | string_to_sign = http_method+"\n"+http_uri+"\n"+access_key+"\n"+data_type+"\n"+signature_version+"\n"+timestamp 17 | 18 | digest = OpenSSL::Digest.new('sha1') 19 | signature = Base64.encode64(OpenSSL::HMAC.digest(digest, access_secret, string_to_sign)) 20 | 21 | file_name = ARGV[0] 22 | sample_bytes = File.size(file_name) 23 | 24 | url = URI.parse(requrl) 25 | File.open(file_name) do |file| 26 | req = Net::HTTP::Post::Multipart.new url.path, 27 | "sample" => UploadIO.new(file, "audio/mp3", file_name), 28 | "access_key" =>access_key, 29 | "data_type"=> data_type, 30 | "signature_version"=> signature_version, 31 | "signature"=>signature, 32 | "sample_bytes"=>sample_bytes, 33 | "timestamp" => timestamp 34 | res = Net::HTTP.start(url.host, url.port) do |http| 35 | http.request(req) 36 | end 37 | puts(res.body) 38 | end 39 | -------------------------------------------------------------------------------- /identify protocol 1 (recommended)/IdentifyProtocolV1_1.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This is a demo program which implements ACRCloud Identify Protocol V1 with the third party library "requests". 3 | We recomment you implement your own app with "requests" too. 4 | You can install this python library by: 5 | 1) sudo easy_install requests 6 | 2) sudo pip install requests 7 | ''' 8 | 9 | import sys 10 | import os 11 | import base64 12 | import hmac 13 | import hashlib 14 | import time 15 | import requests 16 | 17 | ''' 18 | Replace "###...###" below with your project's host, access_key and access_secret. 19 | ''' 20 | access_key = "###YOUR_ACCESS_KEY###" 21 | access_secret = "###YOUR_ACCESS_SECRET###" 22 | requrl = "http://###YOUR_HOST###/v1/identify" 23 | 24 | 25 | http_method = "POST" 26 | http_uri = "/v1/identify" 27 | #default is "fingerprint", it's for recognizing fingerprint, if you want to identify audio, please change data_type="audio" 28 | data_type = "fingerprint" 29 | signature_version = "1" 30 | timestamp = time.time() 31 | 32 | string_to_sign = http_method+"\n"+http_uri+"\n"+access_key+"\n"+data_type+"\n"+signature_version+"\n"+str(timestamp) 33 | 34 | sign = base64.b64encode(hmac.new(access_secret, string_to_sign, digestmod=hashlib.sha1).digest()) 35 | 36 | # suported file formats: mp3,wav,wma,amr,ogg, ape,acc,spx,m4a,mp4,FLAC, etc 37 | # File size: < 1M , You'de better cut large file to small file, within 15 seconds data size is better 38 | f = open(sys.argv[1], "rb") 39 | sample_bytes = os.path.getsize(sys.argv[1]) 40 | 41 | files = {'sample':f} 42 | data = {'access_key':access_key, 43 | 'sample_bytes':sample_bytes, 44 | 'timestamp':str(timestamp), 45 | 'signature':sign, 46 | 'data_type':data_type, 47 | "signature_version":signature_version} 48 | 49 | r = requests.post(requrl, files=files, data=data) 50 | r.encoding = "utf-8" 51 | print r.text 52 | -------------------------------------------------------------------------------- /identify protocol 1 (recommended)/IdentifyProtocolV1_2.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This is a demo program which implements ACRCloud Identify Protocol V1 all by native python libraries. 3 | ''' 4 | 5 | import sys 6 | import os 7 | import base64 8 | import hmac 9 | import hashlib 10 | import time 11 | import httplib 12 | import mimetools 13 | 14 | def post_multipart(host, selector, fields, files): 15 | content_type, body = encode_multipart_formdata(fields, files) 16 | h = httplib.HTTP(host) 17 | h.putrequest('POST', selector) 18 | h.putheader('content-type', content_type) 19 | h.putheader('content-length', str(len(body))) 20 | h.endheaders() 21 | h.send(body) 22 | errcode, errmsg, headers = h.getreply() 23 | return h.file.read() 24 | 25 | def encode_multipart_formdata(fields, files): 26 | boundary = mimetools.choose_boundary() 27 | CRLF = '\r\n' 28 | L = [] 29 | for (key, value) in fields.items(): 30 | L.append('--' + boundary) 31 | L.append('Content-Disposition: form-data; name="%s"' % key) 32 | L.append('') 33 | L.append(str(value)) 34 | for (key, value) in files.items(): 35 | L.append('--' + boundary) 36 | L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, key)) 37 | L.append('Content-Type: application/octet-stream') 38 | L.append('') 39 | L.append(value) 40 | L.append('--' + boundary + '--') 41 | L.append('') 42 | body = CRLF.join(L) 43 | content_type = 'multipart/form-data; boundary=%s' % boundary 44 | return content_type, body 45 | 46 | ''' 47 | Replace "###...###" below with your project's host, access_key and access_secret. 48 | ''' 49 | host = "###YOUR_HOST###" 50 | access_key = "###YOUR_ACCESS_KEY###" 51 | access_secret = "###YOUR_ACCESS_SECRET###" 52 | 53 | # suported file formats: mp3,wav,wma,amr,ogg, ape,acc,spx,m4a,mp4,FLAC, etc 54 | # File size: < 1M , You'de better cut large file to small file, within 15 seconds data size is better 55 | 56 | f = open(sys.argv[1], "rb") 57 | sample_bytes = os.path.getsize(sys.argv[1]) 58 | content = f.read() 59 | f.close() 60 | 61 | http_method = "POST" 62 | http_uri = "/v1/identify" 63 | data_type = "audio" 64 | signature_version = "1" 65 | timestamp = time.time() 66 | 67 | string_to_sign = http_method+"\n"+http_uri+"\n"+access_key+"\n"+data_type+"\n"+signature_version+"\n"+str(timestamp) 68 | sign = base64.b64encode(hmac.new(access_secret, string_to_sign, digestmod=hashlib.sha1).digest()) 69 | 70 | fields = {'access_key':access_key, 71 | 'sample_bytes':sample_bytes, 72 | 'timestamp':str(timestamp), 73 | 'signature':sign, 74 | 'data_type':data_type, 75 | "signature_version":signature_version} 76 | 77 | res = post_multipart(host, "/v1/identify", fields, {"sample":content}) 78 | print res 79 | -------------------------------------------------------------------------------- /identify protocol 1 (recommended)/reactnative_ios.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import {StyleSheet, Button, View, Text} from 'react-native'; 3 | import {Audio} from 'expo-av'; 4 | import {FileSystem, Permissions} from 'react-native-unimodules'; 5 | import hmacSHA1 from 'crypto-js/hmac-sha1'; 6 | import Base64 from 'crypto-js/enc-base64'; 7 | import {Buffer} from 'buffer'; 8 | 9 | export default class MusicRec_Test extends React.Component { 10 | constructor(props) { 11 | super(props); 12 | this.state = {response: ''}; 13 | } 14 | async _findSong() { 15 | // Audio.setAudioModeAsync() 16 | const {status} = await Audio.requestPermissionsAsync(); 17 | console.log('Current Status ' + status); 18 | const recording = new Audio.Recording(); 19 | try { 20 | await Audio.setAudioModeAsync({ 21 | playsInSilentModeIOS: true, 22 | allowsRecordingIOS: true, 23 | }); 24 | const recordOptions = { 25 | android: { 26 | extension: '.m4a', 27 | outputFormat: Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG_4, 28 | audioEncoder: Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AAC, 29 | sampleRate: 44100, 30 | numberOfChannels: 2, 31 | bitRate: 128000, 32 | }, 33 | ios: { 34 | extension: '.wav', 35 | audioQuality: Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_HIGH, 36 | sampleRate: 8000, 37 | numberOfChannels: 1, 38 | linearPCMBitDepth: 16, 39 | linearPCMIsBigEndian: false, 40 | linearPCMIsFloat: true, 41 | }, 42 | }; 43 | await recording.prepareToRecordAsync(recordOptions); 44 | await recording.startAsync(); 45 | console.log('Recording'); 46 | await timeout(8000); 47 | console.log('Done recording'); 48 | await recording.stopAndUnloadAsync(); 49 | let recordingFile = recording.getURI(); 50 | 51 | let result = await identify(recordingFile, defaultOptions); 52 | console.log(result); 53 | //return result; 54 | } catch (error) { 55 | console.log(error); 56 | console.log('Error in this!!!!'); 57 | } 58 | } 59 | render() { 60 | return ( 61 | 62 |