From 113f7abd240c0406faa83c07db4742c090febe96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E4=B9=BE=E6=B3=BD?= Date: Sun, 30 Jun 2019 21:11:33 +0800 Subject: [PATCH 01/21] support 2.8.0 --- Golem/.gitignore | 1 + Golem/golem.cpp | 22 +++++++++++++++++++--- Golem/golem.h | 1 + Golem/golem_run.py | 2 +- Golem/json_parser.cpp | 13 +++++++++++-- Golem/json_parser.h | 4 +++- Golem/main.cpp | 2 +- 7 files changed, 37 insertions(+), 8 deletions(-) create mode 100644 Golem/.gitignore diff --git a/Golem/.gitignore b/Golem/.gitignore new file mode 100644 index 00000000..722d5e71 --- /dev/null +++ b/Golem/.gitignore @@ -0,0 +1 @@ +.vscode diff --git a/Golem/golem.cpp b/Golem/golem.cpp index 72fa1397..b0ac6708 100644 --- a/Golem/golem.cpp +++ b/Golem/golem.cpp @@ -40,6 +40,7 @@ void golem::dump_settings() std::cout << " -- key : " << settings_.key << std::endl; std::cout << " -- channel name : " << settings_.channel_name << std::endl; std::cout << " -- uid : " << settings_.uid << std::endl; + std::cout << " -- account : " << settings_.account << std::endl; std::cout << " -- mode : " << (settings_.mode == MODE_BROADCAST ? "broadcast" : "communicat") << std::endl; std::cout << " -- role : " << (settings_.role == ROLE_BROADCASTER ? "broadcaster" : "audience") << std::endl; std::cout << " -- dual stream : " << (settings_.dual_stream == 1 ? "true" : "false") << std::endl; @@ -189,9 +190,18 @@ int golem::run() parameter.muteAllRemoteVideoStreams(settings_.mute.remote_video); // Join channel - if (rtc_engine->joinChannel(settings_.key.c_str(), settings_.channel_name.c_str(), NULL, settings_.uid) < 0) { - SAFE_LOG(ERROR) << "Failed to create the channel " << settings_.channel_name; - return -2; + if(settings_.account != "") { + std::cout << "Join with user account" << settings_.account << std::endl; + if (rtc_engine->joinChannelWithUserAccount(settings_.key.c_str(), settings_.channel_name.c_str(), settings_.account.c_str()) < 0) { + SAFE_LOG(ERROR) << "Failed to create the channel " << settings_.channel_name; + return -2; + } + } else { + std::cout << "Join with uid" << settings_.uid << std::endl; + if (rtc_engine->joinChannel(settings_.key.c_str(), settings_.channel_name.c_str(), NULL, settings_.uid) < 0) { + SAFE_LOG(ERROR) << "Failed to create the channel " << settings_.channel_name; + return -2; + } } return run_interactive(); @@ -262,6 +272,12 @@ void golem::onRtcStats(const rtc::RtcStats &stats) { } +void golem::onLocalUserRegistered(uid_t uid, const char* userAccount) +{ + LOG(INFO, "onLocalUserRegistered %d: %s", uid, userAccount); + std::cout << "onLocalUserRegistered " << uid << ": " << userAccount << std::endl; +} + void golem::onLogEvent(int level, const char *msg, int length) { (void)length; diff --git a/Golem/golem.h b/Golem/golem.h index ba5ec427..0ee7c43c 100644 --- a/Golem/golem.h +++ b/Golem/golem.h @@ -39,6 +39,7 @@ class golem : private rtc::IRtcEngineEventHandler, virtual void onUserJoined(uid_t uid, int elapsed); virtual void onUserOffline(uid_t uid, rtc::USER_OFFLINE_REASON_TYPE reason); virtual void onRtcStats(const rtc::RtcStats &stats); + virtual void onLocalUserRegistered(uid_t uid, const char* userAccount); // inherited from IRtcEngineEventHandlerEx virtual void onLogEvent(int level, const char *msg, int length); diff --git a/Golem/golem_run.py b/Golem/golem_run.py index 1d3890e3..b1a285a1 100644 --- a/Golem/golem_run.py +++ b/Golem/golem_run.py @@ -49,7 +49,7 @@ def runRobots(): print("\n############# ROBOT %d #############" %i) cmd = './Golem --global_settings %s --golem_settings %s &' % (global_settings_text, golem_settings_text) - + print("\n%s" %cmd) runCmd(cmd) time.sleep(interval) diff --git a/Golem/json_parser.cpp b/Golem/json_parser.cpp index 7445d477..dbc421d1 100644 --- a/Golem/json_parser.cpp +++ b/Golem/json_parser.cpp @@ -75,9 +75,18 @@ void json_parser::parse_golem_settings(std::string golem_settings) assert(item != nullptr); settings_.audio_file = std::string(item->valuestring); + item = cJSON_GetObjectItem(root, "uid"); - assert(item != nullptr); - settings_.uid = item->valueint; + cJSON *account_item = nullptr; + account_item = cJSON_GetObjectItem(root, "account"); + assert((item != nullptr) || (item != nullptr)); + if(item != nullptr) { + settings_.uid = item->valueint; + } + if(account_item != nullptr) { + settings_.account = account_item->valuestring; + } + mute_obj = cJSON_GetObjectItem(root, "mute"); assert(mute_obj != nullptr); { diff --git a/Golem/json_parser.h b/Golem/json_parser.h index 2d32348d..792a440b 100644 --- a/Golem/json_parser.h +++ b/Golem/json_parser.h @@ -36,6 +36,7 @@ class settings_t { key = other_settings.key; channel_name = other_settings.channel_name; + account = other_settings.account; uid = other_settings.uid; mode = other_settings.mode; role= other_settings.role; @@ -74,6 +75,7 @@ class settings_t mute_stst_t mute; std::string video_file; std::string audio_file; + std::string account; }; class json_parser @@ -90,4 +92,4 @@ class json_parser private: settings_t settings_; -}; \ No newline at end of file +}; diff --git a/Golem/main.cpp b/Golem/main.cpp index 7c77b766..bfc9a20a 100644 --- a/Golem/main.cpp +++ b/Golem/main.cpp @@ -31,7 +31,7 @@ int main(int argc, char *argv[]) { std::string(argv[4]).empty() ) { - std::cerr << "Illegal arguments\n"; + std::cerr << "Illegal arguments " << argc << "\n"; print_usage(); return -1; } From f184e7692e62fd93123e95867ae2383f1d4c2df4 Mon Sep 17 00:00:00 2001 From: Arvin Hsu Date: Fri, 17 Dec 2021 18:40:22 +0800 Subject: [PATCH 02/21] Only release rtc & chat service in token007 --- .../AgoraDynamicKey/cpp/src/AccessToken2.h | 131 ------------------ .../cpp/test/AccessToken2_test.cpp | 74 +--------- 2 files changed, 4 insertions(+), 201 deletions(-) diff --git a/DynamicKey/AgoraDynamicKey/cpp/src/AccessToken2.h b/DynamicKey/AgoraDynamicKey/cpp/src/AccessToken2.h index 2cfa7f69..1a4035c9 100644 --- a/DynamicKey/AgoraDynamicKey/cpp/src/AccessToken2.h +++ b/DynamicKey/AgoraDynamicKey/cpp/src/AccessToken2.h @@ -111,134 +111,6 @@ class ServiceRtc : public Service { ServiceRtc &operator=(ServiceRtc &&) = default; }; -class ServiceRtm : public Service { - public: - enum { - kServiceType = 2, - - kPrivilegeLogin = 1, - }; - - public: - ServiceRtm(const std::string &user_id = "") - : Service(kServiceType), user_id_(user_id) {} - - virtual std::string PackService() override { return Pack(this); } - - virtual void UnpackService(Unpacker *unpacker) override { *unpacker >> this; } - - virtual std::unique_ptr Clone() const override { - return std::unique_ptr(new ServiceRtm(*this)); - } - - friend agora::tools::Packer &operator<<(agora::tools::Packer &p, - const ServiceRtm *x) { - p << dynamic_cast(x) << x->user_id_; - return p; - } - - friend agora::tools::Unpacker &operator>>(agora::tools::Unpacker &p, - ServiceRtm *x) { - p >> dynamic_cast(x) >> x->user_id_; - return p; - } - - public: - std::string user_id_; - - protected: - ServiceRtm(const ServiceRtm &) = default; - ServiceRtm(ServiceRtm &&) = default; - ServiceRtm &operator=(const ServiceRtm &) = default; - ServiceRtm &operator=(ServiceRtm &&) = default; -}; - -class ServiceStreaming : public Service { - public: - enum { - kServiceType = 3, - - kPrivilegePublishMixStream = 1, - kPrivilegePublishRawStream = 2, - }; - - public: - ServiceStreaming(const std::string &channel_name = "", uint32_t uid = 0) - : Service(kServiceType), channel_name_(channel_name) { - if (uid == 0) { - account_ = ""; - } else { - account_ = std::to_string(uid); - } - } - - ServiceStreaming(const std::string &channel_name, const std::string &account) - : Service(kServiceType), channel_name_(channel_name), account_(account) {} - - virtual std::string PackService() override { return Pack(this); } - - virtual void UnpackService(Unpacker *unpacker) override { *unpacker >> this; } - - virtual std::unique_ptr Clone() const override { - return std::unique_ptr(new ServiceStreaming(*this)); - } - - friend agora::tools::Packer &operator<<(agora::tools::Packer &p, - const ServiceStreaming *x) { - p << dynamic_cast(x) << x->channel_name_ << x->account_; - return p; - } - - friend agora::tools::Unpacker &operator>>(agora::tools::Unpacker &p, - ServiceStreaming *x) { - p >> dynamic_cast(x) >> x->channel_name_ >> x->account_; - return p; - } - - public: - std::string channel_name_; - std::string account_; - - protected: - ServiceStreaming(const ServiceStreaming &) = default; - ServiceStreaming(ServiceStreaming &&) = default; - ServiceStreaming &operator=(const ServiceStreaming &) = default; - ServiceStreaming &operator=(ServiceStreaming &&) = default; -}; - -class ServiceFpa : public Service { - public: - enum { - kServiceType = 4, - - kPrivilegeLogin = 1, - }; - - ServiceFpa() : Service(kServiceType) {} - - virtual std::string PackService() override { return Pack(this); } - virtual void UnpackService(Unpacker *unpacker) override { *unpacker >> this; } - - virtual std::unique_ptr Clone() const override { - return std::unique_ptr(new ServiceFpa(*this)); - } - - friend agora::tools::Packer &operator<<(agora::tools::Packer &p, - const ServiceFpa *x) { - return p << dynamic_cast(x); - } - friend agora::tools::Unpacker &operator>>(agora::tools::Unpacker &p, - ServiceFpa *x) { - return p >> dynamic_cast(x); - } - - protected: - ServiceFpa(const ServiceFpa &) = default; - ServiceFpa(ServiceFpa &&) = default; - ServiceFpa &operator=(const ServiceFpa &) = default; - ServiceFpa &operator=(ServiceFpa &&) = default; -}; - class ServiceChat : public Service { public: enum { @@ -282,9 +154,6 @@ struct ServiceCreator { }; static const std::map kServiceCreator = { {ServiceRtc::kServiceType, ServiceCreator::New}, - {ServiceRtm::kServiceType, ServiceCreator::New}, - {ServiceStreaming::kServiceType, ServiceCreator::New}, - {ServiceFpa::kServiceType, ServiceCreator::New}, {ServiceChat::kServiceType, ServiceCreator::New}, }; diff --git a/DynamicKey/AgoraDynamicKey/cpp/test/AccessToken2_test.cpp b/DynamicKey/AgoraDynamicKey/cpp/test/AccessToken2_test.cpp index 89f7b931..6cc59fa8 100644 --- a/DynamicKey/AgoraDynamicKey/cpp/test/AccessToken2_test.cpp +++ b/DynamicKey/AgoraDynamicKey/cpp/test/AccessToken2_test.cpp @@ -48,32 +48,6 @@ class AccessToken2_test : public testing::Test { EXPECT_EQ(l_rtc->account_, r_rtc->account_); } - void VerifyServiceRtm(Service *l, Service *r) { - VerifyService(l, r); - - auto l_rtc = dynamic_cast(l); - auto r_rtc = dynamic_cast(r); - - EXPECT_EQ(l_rtc->user_id_, r_rtc->user_id_); - } - - void VerifyServiceStreaming(Service *l, Service *r) { - VerifyService(l, r); - - auto l_rtc = dynamic_cast(l); - auto r_rtc = dynamic_cast(r); - - EXPECT_EQ(l_rtc->channel_name_, r_rtc->channel_name_); - EXPECT_EQ(l_rtc->account_, r_rtc->account_); - } - - void VerifyServiceFpa(Service *l, Service *r) { - VerifyService(l, r); - - (void)dynamic_cast(l); - (void)dynamic_cast(r); - } - void VerifyServiceChat(Service *l, Service *r) { VerifyService(l, r); @@ -109,10 +83,6 @@ class AccessToken2_test : public testing::Test { void (AccessToken2_test::*)(Service *, Service *); static const std::map kVerifyServices = { {ServiceRtc::kServiceType, &AccessToken2_test::VerifyServiceRtc}, - {ServiceRtm::kServiceType, &AccessToken2_test::VerifyServiceRtm}, - {ServiceStreaming::kServiceType, - &AccessToken2_test::VerifyServiceStreaming}, - {ServiceFpa::kServiceType, &AccessToken2_test::VerifyServiceFpa}, {ServiceChat::kServiceType, &AccessToken2_test::VerifyServiceChat}, }; @@ -181,23 +151,6 @@ class AccessToken2_test : public testing::Test { VerifyAccessToken2(expected, &key); } - void TestAccessToken2Rtm() { - AccessToken2 key(app_id_, app_certificate_, issue_ts_, expire_); - key.salt_ = 1; - - std::unique_ptr service(new ServiceRtm(account_)); - service->AddPrivilege(ServiceRtm::kPrivilegeLogin, expire_); - - key.AddService(std::move(service)); - - std::string expected = - "007eJxTYEhuZrAR/XT+XPihI+6t4t5F9RtUltw9em3Pwi2sr6P/lAspMFiaGzg7GpumpJo" - "ZJJuYmJmYJiUlplokGhmaGpgZJhkbu38RYIhgYmBgZABhJiBmBPO5GIwsLIyMTQyNzI0Bn" - "dAdKg=="; - - VerifyAccessToken2(expected, &key); - } - void TestAccessToken2ChatUser() { AccessToken2 key(app_id_, app_certificate_, issue_ts_, expire_); key.salt_ = 1; @@ -241,33 +194,17 @@ class AccessToken2_test : public testing::Test { rtc->AddPrivilege(ServiceRtc::kPrivilegePublishVideoStream, expire_); rtc->AddPrivilege(ServiceRtc::kPrivilegePublishDataStream, expire_); - std::unique_ptr rtm(new ServiceRtm(user_id_)); - rtm->AddPrivilege(ServiceRtm::kPrivilegeLogin, expire_); - - std::unique_ptr streaming( - new ServiceStreaming(channel_name_, uid_)); - streaming->AddPrivilege(ServiceStreaming::kPrivilegePublishMixStream, - expire_); - streaming->AddPrivilege(ServiceStreaming::kPrivilegePublishRawStream, - expire_); - - std::unique_ptr fpa(new ServiceFpa()); - fpa->AddPrivilege(ServiceFpa::kPrivilegeLogin, expire_); - std::unique_ptr chat(new ServiceChat(account_)); chat->AddPrivilege(ServiceChat::kPrivilegeUser, expire_); key.AddService(std::move(rtc)); - key.AddService(std::move(rtm)); - key.AddService(std::move(streaming)); - key.AddService(std::move(fpa)); key.AddService(std::move(chat)); std::string expected = - "007eJxTYLgzwyF4z+F775+LdK4+u313oKDtdBXruNf31QTrlydWfuRSYLA0N3B2NDZNSTU" - "zSDYxMTMxTUpKTLVINDI0NTAzTDI2dv8iwBDBxMDAyMDAwAokWYAYxGcCk8xgkgVMKjCYp" - "5gbGZuZpiZZWhibWJgaW5qnGqcap1mmmJgZJKWkJHIxGFlYGBmbGBqZGzMBzYGYxMlQklp" - "cEl9anFrEzMCEYjxpRrLAjWSFs5DlAYHiOdw="; + "007eJxTYLh59YaCUHZeRLXJsRSTDvfv2SV2uddsV+m05Vx5HaP59bMCg6W5gbOjsWlKqpl" + "BsomJmYlpUlJiqkWikaGpgZlhkrGx+xcBhggmBgZGBgYGJiDJAsQgPhOYZAaTLGBSgcE8x" + "dzI2Mw0NcnSwtjEwtTY0jzVONU4zTLFxMwgKSUlkYvByMLCyNjE0MjcmBVoDsQkZFEAlCc" + "pOg=="; VerifyAccessToken2(expected, &key); } @@ -293,9 +230,6 @@ TEST_F(AccessToken2_test, testAccessToken2WithIntUidZero) { TEST_F(AccessToken2_test, testAccessToken2WithStringUid) { TestAccessToken2WithStringUid(); } -TEST_F(AccessToken2_test, testAccessToken2Rtm) { - TestAccessToken2Rtm(); -} TEST_F(AccessToken2_test, testAccessToken2ChatUser) { TestAccessToken2ChatUser(); } From 7328617fd9c37f8284c3bc10ebc2542756952e22 Mon Sep 17 00:00:00 2001 From: Arvin Hsu Date: Tue, 21 Dec 2021 15:07:21 +0800 Subject: [PATCH 03/21] Remove useless token builder --- .../AgoraDynamicKey/cpp/src/FpaTokenBuilder.h | 47 ------------------- .../cpp/src/RtmTokenBuilder2.h | 47 ------------------- 2 files changed, 94 deletions(-) delete mode 100644 DynamicKey/AgoraDynamicKey/cpp/src/FpaTokenBuilder.h delete mode 100644 DynamicKey/AgoraDynamicKey/cpp/src/RtmTokenBuilder2.h diff --git a/DynamicKey/AgoraDynamicKey/cpp/src/FpaTokenBuilder.h b/DynamicKey/AgoraDynamicKey/cpp/src/FpaTokenBuilder.h deleted file mode 100644 index 27592a44..00000000 --- a/DynamicKey/AgoraDynamicKey/cpp/src/FpaTokenBuilder.h +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2014-2017 Agora.io, Inc. -// - -#pragma once // NOLINT(build/header_guard) - -#include - -#include -#include -#include -#include -#include - -#include "cpp/src/AccessToken2.h" - -namespace agora { -namespace tools { - -class FpaTokenBuilder { - public: - /** - Builds a FPA token. - - @param app_id The App ID issued to you by Agora. - @param app_certificate Certificate of the application that you registered in - the Agora Dashboard. - @return The new Token. Token is available for 24 hours after generation - */ - static std::string BuildToken( - const std::string& app_id, - const std::string& app_certificate); -}; - -inline std::string FpaTokenBuilder::BuildToken( - const std::string& app_id, const std::string& app_certificate) { - std::unique_ptr service(new ServiceFpa()); - service->AddPrivilege(ServiceFpa::kPrivilegeLogin, 0); - - AccessToken2 generator(app_id, app_certificate, 0, 24 * 3600); - generator.AddService(std::move(service)); - - return generator.Build(); -} - -} // namespace tools -} // namespace agora - diff --git a/DynamicKey/AgoraDynamicKey/cpp/src/RtmTokenBuilder2.h b/DynamicKey/AgoraDynamicKey/cpp/src/RtmTokenBuilder2.h deleted file mode 100644 index 27d9f188..00000000 --- a/DynamicKey/AgoraDynamicKey/cpp/src/RtmTokenBuilder2.h +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2014-2017 Agora.io, Inc. -// - -#pragma once // NOLINT(build/header_guard) - -#include -#include - -#include "cpp/src/AccessToken2.h" - -namespace agora { -namespace tools { - -class RtmTokenBuilder2 { - public: - /** - Builds an RTM token. - - @param app_id The App ID issued to you by Agora. - @param app_certificate Certificate of the application that you registered in - the Agora Dashboard. - @param user_id The user's account, max length is 64 Bytes. - @param expire represented by the number of seconds elapsed since now. If, for - example, you want to access the Agora Service within 10 minutes after the - token is generated, set expireTimestamp as 600(seconds). - @return The new Token. - */ - static std::string BuildToken(const std::string& app_id, - const std::string& app_certificate, - const std::string& user_id, - uint32_t expire = 0); -}; - -inline std::string RtmTokenBuilder2::BuildToken( - const std::string& app_id, const std::string& app_certificate, - const std::string& user_id, uint32_t expire) { - std::unique_ptr service(new ServiceRtm(user_id)); - service->AddPrivilege(ServiceRtm::kPrivilegeLogin, expire); - - AccessToken2 generator(app_id, app_certificate, 0, expire); - generator.AddService(std::move(service)); - - return generator.Build(); -} - -} // namespace tools -} // namespace agora From f04e21c1e2e0cfc00641b41a98207442ee978231 Mon Sep 17 00:00:00 2001 From: lixinhui Date: Tue, 21 Dec 2021 18:27:32 +0800 Subject: [PATCH 04/21] just support Rtc/Chat service --- .../go/sample/fpatokenbuilder/sample.go | 18 - .../go/sample/rtmtokenbuilder2/sample.go | 20 - .../go/src/accesstoken2/accesstoken.go | 567 ++++++++---------- .../go/src/accesstoken2/accesstoken_test.go | 75 +-- .../go/src/fpatokenbuilder/fpatokenbuilder.go | 22 - .../fpatokenbuilder/fpatokenbuilder_test.go | 27 - .../src/rtmtokenbuilder2/rtmtokenbuilder.go | 25 - .../rtmtokenbuilder2/rtmtokenbuilder_test.go | 28 - .../python3/sample/RtmTokenBuilder2Sample.py | 23 - .../sample/fpa_token_builder_sample.py | 20 - .../python3/src/AccessToken2.py | 66 +- .../python3/src/RtmTokenBuilder2.py | 29 - .../python3/src/fpa_token_builder.py | 24 - .../python3/test/AccessToken2Test.py | 19 +- .../python3/test/RtmTokenBuilder2Test.py | 36 -- .../python3/test/test_fpa_token_builder.py | 30 - 16 files changed, 245 insertions(+), 784 deletions(-) delete mode 100644 DynamicKey/AgoraDynamicKey/go/sample/fpatokenbuilder/sample.go delete mode 100644 DynamicKey/AgoraDynamicKey/go/sample/rtmtokenbuilder2/sample.go delete mode 100644 DynamicKey/AgoraDynamicKey/go/src/fpatokenbuilder/fpatokenbuilder.go delete mode 100644 DynamicKey/AgoraDynamicKey/go/src/fpatokenbuilder/fpatokenbuilder_test.go delete mode 100644 DynamicKey/AgoraDynamicKey/go/src/rtmtokenbuilder2/rtmtokenbuilder.go delete mode 100644 DynamicKey/AgoraDynamicKey/go/src/rtmtokenbuilder2/rtmtokenbuilder_test.go delete mode 100644 DynamicKey/AgoraDynamicKey/python3/sample/RtmTokenBuilder2Sample.py delete mode 100644 DynamicKey/AgoraDynamicKey/python3/sample/fpa_token_builder_sample.py delete mode 100755 DynamicKey/AgoraDynamicKey/python3/src/RtmTokenBuilder2.py delete mode 100755 DynamicKey/AgoraDynamicKey/python3/src/fpa_token_builder.py delete mode 100644 DynamicKey/AgoraDynamicKey/python3/test/RtmTokenBuilder2Test.py delete mode 100644 DynamicKey/AgoraDynamicKey/python3/test/test_fpa_token_builder.py diff --git a/DynamicKey/AgoraDynamicKey/go/sample/fpatokenbuilder/sample.go b/DynamicKey/AgoraDynamicKey/go/sample/fpatokenbuilder/sample.go deleted file mode 100644 index 836f7441..00000000 --- a/DynamicKey/AgoraDynamicKey/go/sample/fpatokenbuilder/sample.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "fmt" - "github.com/AgoraIO/Tools/DynamicKey/AgoraDynamicKey/go/src/fpatokenbuilder" -) - -func main() { - appID := "970CA35de60c44645bbae8a215061b33" - appCertificate := "5CFd2fd1755d40ecb72977518be15d3b" - - result, err := fpatokenbuilder.BuildToken(appID, appCertificate) - if err != nil { - fmt.Println(err) - } else { - fmt.Printf("Token with FPA service: %s\n", result) - } -} diff --git a/DynamicKey/AgoraDynamicKey/go/sample/rtmtokenbuilder2/sample.go b/DynamicKey/AgoraDynamicKey/go/sample/rtmtokenbuilder2/sample.go deleted file mode 100644 index 57be8bff..00000000 --- a/DynamicKey/AgoraDynamicKey/go/sample/rtmtokenbuilder2/sample.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "fmt" - rtmtokenbuilder "github.com/AgoraIO/Tools/DynamicKey/AgoraDynamicKey/go/src/rtmtokenbuilder2" -) - -func main() { - appID := "970CA35de60c44645bbae8a215061b33" - appCertificate := "5CFd2fd1755d40ecb72977518be15d3b" - userId := "test_user_id" - expirationInSeconds := uint32(3600) - - result, err := rtmtokenbuilder.BuildToken(appID, appCertificate, userId, expirationInSeconds) - if err != nil { - fmt.Println(err) - } else { - fmt.Printf("Rtm Token: %s\n", result) - } -} diff --git a/DynamicKey/AgoraDynamicKey/go/src/accesstoken2/accesstoken.go b/DynamicKey/AgoraDynamicKey/go/src/accesstoken2/accesstoken.go index 4a6c579a..d254c556 100644 --- a/DynamicKey/AgoraDynamicKey/go/src/accesstoken2/accesstoken.go +++ b/DynamicKey/AgoraDynamicKey/go/src/accesstoken2/accesstoken.go @@ -1,427 +1,328 @@ package accesstoken2 import ( - "bytes" - "crypto/hmac" - "crypto/sha256" - "encoding/hex" - "errors" - "fmt" - "io" - "time" + "bytes" + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "time" ) const ( - Version = "007" - VersionLength = 3 - - // Service type - ServiceTypeRtc = 1 - ServiceTypeRtm = 2 - ServiceTypeStreaming = 3 - ServiceTypeFpa = 4 - ServiceTypeChat = 5 - - // Rtc - PrivilegeJoinChannel = 1 - PrivilegePublishAudioStream = 2 - PrivilegePublishVideoStream = 3 - PrivilegePublishDataStream = 4 - - // Rtm - // Fpa - PrivilegeLogin = 1 - - // Streaming - PrivilegePublishMixStream = 1 - PrivilegePublishRawStream = 2 - - // Chat - PrivilegeChatUser = 1 - PrivilegeChatApp = 2 + Version = "007" + VersionLength = 3 + + // Service type + ServiceTypeRtc = 1 + ServiceTypeChat = 5 + + // Rtc + PrivilegeJoinChannel = 1 + PrivilegePublishAudioStream = 2 + PrivilegePublishVideoStream = 3 + PrivilegePublishDataStream = 4 + + // Chat + PrivilegeChatUser = 1 + PrivilegeChatApp = 2 ) type IService interface { - getServiceType() uint16 - Pack(io.Writer) error - UnPack(io.Reader) error + getServiceType() uint16 + Pack(io.Writer) error + UnPack(io.Reader) error } type Service struct { - Privileges map[uint16]uint32 - Type uint16 + Privileges map[uint16]uint32 + Type uint16 } func NewService(serviceType uint16) (service *Service) { - service = &Service{Privileges: make(map[uint16]uint32), Type: serviceType} - return + service = &Service{Privileges: make(map[uint16]uint32), Type: serviceType} + return } func (service *Service) AddPrivilege(privilege uint16, expire uint32) { - service.Privileges[privilege] = expire + service.Privileges[privilege] = expire } func (service *Service) getServiceType() uint16 { - return service.Type + return service.Type } func (service *Service) Pack(w io.Writer) (err error) { - err = service.packType(w) - if err != nil { - return - } - err = service.packPrivileges(w) - return + err = service.packType(w) + if err != nil { + return + } + err = service.packPrivileges(w) + return } func (service *Service) UnPack(r io.Reader) (err error) { - service.Privileges, err = unPackMapUint32(r) - return + service.Privileges, err = unPackMapUint32(r) + return } func (service *Service) packPrivileges(w io.Writer) error { - return packMapUint32(w, service.Privileges) + return packMapUint32(w, service.Privileges) } func (service *Service) packType(w io.Writer) error { - return packUint16(w, service.Type) + return packUint16(w, service.Type) } type ServiceRtc struct { - *Service - ChannelName string - Uid string + *Service + ChannelName string + Uid string } func NewServiceRtc(channelName string, uid string) (serviceRtc *ServiceRtc) { - serviceRtc = &ServiceRtc{ChannelName: channelName, Service: NewService(ServiceTypeRtc), Uid: uid} - return + serviceRtc = &ServiceRtc{ChannelName: channelName, Service: NewService(ServiceTypeRtc), Uid: uid} + return } func (serviceRtc *ServiceRtc) Pack(w io.Writer) (err error) { - err = serviceRtc.Service.Pack(w) - if err != nil { - return - } - err = packString(w, serviceRtc.ChannelName) - if err != nil { - return - } - err = packString(w, serviceRtc.Uid) - return + err = serviceRtc.Service.Pack(w) + if err != nil { + return + } + err = packString(w, serviceRtc.ChannelName) + if err != nil { + return + } + err = packString(w, serviceRtc.Uid) + return } func (serviceRtc *ServiceRtc) UnPack(r io.Reader) (err error) { - err = serviceRtc.Service.UnPack(r) - if err != nil { - return - } - serviceRtc.ChannelName, err = unPackString(r) - serviceRtc.Uid, err = unPackString(r) - return + err = serviceRtc.Service.UnPack(r) + if err != nil { + return + } + serviceRtc.ChannelName, err = unPackString(r) + serviceRtc.Uid, err = unPackString(r) + return } type ServiceRtm struct { - *Service - UserId string -} - -func NewServiceRtm(userId string) (serviceRtm *ServiceRtm) { - serviceRtm = &ServiceRtm{UserId: userId, Service: NewService(ServiceTypeRtm)} - return -} - -func (serviceRtm *ServiceRtm) Pack(w io.Writer) (err error) { - err = serviceRtm.Service.Pack(w) - if err != nil { - return - } - err = packString(w, serviceRtm.UserId) - return -} - -func (serviceRtm *ServiceRtm) UnPack(r io.Reader) (err error) { - err = serviceRtm.Service.UnPack(r) - if err != nil { - return - } - serviceRtm.UserId, err = unPackString(r) - return -} - -type ServiceStreaming struct { - *Service - ChannelName string - Uid string -} - -func NewServiceStreaming(channelName string, uid string) (serviceStreaming *ServiceStreaming) { - serviceStreaming = &ServiceStreaming{ChannelName: channelName, Service: NewService(ServiceTypeStreaming), Uid: uid} - return -} - -func (serviceStreaming *ServiceStreaming) Pack(w io.Writer) (err error) { - err = serviceStreaming.Service.Pack(w) - if err != nil { - return - } - err = packString(w, serviceStreaming.ChannelName) - if err != nil { - return - } - err = packString(w, serviceStreaming.Uid) - return -} - -func (serviceStreaming *ServiceStreaming) UnPack(r io.Reader) (err error) { - err = serviceStreaming.Service.UnPack(r) - if err != nil { - return - } - serviceStreaming.ChannelName, err = unPackString(r) - serviceStreaming.Uid, err = unPackString(r) - return -} - -type ServiceFpa struct { - *Service -} - -func NewServiceFpa() (serviceFpa *ServiceFpa) { - serviceFpa = &ServiceFpa{Service: NewService(ServiceTypeFpa)} - return -} - -func (serviceFpa *ServiceFpa) Pack(w io.Writer) (err error) { - err = serviceFpa.Service.Pack(w) - if err != nil { - return - } - return -} - -func (serviceFpa *ServiceFpa) UnPack(r io.Reader) (err error) { - err = serviceFpa.Service.UnPack(r) - if err != nil { - return - } - return + *Service + UserId string } type ServiceChat struct { - *Service - UserId string + *Service + UserId string } func NewServiceChat(userId string) (serviceChat *ServiceChat) { - serviceChat = &ServiceChat{Service: NewService(ServiceTypeChat), UserId: userId} - return + serviceChat = &ServiceChat{Service: NewService(ServiceTypeChat), UserId: userId} + return } func (serviceChat *ServiceChat) Pack(w io.Writer) (err error) { - err = serviceChat.Service.Pack(w) - if err != nil { - panic(fmt.Sprintf("pack service failed: %v", err.Error())) - } - err = packString(w, serviceChat.UserId) - return + err = serviceChat.Service.Pack(w) + if err != nil { + panic(fmt.Sprintf("pack service failed: %v", err.Error())) + } + err = packString(w, serviceChat.UserId) + return } func (serviceChat *ServiceChat) UnPack(r io.Reader) (err error) { - err = serviceChat.Service.UnPack(r) - if err != nil { - panic(fmt.Sprintf("unpack service failed: %v", err.Error())) - } - serviceChat.UserId, err = unPackString(r) - return + err = serviceChat.Service.UnPack(r) + if err != nil { + panic(fmt.Sprintf("unpack service failed: %v", err.Error())) + } + serviceChat.UserId, err = unPackString(r) + return } type AccessToken struct { - AppCert string - AppId string - Expire uint32 - IssueTs uint32 - Salt uint32 - Services map[uint16]IService + AppCert string + AppId string + Expire uint32 + IssueTs uint32 + Salt uint32 + Services map[uint16]IService } func NewAccessToken(appId string, appCert string, expire uint32) (accessToken *AccessToken) { - issueTs := uint32(time.Now().Unix()) - salt := uint32(getRand(1, 99999999)) - accessToken = &AccessToken{AppCert: appCert, AppId: appId, Expire: expire, IssueTs: issueTs, Salt: salt, Services: make(map[uint16]IService)} - return + issueTs := uint32(time.Now().Unix()) + salt := uint32(getRand(1, 99999999)) + accessToken = &AccessToken{AppCert: appCert, AppId: appId, Expire: expire, IssueTs: issueTs, Salt: salt, Services: make(map[uint16]IService)} + return } func CreateAccessToken() (accessToken *AccessToken) { - return NewAccessToken("", "", 900) + return NewAccessToken("", "", 900) } func (accessToken *AccessToken) AddService(service IService) { - accessToken.Services[service.getServiceType()] = service + accessToken.Services[service.getServiceType()] = service } func (accessToken *AccessToken) Build() (res string, err error) { - recoverException() - - if !isUuid(accessToken.AppId) || !isUuid(accessToken.AppCert) { - return "", errors.New("check appId or appCertificate") - } - - buf := new(bytes.Buffer) - if err = packString(buf, accessToken.AppId); err != nil { - return - } - if err = packUint32(buf, accessToken.IssueTs); err != nil { - return - } - if err = packUint32(buf, accessToken.Expire); err != nil { - return - } - if err = packUint32(buf, accessToken.Salt); err != nil { - return - } - if err = packUint16(buf, uint16(len(accessToken.Services))); err != nil { - return - } - - // Sign - var sign []byte - sign, err = accessToken.getSign() - - if err != nil { - return - } - - // Pack services in definite order - serviceTypes := []uint16{ServiceTypeRtc, ServiceTypeRtm, ServiceTypeStreaming, ServiceTypeFpa, ServiceTypeChat} - for _, serviceType := range serviceTypes { - if service, ok := accessToken.Services[serviceType]; ok { - err = service.Pack(buf) - if err != nil { - return - } - } - } - - // Signature - hSign := hmac.New(sha256.New, sign) - hSign.Write(buf.Bytes()) - signature := hSign.Sum(nil) - - bufContent := new(bytes.Buffer) - if err = packString(bufContent, string(signature)); err != nil { - return - } - bufContent.Write(buf.Bytes()) - - res = getVersion() + base64EncodeStr(compressZlib(bufContent.Bytes())) - return + recoverException() + + if !isUuid(accessToken.AppId) || !isUuid(accessToken.AppCert) { + return "", errors.New("check appId or appCertificate") + } + + buf := new(bytes.Buffer) + if err = packString(buf, accessToken.AppId); err != nil { + return + } + if err = packUint32(buf, accessToken.IssueTs); err != nil { + return + } + if err = packUint32(buf, accessToken.Expire); err != nil { + return + } + if err = packUint32(buf, accessToken.Salt); err != nil { + return + } + if err = packUint16(buf, uint16(len(accessToken.Services))); err != nil { + return + } + + // Sign + var sign []byte + sign, err = accessToken.getSign() + + if err != nil { + return + } + + // Pack services in definite order + serviceTypes := []uint16{ServiceTypeRtc, ServiceTypeChat} + for _, serviceType := range serviceTypes { + if service, ok := accessToken.Services[serviceType]; ok { + err = service.Pack(buf) + if err != nil { + return + } + } + } + + // Signature + hSign := hmac.New(sha256.New, sign) + hSign.Write(buf.Bytes()) + signature := hSign.Sum(nil) + + bufContent := new(bytes.Buffer) + if err = packString(bufContent, string(signature)); err != nil { + return + } + bufContent.Write(buf.Bytes()) + + res = getVersion() + base64EncodeStr(compressZlib(bufContent.Bytes())) + return } func (accessToken *AccessToken) Parse(token string) (res bool, err error) { - recoverException() - - version := token[:VersionLength] - if version != getVersion() { - return - } - - var decodeByte []byte - if decodeByte, err = base64DecodeStr(token[VersionLength:]); err != nil { - return - } - buffer := bytes.NewReader(decompressZlib(decodeByte)) - // signature - _, err = unPackString(buffer) - if accessToken.AppId, err = unPackString(buffer); err != nil { - return - } - if accessToken.IssueTs, err = unPackUint32(buffer); err != nil { - return - } - if accessToken.Expire, err = unPackUint32(buffer); err != nil { - return - } - if accessToken.Salt, err = unPackUint32(buffer); err != nil { - return - } - - var serviceNum uint16 - if serviceNum, err = unPackUint16(buffer); err != nil { - return - } - var serviceType uint16 - for i := 0; i < int(serviceNum); i++ { - if serviceType, err = unPackUint16(buffer); err != nil { - return - } - service := accessToken.newService(serviceType) - if err = service.UnPack(buffer); err != nil { - return - } - accessToken.Services[serviceType] = service - } - - return true, nil + recoverException() + + version := token[:VersionLength] + if version != getVersion() { + return + } + + var decodeByte []byte + if decodeByte, err = base64DecodeStr(token[VersionLength:]); err != nil { + return + } + buffer := bytes.NewReader(decompressZlib(decodeByte)) + // signature + _, err = unPackString(buffer) + if accessToken.AppId, err = unPackString(buffer); err != nil { + return + } + if accessToken.IssueTs, err = unPackUint32(buffer); err != nil { + return + } + if accessToken.Expire, err = unPackUint32(buffer); err != nil { + return + } + if accessToken.Salt, err = unPackUint32(buffer); err != nil { + return + } + + var serviceNum uint16 + if serviceNum, err = unPackUint16(buffer); err != nil { + return + } + var serviceType uint16 + for i := 0; i < int(serviceNum); i++ { + if serviceType, err = unPackUint16(buffer); err != nil { + return + } + service := accessToken.newService(serviceType) + if err = service.UnPack(buffer); err != nil { + return + } + accessToken.Services[serviceType] = service + } + + return true, nil } func (accessToken *AccessToken) getSign() (sign []byte, err error) { - // IssueTs - bufIssueTs := new(bytes.Buffer) - err = packUint32(bufIssueTs, accessToken.IssueTs) - if err != nil { - return - } - hIssueTs := hmac.New(sha256.New, bufIssueTs.Bytes()) - hIssueTs.Write([]byte(accessToken.AppCert)) - - // Salt - bufSalt := new(bytes.Buffer) - err = packUint32(bufSalt, accessToken.Salt) - if err != nil { - return - } - hSalt := hmac.New(sha256.New, bufSalt.Bytes()) - hSalt.Write([]byte(hIssueTs.Sum(nil))) - sign = hSalt.Sum(nil) - return + // IssueTs + bufIssueTs := new(bytes.Buffer) + err = packUint32(bufIssueTs, accessToken.IssueTs) + if err != nil { + return + } + hIssueTs := hmac.New(sha256.New, bufIssueTs.Bytes()) + hIssueTs.Write([]byte(accessToken.AppCert)) + + // Salt + bufSalt := new(bytes.Buffer) + err = packUint32(bufSalt, accessToken.Salt) + if err != nil { + return + } + hSalt := hmac.New(sha256.New, bufSalt.Bytes()) + hSalt.Write([]byte(hIssueTs.Sum(nil))) + sign = hSalt.Sum(nil) + return } func (accessToken *AccessToken) newService(serviceType uint16) (service IService) { - switch serviceType { - case ServiceTypeRtc: - service = NewServiceRtc("", "") - case ServiceTypeRtm: - service = NewServiceRtm("") - case ServiceTypeStreaming: - service = NewServiceStreaming("", "") - case ServiceTypeFpa: - service = NewServiceFpa() - case ServiceTypeChat: - service = NewServiceChat("") - default: - panic(fmt.Sprintf("new service failed: unknown service type `%v`", serviceType)) - } - return + switch serviceType { + case ServiceTypeRtc: + service = NewServiceRtc("", "") + case ServiceTypeChat: + service = NewServiceChat("") + default: + panic(fmt.Sprintf("new service failed: unknown service type `%v`", serviceType)) + } + return } func GetUidStr(uid uint32) string { - if uid == 0 { - return "" - } - return fmt.Sprintf("%d", uid) + if uid == 0 { + return "" + } + return fmt.Sprintf("%d", uid) } func getVersion() string { - return Version + return Version } func isUuid(s string) (res bool) { - if len(s) != 32 { - return - } - if _, err := hex.DecodeString(s); err != nil { - return - } - return true + if len(s) != 32 { + return + } + if _, err := hex.DecodeString(s); err != nil { + return + } + return true } diff --git a/DynamicKey/AgoraDynamicKey/go/src/accesstoken2/accesstoken_test.go b/DynamicKey/AgoraDynamicKey/go/src/accesstoken2/accesstoken_test.go index e4d3e7f7..73afd369 100644 --- a/DynamicKey/AgoraDynamicKey/go/src/accesstoken2/accesstoken_test.go +++ b/DynamicKey/AgoraDynamicKey/go/src/accesstoken2/accesstoken_test.go @@ -101,39 +101,6 @@ func Test_AccessToken_Build_ServiceRtc_Uid0(t *testing.T) { AssertEqual(t, "007eJxSYLhzZP08Lxa1Pg57+TcXb/3cZ3wi4V6kbpbOog0G2dOYk20UGCzNDZwdjU1TUs0Mkk1MzExMk5ISUy0SjQxNDcwMk4yN3b8IMEQwMTAwMoAwBIL4CgzmKeZGxmamqUmWFsYmFqbGluapxqnGaZYpJmYGSSkpiQwMgAAAAP//Npwiag==", token) } -func Test_AccessToken_Build_ServiceRtm(t *testing.T) { - accessToken := NewAccessToken(DataMockAppId, DataMockAppCertificate, DataMockExpire) - accessToken.IssueTs = DataMockIssueTs - accessToken.Salt = DataMockSalt - - serviceRtm := NewServiceRtm(DataMockUserId) - serviceRtm.AddPrivilege(PrivilegeLogin, DataMockExpire) - accessToken.AddService(serviceRtm) - - AssertEqual(t, DataMockUserId, serviceRtm.UserId) - - token, err := accessToken.Build() - AssertNil(t, err) - AssertEqual(t, "007eJxSYOCdJftjyTM2zxW6Xhm/5T0j5LdcUt/xYVt48fb5Mp3PX9coMFiaGzg7GpumpJoZJJuYmJmYJiUlplokGhmaGpgZJhkbu38RYIhgYmBgZABhJgZGBkYwn5OhJLW4JL60OLUIEAAA//9ZVh6A", token) -} - -func Test_AccessToken_Build_ServiceStreaming(t *testing.T) { - accessToken := NewAccessToken(DataMockAppId, DataMockAppCertificate, DataMockExpire) - accessToken.IssueTs = DataMockIssueTs - accessToken.Salt = DataMockSalt - - serviceStreaming := NewServiceStreaming(DataMockChannelName, DataMockUidStr) - serviceStreaming.AddPrivilege(PrivilegeJoinChannel, DataMockExpire) - accessToken.AddService(serviceStreaming) - - AssertEqual(t, DataMockChannelName, serviceStreaming.ChannelName) - AssertEqual(t, DataMockUidStr, serviceStreaming.Uid) - - token, err := accessToken.Build() - AssertNil(t, err) - AssertEqual(t, "007eJxSYGBj//4jzGnul2n88j7n7tb9njDzn/j5BhulK6yLV5/YlWKnwGBpbuDsaGyakmpmkGxiYmZimpSUmGqRaGRoamBmmGRs7P5FgCGCiYGBkQGEmRkYGRjBfAUG8xRzI2Mz09QkSwtjEwtTY0vzVONU4zTLFBMzg6SUlEQuBiMLCyNjE0Mjc2NAAAAA//8zyyXw", token) -} - func Test_AccessToken_Build_ServiceChatUser(t *testing.T) { accessToken := NewAccessToken(DataMockAppId, DataMockAppCertificate, DataMockExpire) accessToken.IssueTs = DataMockIssueTs @@ -174,29 +141,22 @@ func Test_AccessToken_Build_MultipleServices(t *testing.T) { // RTC serviceRtc := NewServiceRtc(DataMockChannelName, DataMockUidStr) serviceRtc.AddPrivilege(PrivilegeJoinChannel, DataMockExpire) + serviceRtc.AddPrivilege(PrivilegePublishAudioStream, DataMockExpire) + serviceRtc.AddPrivilege(PrivilegePublishVideoStream, DataMockExpire) + serviceRtc.AddPrivilege(PrivilegePublishDataStream, DataMockExpire) accessToken.AddService(serviceRtc) - // RTM - serviceRtm := NewServiceRtm(DataMockUserId) - serviceRtm.AddPrivilege(PrivilegeLogin, DataMockExpire) - accessToken.AddService(serviceRtm) - - // STREAMING - serviceStreaming := NewServiceStreaming(DataMockChannelName, DataMockUidStr) - serviceStreaming.AddPrivilege(PrivilegeJoinChannel, DataMockExpire) - accessToken.AddService(serviceStreaming) - // CHAT serviceChat := NewServiceChat(DataMockUidStr) serviceChat.AddPrivilege(PrivilegeChatUser, DataMockExpire) accessToken.AddService(serviceChat) - AssertEqual(t, DataMockChannelName, serviceStreaming.ChannelName) - AssertEqual(t, DataMockUidStr, serviceStreaming.Uid) + AssertEqual(t, DataMockChannelName, serviceRtc.ChannelName) + AssertEqual(t, DataMockUidStr, serviceRtc.Uid) token, err := accessToken.Build() AssertNil(t, err) - AssertEqual(t, "007eJxSYHh7j83I4Q6X9f94Vt1zS7du+NrqujQ86nSB+NJZn+eYG1kqMFiaGzg7GpumpJoZJJuYmJmYJiUlplokGhmaGpgZJhkbu38RYIhgYmBgZGBgYGFgBEMQX4HBPMXcyNjMNDXJ0sLYxMLU2NI81TjVOM0yxcTMICklJZGLwcjCwsjYxNDI3JgJro+ToSS1uCS+tDi1iJlMw1jh+pBFAQEAAP//oGY29w==", token) + AssertEqual(t, "007eJxSYLh59YaCUHZeRLXJsRSTDvfv2SV2uddsV+m05Vx5HaP59bMCg6W5gbOjsWlKqplBsomJmYlpUlJiqkWikaGpgZlhkrGx+xcBhggmBgZGBgYGJgZGBhYGRjCfCUwyg0kWMKnAYJ5ibmRsZpqaZGlhbGJhamxpnmqcapxmmWJiZpCUkpLIxWBkYWFkbGJoZG7MysAINQlZFBAAAP//lCcpOg==", token) } func Test_AccessToken_Parse_TokenRtc(t *testing.T) { @@ -243,7 +203,7 @@ func Test_AccessToken_Parse_TokenRtc_FromPython(t *testing.T) { func Test_AccessToken_Parse_TokenRtc_Rtm_MultiService_FromPython(t *testing.T) { accessToken := CreateAccessToken() - res, err := accessToken.Parse("007eJxTYOAQsrQ5s3TfH+1tvy8zZZ46EpCc0V43JXdGd2jS8porKo4KDJbmBs6OxqYpqWYGySYmZiamSUmJqRaJRoamBmaGScbG7l8EGCKYGBgYGRgYmIAkCxCD+ExgkhlMsoBJBQbzFHMjYzPT1CRLC2MTC1NjS/NU41TjNMsUEzODpJSURC4GIwsLI2MTQyNzY5BZEJM4GUpSi0viS4tTiwAipyp4") + res, err := accessToken.Parse("007eJxTYLh59YaCUHZeRLXJsRSTDvfv2SV2uddsV+m05Vx5HaP59bMCg6W5gbOjsWlKqplBsomJmYlpUlJiqkWikaGpgZlhkrGx+xcBhggmBgZGBgYGJiDJAsQgPhOYZAaTLGBSgcE8xdzI2Mw0NcnSwtjEwtTY0jzVONU4zTLFxMwgKSUlkYvByMLCyNjE0MjcmBVoDsQkZFEAlCcpOg==") AssertNil(t, err) AssertEqual(t, true, res) @@ -260,27 +220,6 @@ func Test_AccessToken_Parse_TokenRtc_Rtm_MultiService_FromPython(t *testing.T) { AssertEqual(t, DataMockExpire, accessToken.Services[ServiceTypeRtc].(*ServiceRtc).Privileges[PrivilegePublishAudioStream]) AssertEqual(t, DataMockExpire, accessToken.Services[ServiceTypeRtc].(*ServiceRtc).Privileges[PrivilegePublishVideoStream]) AssertEqual(t, DataMockExpire, accessToken.Services[ServiceTypeRtc].(*ServiceRtc).Privileges[PrivilegePublishDataStream]) - AssertEqual(t, true, accessToken.Services[ServiceTypeRtm] != nil) - AssertEqual(t, DataMockUserId, accessToken.Services[ServiceTypeRtm].(*ServiceRtm).UserId) - AssertEqual(t, uint16(ServiceTypeRtm), accessToken.Services[ServiceTypeRtm].(*ServiceRtm).Type) - AssertEqual(t, DataMockExpire, accessToken.Services[ServiceTypeRtm].(*ServiceRtm).Privileges[PrivilegeLogin]) -} - -func Test_AccessToken_Parse_TokenRtm(t *testing.T) { - accessToken := CreateAccessToken() - res, err := accessToken.Parse("007eJxSYOCdJftjyTM2zxW6Xhm/5T0j5LdcUt/xYVt48fb5Mp3PX9coMFiaGzg7GpumpJoZJJuYmJmYJiUlplokGhmaGpgZJhkbu38RYIhgYmBgZABhJgZGBkYwn5OhJLW4JL60OLUIEAAA//9ZVh6A") - - AssertNil(t, err) - AssertEqual(t, true, res) - AssertEqual(t, DataMockAppId, accessToken.AppId) - AssertEqual(t, DataMockExpire, accessToken.Expire) - AssertEqual(t, DataMockIssueTs, accessToken.IssueTs) - AssertEqual(t, DataMockSalt, accessToken.Salt) - AssertEqual(t, 1, len(accessToken.Services)) - AssertEqual(t, true, accessToken.Services[ServiceTypeRtm] != nil) - AssertEqual(t, DataMockUserId, accessToken.Services[ServiceTypeRtm].(*ServiceRtm).UserId) - AssertEqual(t, uint16(ServiceTypeRtm), accessToken.Services[ServiceTypeRtm].(*ServiceRtm).Type) - AssertEqual(t, DataMockExpire, accessToken.Services[ServiceTypeRtm].(*ServiceRtm).Privileges[PrivilegeLogin]) } func Test_AccessToken_Parse_TokenChatUser(t *testing.T) { diff --git a/DynamicKey/AgoraDynamicKey/go/src/fpatokenbuilder/fpatokenbuilder.go b/DynamicKey/AgoraDynamicKey/go/src/fpatokenbuilder/fpatokenbuilder.go deleted file mode 100644 index 4cd04da1..00000000 --- a/DynamicKey/AgoraDynamicKey/go/src/fpatokenbuilder/fpatokenbuilder.go +++ /dev/null @@ -1,22 +0,0 @@ -package fpatokenbuilder - -import ( - accesstoken "github.com/AgoraIO/Tools/DynamicKey/AgoraDynamicKey/go/src/accesstoken2" -) - -// Build the FPA token. -// -// appId: The App ID issued to you by Agora. Apply for a new App ID from -// Agora Dashboard if it is missing from your kit. See Get an App ID. -// appCertificate: Certificate of the application that you registered in -// the Agora Dashboard. See Get an App Certificate. -// return The FPA token. -func BuildToken(appId string, appCertificate string) (string, error) { - token := accesstoken.NewAccessToken(appId, appCertificate, 24 * 3600) - - serviceFpa := accesstoken.NewServiceFpa() - serviceFpa.AddPrivilege(accesstoken.PrivilegeLogin, 0) - token.AddService(serviceFpa) - - return token.Build() -} diff --git a/DynamicKey/AgoraDynamicKey/go/src/fpatokenbuilder/fpatokenbuilder_test.go b/DynamicKey/AgoraDynamicKey/go/src/fpatokenbuilder/fpatokenbuilder_test.go deleted file mode 100644 index 5404c3b8..00000000 --- a/DynamicKey/AgoraDynamicKey/go/src/fpatokenbuilder/fpatokenbuilder_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package fpatokenbuilder - -import ( - accesstoken "github.com/AgoraIO/Tools/DynamicKey/AgoraDynamicKey/go/src/accesstoken2" - "testing" -) - -const ( - DataMockAppCertificate = "5CFd2fd1755d40ecb72977518be15d3b" - DataMockAppId = "970CA35de60c44645bbae8a215061b33" - DataMockExpire = uint32(24 * 3600) - DataMockPrivilegeLoginExpire = uint32(0) -) - -func Test_BuildToken(t *testing.T) { - token, err := BuildToken(DataMockAppId, DataMockAppCertificate) - accesstoken.AssertNil(t, err) - - accessToken := accesstoken.CreateAccessToken() - accessToken.Parse(token) - - accesstoken.AssertEqual(t, DataMockAppId, accessToken.AppId) - accesstoken.AssertEqual(t, DataMockExpire, accessToken.Expire) - accesstoken.AssertEqual(t, true, accessToken.Services[accesstoken.ServiceTypeFpa] != nil) - accesstoken.AssertEqual(t, uint16(accesstoken.ServiceTypeFpa), accessToken.Services[accesstoken.ServiceTypeFpa].(*accesstoken.ServiceFpa).Type) - accesstoken.AssertEqual(t, DataMockPrivilegeLoginExpire, accessToken.Services[accesstoken.ServiceTypeFpa].(*accesstoken.ServiceFpa).Privileges[accesstoken.PrivilegeLogin]) -} diff --git a/DynamicKey/AgoraDynamicKey/go/src/rtmtokenbuilder2/rtmtokenbuilder.go b/DynamicKey/AgoraDynamicKey/go/src/rtmtokenbuilder2/rtmtokenbuilder.go deleted file mode 100644 index 9a791509..00000000 --- a/DynamicKey/AgoraDynamicKey/go/src/rtmtokenbuilder2/rtmtokenbuilder.go +++ /dev/null @@ -1,25 +0,0 @@ -package rtmtokenbuilder2 - -import ( - accesstoken "github.com/AgoraIO/Tools/DynamicKey/AgoraDynamicKey/go/src/accesstoken2" -) - -// Build the RTM token. -// -// appId: The App ID issued to you by Agora. Apply for a new App ID from -// Agora Dashboard if it is missing from your kit. See Get an App ID. -// appCertificate: Certificate of the application that you registered in -// the Agora Dashboard. See Get an App Certificate. -// userId: The user's account, max length is 64 Bytes. -// expire: represented by the number of seconds elapsed since now. If, for example, you want to access the -// Agora Service within 10 minutes after the token is generated, set expireTimestamp as 600(seconds). -// return The RTM token. -func BuildToken(appId string, appCertificate string, userId string, expire uint32) (string, error) { - token := accesstoken.NewAccessToken(appId, appCertificate, expire) - - serviceRtm := accesstoken.NewServiceRtm(userId) - serviceRtm.AddPrivilege(accesstoken.PrivilegeLogin, expire) - token.AddService(serviceRtm) - - return token.Build() -} diff --git a/DynamicKey/AgoraDynamicKey/go/src/rtmtokenbuilder2/rtmtokenbuilder_test.go b/DynamicKey/AgoraDynamicKey/go/src/rtmtokenbuilder2/rtmtokenbuilder_test.go deleted file mode 100644 index abaf373a..00000000 --- a/DynamicKey/AgoraDynamicKey/go/src/rtmtokenbuilder2/rtmtokenbuilder_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package rtmtokenbuilder2 - -import ( - accesstoken "github.com/AgoraIO/Tools/DynamicKey/AgoraDynamicKey/go/src/accesstoken2" - "testing" -) - -const ( - DataMockAppCertificate = "5CFd2fd1755d40ecb72977518be15d3b" - DataMockAppId = "970CA35de60c44645bbae8a215061b33" - DataMockExpire = uint32(900) - DataMockUserId = "test_user" -) - -func Test_BuildToken(t *testing.T) { - token, err := BuildToken(DataMockAppId, DataMockAppCertificate, DataMockUserId, DataMockExpire) - accesstoken.AssertNil(t, err) - - accessToken := accesstoken.CreateAccessToken() - accessToken.Parse(token) - - accesstoken.AssertEqual(t, DataMockAppId, accessToken.AppId) - accesstoken.AssertEqual(t, DataMockExpire, accessToken.Expire) - accesstoken.AssertEqual(t, true, accessToken.Services[accesstoken.ServiceTypeRtm] != nil) - accesstoken.AssertEqual(t, DataMockUserId, accessToken.Services[accesstoken.ServiceTypeRtm].(*accesstoken.ServiceRtm).UserId) - accesstoken.AssertEqual(t, uint16(accesstoken.ServiceTypeRtm), accessToken.Services[accesstoken.ServiceTypeRtm].(*accesstoken.ServiceRtm).Type) - accesstoken.AssertEqual(t, DataMockExpire, accessToken.Services[accesstoken.ServiceTypeRtm].(*accesstoken.ServiceRtm).Privileges[accesstoken.PrivilegeLogin]) -} diff --git a/DynamicKey/AgoraDynamicKey/python3/sample/RtmTokenBuilder2Sample.py b/DynamicKey/AgoraDynamicKey/python3/sample/RtmTokenBuilder2Sample.py deleted file mode 100644 index e4264b44..00000000 --- a/DynamicKey/AgoraDynamicKey/python3/sample/RtmTokenBuilder2Sample.py +++ /dev/null @@ -1,23 +0,0 @@ -# -*- coding: utf-8 -*- -__copyright__ = "Copyright (c) 2014-2017 Agora.io, Inc." - -import os -import sys - -sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) - -from src.RtmTokenBuilder2 import * - - -def main(): - app_id = "970CA35de60c44645bbae8a215061b33" - app_certificate = "5CFd2fd1755d40ecb72977518be15d3b" - user_id = "test_user_id" - expiration_in_seconds = 3600 - - token = RtmTokenBuilder.build_token(app_id, app_certificate, user_id, expiration_in_seconds) - print("Rtm Token: {}".format(token)) - - -if __name__ == "__main__": - main() diff --git a/DynamicKey/AgoraDynamicKey/python3/sample/fpa_token_builder_sample.py b/DynamicKey/AgoraDynamicKey/python3/sample/fpa_token_builder_sample.py deleted file mode 100644 index f67cbc0f..00000000 --- a/DynamicKey/AgoraDynamicKey/python3/sample/fpa_token_builder_sample.py +++ /dev/null @@ -1,20 +0,0 @@ -# -*- coding: utf-8 -*- -__copyright__ = "Copyright (c) 2014-2017 Agora.io, Inc." - -import os -import sys -from src.fpa_token_builder import * - -sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) - - -def main(): - app_id = "970CA35de60c44645bbae8a215061b33" - app_certificate = "5CFd2fd1755d40ecb72977518be15d3b" - - token = FpaTokenBuilder.build_token(app_id, app_certificate) - print("Token with FPA service: {}".format(token)) - - -if __name__ == "__main__": - main() diff --git a/DynamicKey/AgoraDynamicKey/python3/src/AccessToken2.py b/DynamicKey/AgoraDynamicKey/python3/src/AccessToken2.py index b77cb527..d93784fe 100644 --- a/DynamicKey/AgoraDynamicKey/python3/src/AccessToken2.py +++ b/DynamicKey/AgoraDynamicKey/python3/src/AccessToken2.py @@ -1,7 +1,6 @@ # -*- coding: utf-8 -*- __copyright__ = "Copyright (c) 2014-2017 Agora.io, Inc." - import time import hmac import zlib @@ -13,7 +12,6 @@ from .Packer import * - VERSION_LENGTH = 3 @@ -70,67 +68,12 @@ def unpack(self, buffer): return buffer -class ServiceRtm(Service): - kServiceType = 2 - - kPrivilegeLogin = 1 - - def __init__(self, user_id=''): - super(ServiceRtm, self).__init__(ServiceRtm.kServiceType) - self.__user_id = user_id.encode('utf-8') - - def pack(self): - return super(ServiceRtm, self).pack() + pack_string(self.__user_id) - - def unpack(self, buffer): - buffer = super(ServiceRtm, self).unpack(buffer) - self.__user_id, buffer = unpack_string(buffer) - return buffer - - -class ServiceStreaming(Service): - kServiceType = 3 - - kPrivilegePublishMixStream = 1 - kPrivilegePublishRawStream = 2 - - def __init__(self, channel_name='', uid=0): - super(ServiceStreaming, self).__init__(ServiceStreaming.kServiceType) - self.__channel_name = channel_name.encode('utf-8') - self.__uid = b'' if uid == 0 else str(uid).encode('utf-8') - - def pack(self): - return super(ServiceStreaming, self).pack() + pack_string(self.__channel_name) + pack_string(self.__uid) - - def unpack(self, buffer): - buffer = super(ServiceStreaming, self).unpack(buffer) - self.__channel_name, buffer = unpack_string(buffer) - self.__uid, buffer = unpack_string(buffer) - return buffer - - -class ServiceFpa(Service): - kServiceType = 4 - - kPrivilegeLogin = 1 - - def __init__(self): - super(ServiceFpa, self).__init__(ServiceFpa.kServiceType) - - def pack(self): - return super(ServiceFpa, self).pack() - - def unpack(self, buffer): - buffer = super(ServiceFpa, self).unpack(buffer) - return buffer - - class ServiceChat(Service): kServiceType = 5 kPrivilegeUser = 1 kPrivilegeApp = 2 - + def __init__(self, user_id=''): super(ServiceChat, self).__init__(ServiceChat.kServiceType) self.__user_id = user_id.encode('utf-8') @@ -147,9 +90,6 @@ def unpack(self, buffer): class AccessToken: kServices = { ServiceRtc.kServiceType: ServiceRtc, - ServiceRtm.kServiceType: ServiceRtm, - ServiceStreaming.kServiceType: ServiceStreaming, - ServiceFpa.kServiceType: ServiceFpa, ServiceChat.kServiceType: ServiceChat } @@ -177,6 +117,7 @@ def is_uuid(data): except: return False return True + if not is_uuid(self.__app_id) or not is_uuid(self.__app_cert): return False if not self.__service: @@ -194,7 +135,7 @@ def build(self): self.__app_cert = self.__app_cert.encode('utf-8') signing = self.__signing() signing_info = pack_string(self.__app_id) + pack_uint32(self.__issue_ts) + pack_uint32(self.__expire) + \ - pack_uint32(self.__salt) + pack_uint16(len(self.__service)) + pack_uint32(self.__salt) + pack_uint16(len(self.__service)) for _, service in self.__service.items(): signing_info += service.pack() @@ -226,4 +167,3 @@ def from_string(self, origin_token): print('Error: {}'.format(repr(e))) raise ValueError('Error: parse origin token failed') return True - diff --git a/DynamicKey/AgoraDynamicKey/python3/src/RtmTokenBuilder2.py b/DynamicKey/AgoraDynamicKey/python3/src/RtmTokenBuilder2.py deleted file mode 100755 index d6ada419..00000000 --- a/DynamicKey/AgoraDynamicKey/python3/src/RtmTokenBuilder2.py +++ /dev/null @@ -1,29 +0,0 @@ -# -*- coding: utf-8 -*- -__copyright__ = "Copyright (c) 2014-2017 Agora.io, Inc." - - -from .AccessToken2 import * - - -class RtmTokenBuilder: - @staticmethod - def build_token(app_id, app_certificate, user_id, expire): - """ - Build the RTM token. - :param app_id: The App ID issued to you by Agora. Apply for a new App ID from Agora Dashboard if it is missing - from your kit. See Get an App ID. - :param app_certificate: Certificate of the application that you registered in the Agora Dashboard. - See Get an App Certificate. - :param user_id: The user's account, max length is 64 Bytes. - :param expire: represented by the number of seconds elapsed since now. If, for example, you want to access the - Agora Service within 10 minutes after the token is generated, set expireTimestamp as 600(seconds). - :return: The RTC token. - """ - token = AccessToken(app_id, app_certificate, expire=expire) - - rtm_service = ServiceRtm(user_id) - rtm_service.add_privilege(ServiceRtm.kPrivilegeLogin, expire) - - token.add_service(rtm_service) - - return token.build() diff --git a/DynamicKey/AgoraDynamicKey/python3/src/fpa_token_builder.py b/DynamicKey/AgoraDynamicKey/python3/src/fpa_token_builder.py deleted file mode 100755 index 3422b38a..00000000 --- a/DynamicKey/AgoraDynamicKey/python3/src/fpa_token_builder.py +++ /dev/null @@ -1,24 +0,0 @@ -# -*- coding: utf-8 -*- -__copyright__ = "Copyright (c) 2014-2017 Agora.io, Inc." - -from .AccessToken2 import * - - -class FpaTokenBuilder: - @staticmethod - def build_token(app_id, app_certificate): - """ - Build the FPA token. - :param app_id: The App ID issued to you by Agora. Apply for a new App ID from Agora Dashboard if it is missing - from your kit. See Get an App ID. - :param app_certificate: Certificate of the application that you registered in the Agora Dashboard. - See Get an App Certificate. - :return: The FPA token. - """ - token = AccessToken(app_id, app_certificate, expire=24 * 3600) - - service_fpa = ServiceFpa() - service_fpa.add_privilege(ServiceFpa.kPrivilegeLogin, 0) - token.add_service(service_fpa) - - return token.build() diff --git a/DynamicKey/AgoraDynamicKey/python3/test/AccessToken2Test.py b/DynamicKey/AgoraDynamicKey/python3/test/AccessToken2Test.py index de41a72b..0a64f362 100644 --- a/DynamicKey/AgoraDynamicKey/python3/test/AccessToken2Test.py +++ b/DynamicKey/AgoraDynamicKey/python3/test/AccessToken2Test.py @@ -90,32 +90,15 @@ def test_multi_service(self): rtc.add_privilege(ServiceRtc.kPrivilegePublishVideoStream, self.__expire) rtc.add_privilege(ServiceRtc.kPrivilegePublishDataStream, self.__expire) - rtm = ServiceRtm(self.__user_id) - rtm.add_privilege(ServiceRtm.kPrivilegeLogin, self.__expire) - - streaming = ServiceStreaming(self.__channel_name, self.__uid) - streaming.add_privilege(ServiceStreaming.kPrivilegePublishMixStream, self.__expire) - streaming.add_privilege(ServiceStreaming.kPrivilegePublishRawStream, self.__expire) - - fpa = ServiceFpa() - fpa.add_privilege(ServiceFpa.kPrivilegeLogin, self.__expire) - chat = ServiceChat(self.__uid_str) chat.add_privilege(ServiceChat.kPrivilegeUser, self.__expire) self.__token.add_service(rtc) - self.__token.add_service(rtm) - self.__token.add_service(streaming) - self.__token.add_service(fpa) self.__token.add_service(chat) result = self.__token.build() - expected = '007eJxTYLgzwyF4z+F775+LdK4+u313oKDtdBXruNf31QTrlydWfuRSYL' \ - 'A0N3B2NDZNSTUzSDYxMTMxTUpKTLVINDI0NTAzTDI2dv8iwBDBxMDAyMD' \ - 'AwAokWYAYxGcCk8xgkgVMKjCYp5gbGZuZpiZZWhibWJgaW5qnGqcap1mm' \ - 'mJgZJKWkJHIxGFlYGBmbGBqZGzMBzYGYxMlQklpcEl9anFrEzMCEYjxpR' \ - 'rLAjWSFs5DlAYHiOdw=' + expected = '007eJxTYLh59YaCUHZeRLXJsRSTDvfv2SV2uddsV+m05Vx5HaP59bMCg6W5gbOjsWlKqplBsomJmYlpUlJiqkWikaGpgZlhkrGx+xcBhggmBgZGBgYGJiDJAsQgPhOYZAaTLGBSgcE8xdzI2Mw0NcnSwtjEwtTY0jzVONU4zTLFxMwgKSUlkYvByMLCyNjE0MjcmBVoDsQkZFEAlCcpOg==' self.assertEqual(expected, result) diff --git a/DynamicKey/AgoraDynamicKey/python3/test/RtmTokenBuilder2Test.py b/DynamicKey/AgoraDynamicKey/python3/test/RtmTokenBuilder2Test.py deleted file mode 100644 index 8139b9b0..00000000 --- a/DynamicKey/AgoraDynamicKey/python3/test/RtmTokenBuilder2Test.py +++ /dev/null @@ -1,36 +0,0 @@ -# -*- coding: utf-8 -*- -__copyright__ = "Copyright (c) 2014-2017 Agora.io, Inc." - - -import sys -import unittest -import os - -sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) - -from src.AccessToken2 import * -from src.RtmTokenBuilder2 import * - - -class RtmTokenBuilder2Test(unittest.TestCase): - def setUp(self) -> None: - self.__app_id = "970CA35de60c44645bbae8a215061b33" - self.__app_cert = "5CFd2fd1755d40ecb72977518be15d3b" - self.__user_id = "test_user" - self.__expire = 600 - - def test_token(self): - token = RtmTokenBuilder.build_token(self.__app_id, self.__app_cert, self.__user_id, self.__expire) - parser = AccessToken() - parser.from_string(token) - - self.assertEqual(parser._AccessToken__app_id, self.__app_id.encode('utf-8')) - self.assertEqual(parser._AccessToken__expire, self.__expire) - self.assertIn(ServiceRtm.kServiceType, parser._AccessToken__service) - - parser_service = parser._AccessToken__service[ServiceRtm.kServiceType] - - self.assertEqual(parser_service._ServiceRtm__user_id, self.__user_id.encode('utf-8')) - self.assertIn(ServiceRtm.kPrivilegeLogin, parser_service._Service__privileges) - self.assertEqual(parser_service._Service__privileges[ServiceRtm.kPrivilegeLogin], self.__expire) - print("token: ", token) diff --git a/DynamicKey/AgoraDynamicKey/python3/test/test_fpa_token_builder.py b/DynamicKey/AgoraDynamicKey/python3/test/test_fpa_token_builder.py deleted file mode 100644 index 6519e6dd..00000000 --- a/DynamicKey/AgoraDynamicKey/python3/test/test_fpa_token_builder.py +++ /dev/null @@ -1,30 +0,0 @@ -# -*- coding: utf-8 -*- -__copyright__ = "Copyright (c) 2014-2017 Agora.io, Inc." - -import os -import sys -import unittest -from src.fpa_token_builder import * - -sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) - - -class TestFpaTokenBuilder(unittest.TestCase): - def setUp(self) -> None: - self.__app_id = '970CA35de60c44645bbae8a215061b33' - self.__app_cert = '5CFd2fd1755d40ecb72977518be15d3b' - self.__expire = 24 * 3600 - - def test_build_token(self): - token = FpaTokenBuilder.build_token(self.__app_id, self.__app_cert) - parser = AccessToken() - parser.from_string(token) - - self.assertEqual(parser._AccessToken__app_id, self.__app_id.encode('utf-8')) - self.assertEqual(parser._AccessToken__expire, self.__expire) - self.assertIn(ServiceFpa.kServiceType, parser._AccessToken__service) - - parser_service = parser._AccessToken__service[ServiceFpa.kServiceType] - - self.assertIn(ServiceFpa.kPrivilegeLogin, parser_service._Service__privileges) - self.assertEqual(parser_service._Service__privileges[ServiceFpa.kPrivilegeLogin], 0) From 5dc593cd66d06b5f0db74c75238b11ed7a145f5b Mon Sep 17 00:00:00 2001 From: lixinhui Date: Tue, 21 Dec 2021 18:32:21 +0800 Subject: [PATCH 05/21] just support Rtc/Chat service --- .../AgoraDynamicKey/python3/sample/AccessToken2Sample.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/DynamicKey/AgoraDynamicKey/python3/sample/AccessToken2Sample.py b/DynamicKey/AgoraDynamicKey/python3/sample/AccessToken2Sample.py index 97607019..53fe8254 100644 --- a/DynamicKey/AgoraDynamicKey/python3/sample/AccessToken2Sample.py +++ b/DynamicKey/AgoraDynamicKey/python3/sample/AccessToken2Sample.py @@ -21,18 +21,14 @@ def main(): rtc_service = ServiceRtc(channel_name, uid) rtc_service.add_privilege(ServiceRtc.kPrivilegeJoinChannel, expiration_in_seconds) - rtm_service = ServiceRtm(account) - rtm_service.add_privilege(ServiceRtm.kPrivilegeLogin, expiration_in_seconds) - chat_service = ServiceChat(chat_user_id) chat_service.add_privilege(ServiceChat.kPrivilegeUser, expiration_in_seconds) token = AccessToken(app_id=app_id, app_certificate=app_certificate, expire=expiration_in_seconds) token.add_service(rtc_service) - token.add_service(rtm_service) token.add_service(chat_service) - print("The token for RTC, RTM and CHAT is: {}".format(token.build())) + print("The token for RTC, and CHAT is: {}".format(token.build())) if __name__ == "__main__": From 9909676862ddadd20d11f92948e5c8e1ca9bfe01 Mon Sep 17 00:00:00 2001 From: lixinhui Date: Tue, 21 Dec 2021 18:39:31 +0800 Subject: [PATCH 06/21] just support Rtc/Chat service --- .../python/sample/AccessToken2Sample.py | 6 +- .../python/sample/RtmTokenBuilder2Sample.py | 23 -------- .../python/sample/fpa_token_builder_sample.py | 20 ------- .../python/src/AccessToken2.py | 58 ------------------- .../python/src/RtmTokenBuilder2.py | 28 --------- .../python/src/fpa_token_builder.py | 24 -------- .../python/test/AccessToken2Test.py | 8 +-- .../python/test/RtmTokenBuilder2Test.py | 33 ----------- .../python/test/test_fpa_token_builder.py | 30 ---------- 9 files changed, 2 insertions(+), 228 deletions(-) delete mode 100644 DynamicKey/AgoraDynamicKey/python/sample/RtmTokenBuilder2Sample.py delete mode 100644 DynamicKey/AgoraDynamicKey/python/sample/fpa_token_builder_sample.py delete mode 100755 DynamicKey/AgoraDynamicKey/python/src/RtmTokenBuilder2.py delete mode 100755 DynamicKey/AgoraDynamicKey/python/src/fpa_token_builder.py delete mode 100644 DynamicKey/AgoraDynamicKey/python/test/RtmTokenBuilder2Test.py delete mode 100644 DynamicKey/AgoraDynamicKey/python/test/test_fpa_token_builder.py diff --git a/DynamicKey/AgoraDynamicKey/python/sample/AccessToken2Sample.py b/DynamicKey/AgoraDynamicKey/python/sample/AccessToken2Sample.py index f30adf5b..35149a15 100644 --- a/DynamicKey/AgoraDynamicKey/python/sample/AccessToken2Sample.py +++ b/DynamicKey/AgoraDynamicKey/python/sample/AccessToken2Sample.py @@ -21,18 +21,14 @@ def main(): rtc_service = ServiceRtc(channel_name, uid) rtc_service.add_privilege(ServiceRtc.kPrivilegeJoinChannel, expiration_in_seconds) - rtm_service = ServiceRtm(account) - rtm_service.add_privilege(ServiceRtm.kPrivilegeLogin, expiration_in_seconds) - chat_service = ServiceChat(chat_user_id) chat_service.add_privilege(ServiceChat.kPrivilegeUser, expiration_in_seconds) token = AccessToken(app_id=app_id, app_certificate=app_certificate, expire=expiration_in_seconds) token.add_service(rtc_service) - token.add_service(rtm_service) token.add_service(chat_service) - print("Token for RTC, RTM and CHAT: {}".format(token.build())) + print("Token for RTC and CHAT: {}".format(token.build())) if __name__ == "__main__": diff --git a/DynamicKey/AgoraDynamicKey/python/sample/RtmTokenBuilder2Sample.py b/DynamicKey/AgoraDynamicKey/python/sample/RtmTokenBuilder2Sample.py deleted file mode 100644 index e4264b44..00000000 --- a/DynamicKey/AgoraDynamicKey/python/sample/RtmTokenBuilder2Sample.py +++ /dev/null @@ -1,23 +0,0 @@ -# -*- coding: utf-8 -*- -__copyright__ = "Copyright (c) 2014-2017 Agora.io, Inc." - -import os -import sys - -sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) - -from src.RtmTokenBuilder2 import * - - -def main(): - app_id = "970CA35de60c44645bbae8a215061b33" - app_certificate = "5CFd2fd1755d40ecb72977518be15d3b" - user_id = "test_user_id" - expiration_in_seconds = 3600 - - token = RtmTokenBuilder.build_token(app_id, app_certificate, user_id, expiration_in_seconds) - print("Rtm Token: {}".format(token)) - - -if __name__ == "__main__": - main() diff --git a/DynamicKey/AgoraDynamicKey/python/sample/fpa_token_builder_sample.py b/DynamicKey/AgoraDynamicKey/python/sample/fpa_token_builder_sample.py deleted file mode 100644 index f67cbc0f..00000000 --- a/DynamicKey/AgoraDynamicKey/python/sample/fpa_token_builder_sample.py +++ /dev/null @@ -1,20 +0,0 @@ -# -*- coding: utf-8 -*- -__copyright__ = "Copyright (c) 2014-2017 Agora.io, Inc." - -import os -import sys -from src.fpa_token_builder import * - -sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) - - -def main(): - app_id = "970CA35de60c44645bbae8a215061b33" - app_certificate = "5CFd2fd1755d40ecb72977518be15d3b" - - token = FpaTokenBuilder.build_token(app_id, app_certificate) - print("Token with FPA service: {}".format(token)) - - -if __name__ == "__main__": - main() diff --git a/DynamicKey/AgoraDynamicKey/python/src/AccessToken2.py b/DynamicKey/AgoraDynamicKey/python/src/AccessToken2.py index 162f4090..eb43473a 100644 --- a/DynamicKey/AgoraDynamicKey/python/src/AccessToken2.py +++ b/DynamicKey/AgoraDynamicKey/python/src/AccessToken2.py @@ -67,61 +67,6 @@ def unpack(self, buffer): return buffer -class ServiceRtm(Service): - kServiceType = 2 - - kPrivilegeLogin = 1 - - def __init__(self, user_id=''): - super(ServiceRtm, self).__init__(ServiceRtm.kServiceType) - self.__user_id = user_id.encode('utf-8') - - def pack(self): - return super(ServiceRtm, self).pack() + pack_string(self.__user_id) - - def unpack(self, buffer): - buffer = super(ServiceRtm, self).unpack(buffer) - self.__user_id, buffer = unpack_string(buffer) - return buffer - - -class ServiceStreaming(Service): - kServiceType = 3 - - kPrivilegePublishMixStream = 1 - kPrivilegePublishRawStream = 2 - - def __init__(self, channel_name='', uid=0): - super(ServiceStreaming, self).__init__(ServiceStreaming.kServiceType) - self.__channel_name = channel_name.encode('utf-8') - self.__uid = b'' if uid == 0 else str(uid).encode('utf-8') - - def pack(self): - return super(ServiceStreaming, self).pack() + pack_string(self.__channel_name) + pack_string(self.__uid) - - def unpack(self, buffer): - buffer = super(ServiceStreaming, self).unpack(buffer) - self.__channel_name, buffer = unpack_string(buffer) - self.__uid, buffer = unpack_string(buffer) - return buffer - - -class ServiceFpa(Service): - kServiceType = 4 - - kPrivilegeLogin = 1 - - def __init__(self): - super(ServiceFpa, self).__init__(ServiceFpa.kServiceType) - - def pack(self): - return super(ServiceFpa, self).pack() - - def unpack(self, buffer): - buffer = super(ServiceFpa, self).unpack(buffer) - return buffer - - class ServiceChat(Service): kServiceType = 5 @@ -144,9 +89,6 @@ def unpack(self, buffer): class AccessToken: kServices = { ServiceRtc.kServiceType: ServiceRtc, - ServiceRtm.kServiceType: ServiceRtm, - ServiceStreaming.kServiceType: ServiceStreaming, - ServiceFpa.kServiceType: ServiceFpa, ServiceChat.kServiceType: ServiceChat } diff --git a/DynamicKey/AgoraDynamicKey/python/src/RtmTokenBuilder2.py b/DynamicKey/AgoraDynamicKey/python/src/RtmTokenBuilder2.py deleted file mode 100755 index 18c7eb9e..00000000 --- a/DynamicKey/AgoraDynamicKey/python/src/RtmTokenBuilder2.py +++ /dev/null @@ -1,28 +0,0 @@ -# -*- coding: utf-8 -*- -__copyright__ = "Copyright (c) 2014-2017 Agora.io, Inc." - -from .AccessToken2 import * - - -class RtmTokenBuilder: - @staticmethod - def build_token(app_id, app_certificate, user_id, expire): - """ - Build the RTM token. - :param app_id: The App ID issued to you by Agora. Apply for a new App ID from Agora Dashboard if it is missing - from your kit. See Get an App ID. - :param app_certificate: Certificate of the application that you registered in the Agora Dashboard. - See Get an App Certificate. - :param user_id: The user's account, max length is 64 Bytes. - :param expire: represented by the number of seconds elapsed since now. If, for example, you want to access the - Agora Service within 10 minutes after the token is generated, set expireTimestamp as 600(seconds). - :return: The RTC token. - """ - token = AccessToken(app_id, app_certificate, expire=expire) - - rtm_service = ServiceRtm(user_id) - rtm_service.add_privilege(ServiceRtm.kPrivilegeLogin, expire) - - token.add_service(rtm_service) - - return token.build() diff --git a/DynamicKey/AgoraDynamicKey/python/src/fpa_token_builder.py b/DynamicKey/AgoraDynamicKey/python/src/fpa_token_builder.py deleted file mode 100755 index 3422b38a..00000000 --- a/DynamicKey/AgoraDynamicKey/python/src/fpa_token_builder.py +++ /dev/null @@ -1,24 +0,0 @@ -# -*- coding: utf-8 -*- -__copyright__ = "Copyright (c) 2014-2017 Agora.io, Inc." - -from .AccessToken2 import * - - -class FpaTokenBuilder: - @staticmethod - def build_token(app_id, app_certificate): - """ - Build the FPA token. - :param app_id: The App ID issued to you by Agora. Apply for a new App ID from Agora Dashboard if it is missing - from your kit. See Get an App ID. - :param app_certificate: Certificate of the application that you registered in the Agora Dashboard. - See Get an App Certificate. - :return: The FPA token. - """ - token = AccessToken(app_id, app_certificate, expire=24 * 3600) - - service_fpa = ServiceFpa() - service_fpa.add_privilege(ServiceFpa.kPrivilegeLogin, 0) - token.add_service(service_fpa) - - return token.build() diff --git a/DynamicKey/AgoraDynamicKey/python/test/AccessToken2Test.py b/DynamicKey/AgoraDynamicKey/python/test/AccessToken2Test.py index c5109505..57c49a7f 100644 --- a/DynamicKey/AgoraDynamicKey/python/test/AccessToken2Test.py +++ b/DynamicKey/AgoraDynamicKey/python/test/AccessToken2Test.py @@ -87,18 +87,12 @@ def test_multi_service(self): rtc.add_privilege(ServiceRtc.kPrivilegePublishVideoStream, self.__expire) rtc.add_privilege(ServiceRtc.kPrivilegePublishDataStream, self.__expire) - rtm = ServiceRtm(self.__user_id) - rtm.add_privilege(ServiceRtm.kPrivilegeLogin, self.__expire) - chat = ServiceChat(self.__uid_str) chat.add_privilege(ServiceChat.kPrivilegeUser, self.__expire) self.__token.add_service(rtc) - self.__token.add_service(rtm) self.__token.add_service(chat) result = self.__token.build() - expected = '007eJxTYPg19dsX8xO2Nys/bpSeoH/0j9CvSs1JWib9291PKC53l85UYLA0N3B2NDZNSTUzSDYxMTMxTUpKTLVINDI0NTA' \ - 'zTDI2dv8iwBDBxMDAyMDAwAwkWYAYxGcCk8xgkgVMKjCYp5gbGZuZpiZZWhibWJgaW5qnGqcap1mmmJgZJKWkJHIxGFlYG' \ - 'BmbGBqZGzMBzYGYxMlQklpcEl9anFrEChdEVgoAw6ct/Q==' + expected = '007eJxTYLh59YaCUHZeRLXJsRSTDvfv2SV2uddsV+m05Vx5HaP59bMCg6W5gbOjsWlKqplBsomJmYlpUlJiqkWikaGpgZlhkrGx+xcBhggmBgZGBgYGJiDJAsQgPhOYZAaTLGBSgcE8xdzI2Mw0NcnSwtjEwtTY0jzVONU4zTLFxMwgKSUlkYvByMLCyNjE0MjcmBVoDsQkZFEAlCcpOg==' self.assertEqual(expected, result) diff --git a/DynamicKey/AgoraDynamicKey/python/test/RtmTokenBuilder2Test.py b/DynamicKey/AgoraDynamicKey/python/test/RtmTokenBuilder2Test.py deleted file mode 100644 index 9e25466d..00000000 --- a/DynamicKey/AgoraDynamicKey/python/test/RtmTokenBuilder2Test.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -__copyright__ = "Copyright (c) 2014-2017 Agora.io, Inc." - -import sys -import unittest -import os - -sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) - -from src.RtmTokenBuilder2 import * - - -class RtmTokenBuilder2Test(unittest.TestCase): - def setUp(self): - self.__app_id = "970CA35de60c44645bbae8a215061b33" - self.__app_cert = "5CFd2fd1755d40ecb72977518be15d3b" - self.__user_id = "test_user" - self.__expire = 600 - - def test_token(self): - token = RtmTokenBuilder.build_token(self.__app_id, self.__app_cert, self.__user_id, self.__expire) - parser = AccessToken() - parser.from_string(token) - - self.assertEqual(parser._AccessToken__app_id, self.__app_id.encode('utf-8')) - self.assertEqual(parser._AccessToken__expire, self.__expire) - self.assertIn(ServiceRtm.kServiceType, parser._AccessToken__service) - - parser_service = parser._AccessToken__service[ServiceRtm.kServiceType] - - self.assertEqual(parser_service._ServiceRtm__user_id, self.__user_id.encode('utf-8')) - self.assertIn(ServiceRtm.kPrivilegeLogin, parser_service._Service__privileges) - self.assertEqual(parser_service._Service__privileges[ServiceRtm.kPrivilegeLogin], self.__expire) diff --git a/DynamicKey/AgoraDynamicKey/python/test/test_fpa_token_builder.py b/DynamicKey/AgoraDynamicKey/python/test/test_fpa_token_builder.py deleted file mode 100644 index 80bd7802..00000000 --- a/DynamicKey/AgoraDynamicKey/python/test/test_fpa_token_builder.py +++ /dev/null @@ -1,30 +0,0 @@ -# -*- coding: utf-8 -*- -__copyright__ = "Copyright (c) 2014-2017 Agora.io, Inc." - -import os -import sys -import unittest -from src.fpa_token_builder import * - -sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) - - -class TestFpaTokenBuilder(unittest.TestCase): - def setUp(self): - self.__app_id = '970CA35de60c44645bbae8a215061b33' - self.__app_cert = '5CFd2fd1755d40ecb72977518be15d3b' - self.__expire = 24 * 3600 - - def test_build_token(self): - token = FpaTokenBuilder.build_token(self.__app_id, self.__app_cert) - parser = AccessToken() - parser.from_string(token) - - self.assertEqual(parser._AccessToken__app_id, self.__app_id.encode('utf-8')) - self.assertEqual(parser._AccessToken__expire, self.__expire) - self.assertIn(ServiceFpa.kServiceType, parser._AccessToken__service) - - parser_service = parser._AccessToken__service[ServiceFpa.kServiceType] - - self.assertIn(ServiceFpa.kPrivilegeLogin, parser_service._Service__privileges) - self.assertEqual(parser_service._Service__privileges[ServiceFpa.kPrivilegeLogin], 0) From 9580836e24b8a21ca38857f9d41510538122644c Mon Sep 17 00:00:00 2001 From: lixinhui Date: Tue, 21 Dec 2021 18:52:17 +0800 Subject: [PATCH 07/21] just support Rtc/Chat service --- .../go/src/accesstoken2/accesstoken_test.go | 2 +- .../php/sample/FpaTokenBuilderSample.php | 8 -- .../php/sample/RtmTokenBuilder2Sample.php | 12 --- .../AgoraDynamicKey/php/src/AccessToken2.php | 76 ------------------- .../php/src/FpaTokenBuilder.php | 25 ------ .../php/src/RtmTokenBuilder2.php | 29 ------- .../php/test/AccessToken2Test.php | 31 ++------ .../php/test/FpaTokenBuilderTest.php | 30 -------- .../php/test/RtmTokenBuilder2Test.php | 33 -------- 9 files changed, 6 insertions(+), 240 deletions(-) delete mode 100644 DynamicKey/AgoraDynamicKey/php/sample/FpaTokenBuilderSample.php delete mode 100644 DynamicKey/AgoraDynamicKey/php/sample/RtmTokenBuilder2Sample.php delete mode 100644 DynamicKey/AgoraDynamicKey/php/src/FpaTokenBuilder.php delete mode 100644 DynamicKey/AgoraDynamicKey/php/src/RtmTokenBuilder2.php delete mode 100644 DynamicKey/AgoraDynamicKey/php/test/FpaTokenBuilderTest.php delete mode 100644 DynamicKey/AgoraDynamicKey/php/test/RtmTokenBuilder2Test.php diff --git a/DynamicKey/AgoraDynamicKey/go/src/accesstoken2/accesstoken_test.go b/DynamicKey/AgoraDynamicKey/go/src/accesstoken2/accesstoken_test.go index 73afd369..577a7cbb 100644 --- a/DynamicKey/AgoraDynamicKey/go/src/accesstoken2/accesstoken_test.go +++ b/DynamicKey/AgoraDynamicKey/go/src/accesstoken2/accesstoken_test.go @@ -201,7 +201,7 @@ func Test_AccessToken_Parse_TokenRtc_FromPython(t *testing.T) { AssertEqual(t, uint32(0), accessToken.Services[ServiceTypeRtc].(*ServiceRtc).Privileges[PrivilegePublishDataStream]) } -func Test_AccessToken_Parse_TokenRtc_Rtm_MultiService_FromPython(t *testing.T) { +func Test_AccessToken_Parse_Token_MultiService_FromPython(t *testing.T) { accessToken := CreateAccessToken() res, err := accessToken.Parse("007eJxTYLh59YaCUHZeRLXJsRSTDvfv2SV2uddsV+m05Vx5HaP59bMCg6W5gbOjsWlKqplBsomJmYlpUlJiqkWikaGpgZlhkrGx+xcBhggmBgZGBgYGJiDJAsQgPhOYZAaTLGBSgcE8xdzI2Mw0NcnSwtjEwtTY0jzVONU4zTLFxMwgKSUlkYvByMLCyNjE0MjcmBVoDsQkZFEAlCcpOg==") diff --git a/DynamicKey/AgoraDynamicKey/php/sample/FpaTokenBuilderSample.php b/DynamicKey/AgoraDynamicKey/php/sample/FpaTokenBuilderSample.php deleted file mode 100644 index 2f7b3411..00000000 --- a/DynamicKey/AgoraDynamicKey/php/sample/FpaTokenBuilderSample.php +++ /dev/null @@ -1,8 +0,0 @@ - diff --git a/DynamicKey/AgoraDynamicKey/php/src/AccessToken2.php b/DynamicKey/AgoraDynamicKey/php/src/AccessToken2.php index 06a3af72..aa68e2f1 100644 --- a/DynamicKey/AgoraDynamicKey/php/src/AccessToken2.php +++ b/DynamicKey/AgoraDynamicKey/php/src/AccessToken2.php @@ -63,79 +63,6 @@ public function unpack(&$data) } } -class ServiceRtm extends Service -{ - const SERVICE_TYPE = 2; - const PRIVILEGE_LOGIN = 1; - public $userId; - - public function __construct($userId = "") - { - parent::__construct(self::SERVICE_TYPE); - $this->userId = $userId; - } - - public function pack() - { - return parent::pack() . Util::packString($this->userId); - } - - public function unpack(&$data) - { - parent::unpack($data); - $this->userId = Util::unpackString($data); - } -} - -class ServiceStreaming extends Service -{ - const SERVICE_TYPE = 3; - const PRIVILEGE_PUBLISH_MIX_STREAM = 1; - const PRIVILEGE_PUBLISH_RAW_STREAM = 2; - public $channelName; - public $uid; - - public function __construct($channelName = "", $uid = "") - { - parent::__construct(self::SERVICE_TYPE); - $this->channelName = $channelName; - $this->uid = $uid; - } - - public function pack() - { - return parent::pack() . Util::packString($this->channelName) . Util::packString($this->uid); - } - - public function unpack(&$data) - { - parent::unpack($data); - $this->channelName = Util::unpackString($data); - $this->uid = Util::unpackString($data); - } -} - -class ServiceFpa extends Service -{ - const SERVICE_TYPE = 4; - const PRIVILEGE_LOGIN = 1; - - public function __construct() - { - parent::__construct(self::SERVICE_TYPE); - } - - public function pack() - { - return parent::pack(); - } - - public function unpack(&$data) - { - parent::unpack($data); - } -} - class ServiceChat extends Service { const SERVICE_TYPE = 5; @@ -240,9 +167,6 @@ public function parse($token) $servicesObj = [ ServiceRtc::SERVICE_TYPE => new ServiceRtc(), - ServiceRtm::SERVICE_TYPE => new ServiceRtm(), - ServiceStreaming::SERVICE_TYPE => new ServiceStreaming(), - ServiceFpa::SERVICE_TYPE => new ServiceFpa(), ServiceChat::SERVICE_TYPE => new ServiceChat() ]; for ($i = 0; $i < $serviceNum; $i++) { diff --git a/DynamicKey/AgoraDynamicKey/php/src/FpaTokenBuilder.php b/DynamicKey/AgoraDynamicKey/php/src/FpaTokenBuilder.php deleted file mode 100644 index 9874e5be..00000000 --- a/DynamicKey/AgoraDynamicKey/php/src/FpaTokenBuilder.php +++ /dev/null @@ -1,25 +0,0 @@ -addPrivilege($serviceFpa::PRIVILEGE_LOGIN, 0); - $token->addService($serviceFpa); - - return $token->build(); - } -} diff --git a/DynamicKey/AgoraDynamicKey/php/src/RtmTokenBuilder2.php b/DynamicKey/AgoraDynamicKey/php/src/RtmTokenBuilder2.php deleted file mode 100644 index d77cf285..00000000 --- a/DynamicKey/AgoraDynamicKey/php/src/RtmTokenBuilder2.php +++ /dev/null @@ -1,29 +0,0 @@ -addPrivilege($serviceRtm::PRIVILEGE_LOGIN, $expire); - $accessToken->addService($serviceRtm); - - return $accessToken->build(); - } -} diff --git a/DynamicKey/AgoraDynamicKey/php/test/AccessToken2Test.php b/DynamicKey/AgoraDynamicKey/php/test/AccessToken2Test.php index 3781c678..c16d7f23 100644 --- a/DynamicKey/AgoraDynamicKey/php/test/AccessToken2Test.php +++ b/DynamicKey/AgoraDynamicKey/php/test/AccessToken2Test.php @@ -24,8 +24,7 @@ public function run() $this->test_build_ServiceChat_app(); $this->test_build_multi_service(); $this->test_parse_TokenRtc(); - $this->test_parse_TokenRtc_Rtm_Chat_MultiService(); - $this->test_parse_TokenRtm(); + $this->test_parse_Token_MultiService(); $this->test_parse_TokenChat_user(); $this->test_parse_TokenChat_app(); } @@ -111,16 +110,12 @@ public function test_build_multi_service() $serviceRtc->addPrivilege($serviceRtc::PRIVILEGE_PUBLISH_DATA_STREAM, $this->expire); $accessToken->addService($serviceRtc); - $serviceRtm = new ServiceRtm($this->userId); - $serviceRtm->addPrivilege($serviceRtm::PRIVILEGE_LOGIN, $this->expire); - $accessToken->addService($serviceRtm); - $serviceChat = new ServiceChat($this->chatUserId); $serviceChat->addPrivilege($serviceChat::PRIVILEGE_USER, $this->expire); $accessToken->addService($serviceChat); $token = $accessToken->build(); - Util::assertEqual("007eJxTYPg19dsX8xO2Nys/bpSeoH/0j9CvSs1JWib9291PKC53l85UYLA0N3B2NDZNSTUzSDYxMTMxTUpKTLVINDI0NTAzTDI2dv8iwBDBxMDAyMDAwAwkWYAYxGcCk8xgkgVMKjCYp5gbGZuZpiZZWhibWJgaW5qnGqcap1mmmJgZJKWkJHIxGFlYGBmbGBqZGzMBzYGYxMlQklpcEl9anFrEChdEVgoAw6ct/Q==", $token); + Util::assertEqual("007eJxTYLh59YaCUHZeRLXJsRSTDvfv2SV2uddsV+m05Vx5HaP59bMCg6W5gbOjsWlKqplBsomJmYlpUlJiqkWikaGpgZlhkrGx+xcBhggmBgZGBgYGJiDJAsQgPhOYZAaTLGBSgcE8xdzI2Mw0NcnSwtjEwtTY0jzVONU4zTLFxMwgKSUlkYvByMLCyNjE0MjcmBVoDsQkZFEAlCcpOg==", $token); } public function test_parse_TokenRtc() @@ -142,25 +137,23 @@ public function test_parse_TokenRtc() Util::assertEqual(0, $accessToken->services[ServiceRtc::SERVICE_TYPE]->privileges[ServiceRtc::PRIVILEGE_PUBLISH_DATA_STREAM]); } - public function test_parse_TokenRtc_Rtm_Chat_MultiService() + public function test_parse_Token_MultiService() { $accessToken = new AccessToken2(); - $res = $accessToken->parse("007eJxTYPg19dsX8xO2Nys/bpSeoH/0j9CvSs1JWib9291PKC53l85UYLA0N3B2NDZNSTUzSDYxMTMxTUpKTLVINDI0NTAzTDI2dv8iwBDBxMDAyMDAwAwkWYAYxGcCk8xgkgVMKjCYp5gbGZuZpiZZWhibWJgaW5qnGqcap1mmmJgZJKWkJHIxGFlYGBmbGBqZGzMBzYGYxMlQklpcEl9anFrEChdEVgoAw6ct/Q=="); + $res = $accessToken->parse("007eJxTYLh59YaCUHZeRLXJsRSTDvfv2SV2uddsV+m05Vx5HaP59bMCg6W5gbOjsWlKqplBsomJmYlpUlJiqkWikaGpgZlhkrGx+xcBhggmBgZGBgYGJiDJAsQgPhOYZAaTLGBSgcE8xdzI2Mw0NcnSwtjEwtTY0jzVONU4zTLFxMwgKSUlkYvByMLCyNjE0MjcmBVoDsQkZFEAlCcpOg=="); Util::assertEqual(true, $res); Util::assertEqual($this->appId, $accessToken->appId); Util::assertEqual($this->expire, $accessToken->expire); Util::assertEqual($this->issueTs, $accessToken->issueTs); Util::assertEqual($this->salt, $accessToken->salt); - Util::assertEqual(3, count($accessToken->services)); + Util::assertEqual(2, count($accessToken->services)); Util::assertEqual($this->channelName, $accessToken->services[ServiceRtc::SERVICE_TYPE]->channelName); Util::assertEqual($this->uidStr, $accessToken->services[ServiceRtc::SERVICE_TYPE]->uid); Util::assertEqual(ServiceRtc::SERVICE_TYPE, $accessToken->services[ServiceRtc::SERVICE_TYPE]->type); - Util::assertEqual($this->userId, $accessToken->services[ServiceRtm::SERVICE_TYPE]->userId); Util::assertEqual($this->expire, $accessToken->services[ServiceRtc::SERVICE_TYPE]->privileges[ServiceRtc::PRIVILEGE_JOIN_CHANNEL]); Util::assertEqual($this->expire, $accessToken->services[ServiceRtc::SERVICE_TYPE]->privileges[ServiceRtc::PRIVILEGE_PUBLISH_AUDIO_STREAM]); Util::assertEqual($this->expire, $accessToken->services[ServiceRtc::SERVICE_TYPE]->privileges[ServiceRtc::PRIVILEGE_PUBLISH_VIDEO_STREAM]); Util::assertEqual($this->expire, $accessToken->services[ServiceRtc::SERVICE_TYPE]->privileges[ServiceRtc::PRIVILEGE_PUBLISH_DATA_STREAM]); - Util::assertEqual($this->expire, $accessToken->services[ServiceRtm::SERVICE_TYPE]->privileges[ServiceRtm::PRIVILEGE_LOGIN]); // CHAT Util::assertEqual(ServiceChat::SERVICE_TYPE, $accessToken->services[ServiceChat::SERVICE_TYPE]->type); Util::assertEqual($this->chatUserId, $accessToken->services[ServiceChat::SERVICE_TYPE]->userId); @@ -168,20 +161,6 @@ public function test_parse_TokenRtc_Rtm_Chat_MultiService() } - public function test_parse_TokenRtm() - { - $accessToken = new AccessToken2(); - $res = $accessToken->parse("007eJxSYOCdJftjyTM2zxW6Xhm/5T0j5LdcUt/xYVt48fb5Mp3PX9coMFiaGzg7GpumpJoZJJuYmJmYJiUlplokGhmaGpgZJhkbu38RYIhgYmBgZABhJgZGBkYwn5OhJLW4JL60OLUIEAAA//9ZVh6A"); - Util::assertEqual(true, $res); - Util::assertEqual($this->appId, $accessToken->appId); - Util::assertEqual($this->expire, $accessToken->expire); - Util::assertEqual($this->issueTs, $accessToken->issueTs); - Util::assertEqual($this->salt, $accessToken->salt); - Util::assertEqual(1, count($accessToken->services)); - Util::assertEqual(ServiceRtm::SERVICE_TYPE, $accessToken->services[ServiceRtm::SERVICE_TYPE]->type); - Util::assertEqual($this->expire, $accessToken->services[ServiceRtm::SERVICE_TYPE]->privileges[ServiceRtm::PRIVILEGE_LOGIN]); - } - public function test_parse_TokenChat_user() { $accessToken = new AccessToken2(); diff --git a/DynamicKey/AgoraDynamicKey/php/test/FpaTokenBuilderTest.php b/DynamicKey/AgoraDynamicKey/php/test/FpaTokenBuilderTest.php deleted file mode 100644 index 49d62755..00000000 --- a/DynamicKey/AgoraDynamicKey/php/test/FpaTokenBuilderTest.php +++ /dev/null @@ -1,30 +0,0 @@ -test_buildToken(); - } - - public function test_buildToken() - { - $token = FpaTokenBuilder::buildToken($this->appId, $this->appCertificate); - $accessToken = new AccessToken2(); - $accessToken->parse($token); - - Util::assertEqual($this->appId, $accessToken->appId); - Util::assertEqual($this->expire, $accessToken->expire); - Util::assertEqual(ServiceFpa::SERVICE_TYPE, $accessToken->services[ServiceFpa::SERVICE_TYPE]->type); - Util::assertEqual(0, $accessToken->services[ServiceFpa::SERVICE_TYPE]->privileges[ServiceFpa::PRIVILEGE_LOGIN]); - } -} - -$fpaTokenBuilderTest = new FpaTokenBuilderTest(); -$fpaTokenBuilderTest->run(); \ No newline at end of file diff --git a/DynamicKey/AgoraDynamicKey/php/test/RtmTokenBuilder2Test.php b/DynamicKey/AgoraDynamicKey/php/test/RtmTokenBuilder2Test.php deleted file mode 100644 index 4f012a21..00000000 --- a/DynamicKey/AgoraDynamicKey/php/test/RtmTokenBuilder2Test.php +++ /dev/null @@ -1,33 +0,0 @@ -test_buildToken(); - } - - public function test_buildToken() - { - $token = RtmTokenBuilder2::buildToken($this->appId, $this->appCertificate, $this->userId, $this->expire); - $accessToken = new AccessToken2(); - $accessToken->parse($token); - - Util::assertEqual($this->appId, $accessToken->appId); - Util::assertEqual($this->expire, $accessToken->expire); - Util::assertEqual($this->userId, $accessToken->services[ServiceRtm::SERVICE_TYPE]->userId); - Util::assertEqual(ServiceRtm::SERVICE_TYPE, $accessToken->services[ServiceRtm::SERVICE_TYPE]->type); - Util::assertEqual($this->expire, $accessToken->services[ServiceRtm::SERVICE_TYPE]->privileges[ServiceRtm::PRIVILEGE_LOGIN]); - } -} - -$rtmTokenBuilder2Test = new RtmTokenBuilder2Test(); -$rtmTokenBuilder2Test->run(); \ No newline at end of file From a69fc028fe38f683e203a3bf0356541882e31c86 Mon Sep 17 00:00:00 2001 From: lixinhui Date: Tue, 21 Dec 2021 19:11:16 +0800 Subject: [PATCH 08/21] just support Rtc/Chat service --- .../nodejs/sample/FpaTokenBuilderSample.js | 7 - .../nodejs/src/AccessToken2.js | 49 +--- .../nodejs/src/FpaTokenBuilder.js | 24 -- .../nodejs/test/AccessToken2Test.js | 212 +++++++++--------- .../nodejs/test/FpaTokenBuilderTest.js | 22 -- 5 files changed, 108 insertions(+), 206 deletions(-) delete mode 100644 DynamicKey/AgoraDynamicKey/nodejs/sample/FpaTokenBuilderSample.js delete mode 100644 DynamicKey/AgoraDynamicKey/nodejs/src/FpaTokenBuilder.js delete mode 100644 DynamicKey/AgoraDynamicKey/nodejs/test/FpaTokenBuilderTest.js diff --git a/DynamicKey/AgoraDynamicKey/nodejs/sample/FpaTokenBuilderSample.js b/DynamicKey/AgoraDynamicKey/nodejs/sample/FpaTokenBuilderSample.js deleted file mode 100644 index e8c09e87..00000000 --- a/DynamicKey/AgoraDynamicKey/nodejs/sample/FpaTokenBuilderSample.js +++ /dev/null @@ -1,7 +0,0 @@ -const FpaTokenBuilder = require('../src/FpaTokenBuilder').FpaTokenBuilder - -const appID = '970CA35de60c44645bbae8a215061b33' -const appCertificate = '5CFd2fd1755d40ecb72977518be15d3b' - -let token = FpaTokenBuilder.buildToken(appID, appCertificate) -console.log("Token with FPA service: " + token) diff --git a/DynamicKey/AgoraDynamicKey/nodejs/src/AccessToken2.js b/DynamicKey/AgoraDynamicKey/nodejs/src/AccessToken2.js index 0649c71e..455fdc14 100644 --- a/DynamicKey/AgoraDynamicKey/nodejs/src/AccessToken2.js +++ b/DynamicKey/AgoraDynamicKey/nodejs/src/AccessToken2.js @@ -72,49 +72,6 @@ ServiceRtc.kPrivilegePublishAudioStream = 2 ServiceRtc.kPrivilegePublishVideoStream = 3 ServiceRtc.kPrivilegePublishDataStream = 4 -const kRtmServiceType = 2 - -class ServiceRtm extends Service { - constructor(user_id) { - super(kRtmServiceType) - this.__user_id = user_id || "" - } - - pack() { - let buffer = new ByteBuf() - buffer.putString(this.__user_id) - return Buffer.concat([super.pack(), buffer.pack()]) - } - - unpack(buffer) { - let bufReader = super.unpack(buffer) - this.__user_id = bufReader.getString() - return bufReader - } -} - -ServiceRtm.kPrivilegeLogin = 1 - - -const kFpaServiceType = 4 - -class ServiceFpa extends Service { - constructor() { - super(kFpaServiceType) - } - - pack() { - return super.pack() - } - - unpack(buffer) { - let bufReader = super.unpack(buffer) - return bufReader - } -} - -ServiceFpa.kPrivilegeLogin = 1 - const kChatServiceType = 5 @@ -354,11 +311,9 @@ var ReadByteBuf = function (bytes) { AccessToken2.kServices = {} AccessToken2.kServices[kRtcServiceType] = ServiceRtc -AccessToken2.kServices[kRtmServiceType] = ServiceRtm -AccessToken2.kServices[kFpaServiceType] = ServiceFpa AccessToken2.kServices[kChatServiceType] = ServiceChat module.exports = { - AccessToken2, ServiceRtc, ServiceRtm, ServiceFpa, ServiceChat, - kRtcServiceType, kRtmServiceType, kFpaServiceType, kChatServiceType + AccessToken2, ServiceRtc, ServiceChat, + kRtcServiceType, kChatServiceType } \ No newline at end of file diff --git a/DynamicKey/AgoraDynamicKey/nodejs/src/FpaTokenBuilder.js b/DynamicKey/AgoraDynamicKey/nodejs/src/FpaTokenBuilder.js deleted file mode 100644 index c65b2b74..00000000 --- a/DynamicKey/AgoraDynamicKey/nodejs/src/FpaTokenBuilder.js +++ /dev/null @@ -1,24 +0,0 @@ -const AccessToken = require('../src/AccessToken2').AccessToken2 -const ServiceFpa = require('../src/AccessToken2').ServiceFpa - -class FpaTokenBuilder { - /** - * Build the FPA token. - * @param appId The App ID issued to you by Agora. Apply for a new App ID from - * Agora Dashboard if it is missing from your kit. See Get an App ID. - * @param appCertificate Certificate of the application that you registered in - * the Agora Dashboard. See Get an App Certificate. - * @return The FPA token. - */ - static buildToken(appId, appCertificate) { - let token = new AccessToken(appId, appCertificate, 0, 24 * 3600) - - let serviceFpa = new ServiceFpa() - serviceFpa.add_privilege(ServiceFpa.kPrivilegeLogin, 0) - token.add_service(serviceFpa) - - return token.build() - } -} - -module.exports.FpaTokenBuilder = FpaTokenBuilder diff --git a/DynamicKey/AgoraDynamicKey/nodejs/test/AccessToken2Test.js b/DynamicKey/AgoraDynamicKey/nodejs/test/AccessToken2Test.js index 9c4cfe58..b7552065 100644 --- a/DynamicKey/AgoraDynamicKey/nodejs/test/AccessToken2Test.js +++ b/DynamicKey/AgoraDynamicKey/nodejs/test/AccessToken2Test.js @@ -1,110 +1,110 @@ /** * run this test with command: - * nodeunit AccessTokenTest.js + * nodeunit test/AccessToken2Test.js * see https://github.com/caolan/nodeunit */ - const {AccessToken2, ServiceRtc, ServiceRtm, ServiceChat} = require('../src/AccessToken2') - - var appID = "970CA35de60c44645bbae8a215061b33"; - var appCertificate = "5CFd2fd1755d40ecb72977518be15d3b"; - var channel = "7d72365eb983485397e3e3f9d460bdda"; - var uid = 2882341273; - var uidStr = "2882341273" - var ts = 1111111; - var expire = 600; - var salt = 1; - var user_id = "test_user" - - exports.AccessToken_Test = function (test) { - var expected = "007eJxTYBBbsMMnKq7p9Hf/HcIX5kce9b518kCiQgSr5Zrp4X1Tu6UUGCzNDZwdjU1TUs0Mkk1MzExMk5ISUy0SjQxNDcwMk4yN3b8IMEQwMTAwMoAwBIL4CgzmKeZGxmamqUmWFsYmFqbGluapxqnGaZYpJmYGSSkpiVwMRhYWRsYmhkbmxgDCaiTj"; - - var token = new AccessToken2(appID, appCertificate, ts, expire); - token.salt = salt; - let rtc_service = new ServiceRtc(channel, uid) - rtc_service.add_privilege(ServiceRtc.kPrivilegeJoinChannel, expire) - token.add_service(rtc_service) - - var actual = token.build(); - test.equal(expected, actual); - test.done(); - }; - - // test uid = 0 - exports.AccessToken_Test2 = function (test) { - var expected = "007eJxTYLhzZP08Lxa1Pg57+TcXb/3cZ3wi4V6kbpbOog0G2dOYk20UGCzNDZwdjU1TUs0Mkk1MzExMk5ISUy0SjQxNDcwMk4yN3b8IMEQwMTAwMoAwBIL4CgzmKeZGxmamqUmWFsYmFqbGluapxqnGaZYpJmYGSSkpiQwMADacImo="; - - var token = new AccessToken2(appID, appCertificate, ts, expire); - token.salt = salt; - let rtc_service = new ServiceRtc(channel, 0) - rtc_service.add_privilege(ServiceRtc.kPrivilegeJoinChannel, expire) - token.add_service(rtc_service) - - var actual = token.build(); - test.equal(expected, actual); - test.done(); - }; - - // test service rtc account - exports.AccessToken_Test3 = function (test) { - var expected = "007eJxTYBBbsMMnKq7p9Hf/HcIX5kce9b518kCiQgSr5Zrp4X1Tu6UUGCzNDZwdjU1TUs0Mkk1MzExMk5ISUy0SjQxNDcwMk4yN3b8IMEQwMTAwMoAwBIL4CgzmKeZGxmamqUmWFsYmFqbGluapxqnGaZYpJmYGSSkpiVwMRhYWRsYmhkbmxgDCaiTj"; - - var token = new AccessToken2(appID, appCertificate, ts, expire); - token.salt = salt; - let rtc_service = new ServiceRtc(channel, `${uid}`) - rtc_service.add_privilege(ServiceRtc.kPrivilegeJoinChannel, expire) - token.add_service(rtc_service) - - var actual = token.build(); - test.equal(expected, actual); - test.done(); - }; - - // test service multi service - exports.AccessToken_Test4 = function (test) { - var expected = "007eJxTYOAQsrQ5s3TfH+1tvy8zZZ46EpCc0V43JXdGd2jS8porKo4KDJbmBs6OxqYpqWYGySYmZiamSUmJqRaJRoamBmaGScbG7l8EGCKYGBgYGRgYmIAkCxCD+ExgkhlMsoBJBQbzFHMjYzPT1CRLC2MTC1NjS/NU41TjNMsUEzODpJSURC4GIwsLI2MTQyNzY5BZEJM4GUpSi0viS4tTiwAipyp4"; - - var token = new AccessToken2(appID, appCertificate, ts, expire); - token.salt = salt; - let rtc_service = new ServiceRtc(channel, uid) - rtc_service.add_privilege(ServiceRtc.kPrivilegeJoinChannel, expire) - rtc_service.add_privilege(ServiceRtc.kPrivilegePublishAudioStream, expire) - rtc_service.add_privilege(ServiceRtc.kPrivilegePublishVideoStream, expire) - rtc_service.add_privilege(ServiceRtc.kPrivilegePublishDataStream, expire) - token.add_service(rtc_service) - - let rtm_service = new ServiceRtm(user_id) - rtm_service.add_privilege(ServiceRtm.kPrivilegeLogin, expire) - token.add_service(rtm_service) - - var actual = token.build(); - test.equal(expected, actual); - test.done(); - }; - - exports.AccessToken_Test_buildChatUserToken = function (test) { - var expected = "007eJxTYNAIsnbS3v/A5t2TC6feR15r+6cq8bqAvfaW+tk/Vzz+p6xTYLA0N3B2NDZNSTUzSDYxMTMxTUpKTLVINDI0NTAzTDI2dv8iwBDBxMDAyADCrEDMCOZzMRhZWBgZmxgamRsDAB+lHrg=" - - var token = new AccessToken2(appID, appCertificate, ts, expire) - token.salt = salt - let chat_service = new ServiceChat(uidStr) - chat_service.add_privilege(ServiceChat.kPrivilegeUser, expire) - token.add_service(chat_service) - - var actual = token.build() - test.equal(expected, actual) - test.done() - } - - exports.AccessToken_Test_buildChatAppToken = function (test) { - var expected = "007eJxTYNDNaz3snC8huEfHWdz6s98qltq4zqy9fl99Uh0FDvy6F6DAYGlu4OxobJqSamaQbGJiZmKalJSYapFoZGhqYGaYZGzs/kWAIYKJgYGRAYRZgZgJzGdgAACt8hhr" - - var token = new AccessToken2(appID, appCertificate, ts, expire) - token.salt = salt - let chat_service = new ServiceChat() - chat_service.add_privilege(ServiceChat.kPrivilegeApp, expire) - token.add_service(chat_service) - - var actual = token.build() - test.equal(expected, actual) - test.done() - } +const {AccessToken2, ServiceRtc, ServiceChat} = require('../src/AccessToken2') + +var appID = "970CA35de60c44645bbae8a215061b33"; +var appCertificate = "5CFd2fd1755d40ecb72977518be15d3b"; +var channel = "7d72365eb983485397e3e3f9d460bdda"; +var uid = 2882341273; +var uidStr = "2882341273" +var ts = 1111111; +var expire = 600; +var salt = 1; +var user_id = "test_user" + +exports.AccessToken_Test = function (test) { + var expected = "007eJxTYBBbsMMnKq7p9Hf/HcIX5kce9b518kCiQgSr5Zrp4X1Tu6UUGCzNDZwdjU1TUs0Mkk1MzExMk5ISUy0SjQxNDcwMk4yN3b8IMEQwMTAwMoAwBIL4CgzmKeZGxmamqUmWFsYmFqbGluapxqnGaZYpJmYGSSkpiVwMRhYWRsYmhkbmxgDCaiTj"; + + var token = new AccessToken2(appID, appCertificate, ts, expire); + token.salt = salt; + let rtc_service = new ServiceRtc(channel, uid) + rtc_service.add_privilege(ServiceRtc.kPrivilegeJoinChannel, expire) + token.add_service(rtc_service) + + var actual = token.build(); + test.equal(expected, actual); + test.done(); +}; + +// test uid = 0 +exports.AccessToken_Test2 = function (test) { + var expected = "007eJxTYLhzZP08Lxa1Pg57+TcXb/3cZ3wi4V6kbpbOog0G2dOYk20UGCzNDZwdjU1TUs0Mkk1MzExMk5ISUy0SjQxNDcwMk4yN3b8IMEQwMTAwMoAwBIL4CgzmKeZGxmamqUmWFsYmFqbGluapxqnGaZYpJmYGSSkpiQwMADacImo="; + + var token = new AccessToken2(appID, appCertificate, ts, expire); + token.salt = salt; + let rtc_service = new ServiceRtc(channel, 0) + rtc_service.add_privilege(ServiceRtc.kPrivilegeJoinChannel, expire) + token.add_service(rtc_service) + + var actual = token.build(); + test.equal(expected, actual); + test.done(); +}; + +// test service rtc account +exports.AccessToken_Test3 = function (test) { + var expected = "007eJxTYBBbsMMnKq7p9Hf/HcIX5kce9b518kCiQgSr5Zrp4X1Tu6UUGCzNDZwdjU1TUs0Mkk1MzExMk5ISUy0SjQxNDcwMk4yN3b8IMEQwMTAwMoAwBIL4CgzmKeZGxmamqUmWFsYmFqbGluapxqnGaZYpJmYGSSkpiVwMRhYWRsYmhkbmxgDCaiTj"; + + var token = new AccessToken2(appID, appCertificate, ts, expire); + token.salt = salt; + let rtc_service = new ServiceRtc(channel, `${uid}`) + rtc_service.add_privilege(ServiceRtc.kPrivilegeJoinChannel, expire) + token.add_service(rtc_service) + + var actual = token.build(); + test.equal(expected, actual); + test.done(); +}; + +// test service multi service +exports.AccessToken_Test_multi_service = function (test) { + var expected = "007eJxTYLh59YaCUHZeRLXJsRSTDvfv2SV2uddsV+m05Vx5HaP59bMCg6W5gbOjsWlKqplBsomJmYlpUlJiqkWikaGpgZlhkrGx+xcBhggmBgZGBgYGJiDJAsQgPhOYZAaTLGBSgcE8xdzI2Mw0NcnSwtjEwtTY0jzVONU4zTLFxMwgKSUlkYvByMLCyNjE0MjcmBVoDsQkZFEAlCcpOg=="; + + var token = new AccessToken2(appID, appCertificate, ts, expire); + token.salt = salt; + let rtc_service = new ServiceRtc(channel, uid) + rtc_service.add_privilege(ServiceRtc.kPrivilegeJoinChannel, expire) + rtc_service.add_privilege(ServiceRtc.kPrivilegePublishAudioStream, expire) + rtc_service.add_privilege(ServiceRtc.kPrivilegePublishVideoStream, expire) + rtc_service.add_privilege(ServiceRtc.kPrivilegePublishDataStream, expire) + token.add_service(rtc_service) + + let chat_service = new ServiceChat(uidStr) + chat_service.add_privilege(ServiceChat.kPrivilegeUser, expire) + token.add_service(chat_service) + + var actual = token.build(); + test.equal(expected, actual); + test.done(); +}; + +exports.AccessToken_Test_buildChatUserToken = function (test) { + var expected = "007eJxTYNAIsnbS3v/A5t2TC6feR15r+6cq8bqAvfaW+tk/Vzz+p6xTYLA0N3B2NDZNSTUzSDYxMTMxTUpKTLVINDI0NTAzTDI2dv8iwBDBxMDAyADCrEDMCOZzMRhZWBgZmxgamRsDAB+lHrg=" + + var token = new AccessToken2(appID, appCertificate, ts, expire) + token.salt = salt + let chat_service = new ServiceChat(uidStr) + chat_service.add_privilege(ServiceChat.kPrivilegeUser, expire) + token.add_service(chat_service) + + var actual = token.build() + test.equal(expected, actual) + test.done() +} + +exports.AccessToken_Test_buildChatAppToken = function (test) { + var expected = "007eJxTYNDNaz3snC8huEfHWdz6s98qltq4zqy9fl99Uh0FDvy6F6DAYGlu4OxobJqSamaQbGJiZmKalJSYapFoZGhqYGaYZGzs/kWAIYKJgYGRAYRZgZgJzGdgAACt8hhr" + + var token = new AccessToken2(appID, appCertificate, ts, expire) + token.salt = salt + let chat_service = new ServiceChat() + chat_service.add_privilege(ServiceChat.kPrivilegeApp, expire) + token.add_service(chat_service) + + var actual = token.build() + test.equal(expected, actual) + test.done() +} diff --git a/DynamicKey/AgoraDynamicKey/nodejs/test/FpaTokenBuilderTest.js b/DynamicKey/AgoraDynamicKey/nodejs/test/FpaTokenBuilderTest.js deleted file mode 100644 index a6fd9fa6..00000000 --- a/DynamicKey/AgoraDynamicKey/nodejs/test/FpaTokenBuilderTest.js +++ /dev/null @@ -1,22 +0,0 @@ -/** - * run this test with command: - * nodeunit test/FpaTokenBuilderTest.js - * see https://github.com/caolan/nodeunit - */ -const FpaTokenBuilder = require('../src/FpaTokenBuilder').FpaTokenBuilder -const {AccessToken2, ServiceFpa, kFpaServiceType} = require('../src/AccessToken2') - -const appId = "970CA35de60c44645bbae8a215061b33" -const appCertificate = "5CFd2fd1755d40ecb72977518be15d3b" -const expire = 24 * 3600 - -exports.buildToken_Test = function (test) { - let token = FpaTokenBuilder.buildToken(appId, appCertificate) - let accessToken = new AccessToken2('', '', 0, 0) - accessToken.from_string(token) - - test.equal(appId, accessToken.appId) - test.equal(expire, accessToken.expire) - test.equal(0, accessToken.services[kFpaServiceType].__privileges[ServiceFpa.kPrivilegeLogin]) - test.done() -} From 13da9ee27af2e704dc9c76528897eb9c64550927 Mon Sep 17 00:00:00 2001 From: lixinhui Date: Tue, 21 Dec 2021 21:03:45 +0800 Subject: [PATCH 09/21] just support Rtc/Chat service --- .../java/io/agora/media/AccessToken2.java | 119 ------------------ .../java/io/agora/media/FpaTokenBuilder.java | 27 ---- .../java/io/agora/rtm/RtmTokenBuilder2.java | 33 ----- .../io/agora/sample/AccessTokenInspector.java | 31 ----- .../agora/sample/FpaTokenBuilderSample.java | 14 --- .../agora/sample/RtmTokenBuilder2Sample.java | 16 --- .../java/io/agora/media/AccessToken2Test.java | 42 +------ .../io/agora/media/FpaTokenBuilderTest.java | 23 ---- .../io/agora/rtm/RtmTokenBuilder2Test.java | 26 ---- 9 files changed, 3 insertions(+), 328 deletions(-) delete mode 100644 DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/media/FpaTokenBuilder.java delete mode 100644 DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/rtm/RtmTokenBuilder2.java delete mode 100644 DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/sample/FpaTokenBuilderSample.java delete mode 100644 DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/sample/RtmTokenBuilder2Sample.java delete mode 100644 DynamicKey/AgoraDynamicKey/java/src/test/java/io/agora/media/FpaTokenBuilderTest.java delete mode 100644 DynamicKey/AgoraDynamicKey/java/src/test/java/io/agora/rtm/RtmTokenBuilder2Test.java diff --git a/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/media/AccessToken2.java b/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/media/AccessToken2.java index 131d8b7b..329163d7 100644 --- a/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/media/AccessToken2.java +++ b/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/media/AccessToken2.java @@ -20,40 +20,6 @@ public enum PrivilegeRtc { } } - public enum PrivilegeRtm { - PRIVILEGE_LOGIN(1), - ; - - public short intValue; - - PrivilegeRtm(int value) { - intValue = (short) value; - } - } - - public enum PrivilegeStreaming { - PRIVILEGE_PUBLISH_MIX_STREAM(1), - PRIVILEGE_PUBLISH_RAW_STREAM(2), - ; - - public short intValue; - - PrivilegeStreaming(int value) { - intValue = (short) value; - } - } - - public enum PrivilegeFpa { - PRIVILEGE_LOGIN(1), - ; - - public short intValue; - - PrivilegeFpa(int value) { - intValue = (short) value; - } - } - public enum PrivilegeChat { PRIVILEGE_CHAT_USER(1), PRIVILEGE_CHAT_APP(2), @@ -68,9 +34,6 @@ public enum PrivilegeChat { private static final String VERSION = "007"; public static final short SERVICE_TYPE_RTC = 1; - public static final short SERVICE_TYPE_RTM = 2; - public static final short SERVICE_TYPE_STREAMING = 3; - public static final short SERVICE_TYPE_FPA = 4; public static final short SERVICE_TYPE_CHAT = 5; public String appCert = ""; @@ -122,15 +85,6 @@ public Service getService(short serviceType) { if (serviceType == SERVICE_TYPE_RTC) { return new ServiceRtc(); } - if (serviceType == SERVICE_TYPE_RTM) { - return new ServiceRtm(); - } - if (serviceType == SERVICE_TYPE_STREAMING) { - return new ServiceStreaming(); - } - if (serviceType == SERVICE_TYPE_FPA) { - return new ServiceFpa(); - } if (serviceType == SERVICE_TYPE_CHAT) { return new ServiceChat(); } @@ -194,14 +148,6 @@ public void addPrivilegeRtc(PrivilegeRtc privilege, int expire) { this.privileges.put(privilege.intValue, expire); } - public void addPrivilegeRtm(PrivilegeRtm privilege, int expire) { - this.privileges.put(privilege.intValue, expire); - } - - public void addPrivilegeFpa(PrivilegeFpa privilege, int expire) { - this.privileges.put(privilege.intValue, expire); - } - public void addPrivilegeChat(PrivilegeChat privilege, int expire) { this.privileges.put(privilege.intValue, expire); } @@ -256,71 +202,6 @@ public void unpack(ByteBuf byteBuf) { } } - public static class ServiceRtm extends Service { - public String userId; - - public ServiceRtm() { - this.type = SERVICE_TYPE_RTM; - } - - public ServiceRtm(String userId) { - this.type = SERVICE_TYPE_RTM; - this.userId = userId; - } - - public String getUserId() { - return this.userId; - } - - public ByteBuf pack(ByteBuf buf) { - return super.pack(buf).put(this.userId); - } - - public void unpack(ByteBuf byteBuf) { - super.unpack(byteBuf); - this.userId = byteBuf.readString(); - } - } - - public static class ServiceStreaming extends Service { - public String channelName; - public String uid; - - public ServiceStreaming() { - this.type = SERVICE_TYPE_STREAMING; - } - - public ServiceStreaming(String channelName, String uid) { - this.type = SERVICE_TYPE_STREAMING; - this.channelName = channelName; - this.uid = uid; - } - - public ByteBuf pack(ByteBuf buf) { - return super.pack(buf).put(this.channelName).put(this.uid); - } - - public void unpack(ByteBuf byteBuf) { - super.unpack(byteBuf); - this.channelName = byteBuf.readString(); - this.uid = byteBuf.readString(); - } - } - - public static class ServiceFpa extends Service { - public ServiceFpa() { - this.type = SERVICE_TYPE_FPA; - } - - public ByteBuf pack(ByteBuf buf) { - return super.pack(buf); - } - - public void unpack(ByteBuf byteBuf) { - super.unpack(byteBuf); - } - } - public static class ServiceChat extends Service { public String userId; diff --git a/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/media/FpaTokenBuilder.java b/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/media/FpaTokenBuilder.java deleted file mode 100644 index 443c9229..00000000 --- a/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/media/FpaTokenBuilder.java +++ /dev/null @@ -1,27 +0,0 @@ -package io.agora.media; - -public class FpaTokenBuilder { - /** - * Build the FPA token. - * - * @param appId: The App ID issued to you by Agora. Apply for a new App ID from - * Agora Dashboard if it is missing from your kit. See Get an App ID. - * @param appCertificate: Certificate of the application that you registered in - * the Agora Dashboard. See Get an App Certificate. - * @return The FPA token. - */ - public String buildToken(String appId, String appCertificate) { - AccessToken2 accessToken = new AccessToken2(appId, appCertificate, 24 * 3600); - AccessToken2.Service serviceFpa = new AccessToken2.ServiceFpa(); - - serviceFpa.addPrivilegeFpa(AccessToken2.PrivilegeFpa.PRIVILEGE_LOGIN, 0); - accessToken.addService(serviceFpa); - - try { - return accessToken.build(); - } catch (Exception e) { - e.printStackTrace(); - return ""; - } - } -} diff --git a/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/rtm/RtmTokenBuilder2.java b/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/rtm/RtmTokenBuilder2.java deleted file mode 100644 index dd7cba98..00000000 --- a/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/rtm/RtmTokenBuilder2.java +++ /dev/null @@ -1,33 +0,0 @@ -package io.agora.rtm; - -import io.agora.media.AccessToken2; - -public class RtmTokenBuilder2 { - - /** - * Build the RTM token. - * - * @param appId: The App ID issued to you by Agora. Apply for a new App ID from - * Agora Dashboard if it is missing from your kit. See Get an App ID. - * @param appCertificate: Certificate of the application that you registered in - * the Agora Dashboard. See Get an App Certificate. - * @param userId: The user's account, max length is 64 Bytes. - * @param expire: represented by the number of seconds elapsed since now. If, for example, you want to access the - * Agora Service within 10 minutes after the token is generated, set expireTimestamp as 600(seconds). - * @return The RTM token. - */ - public String buildToken(String appId, String appCertificate, String userId, int expire) { - AccessToken2 accessToken = new AccessToken2(appId, appCertificate, expire); - AccessToken2.Service serviceRtm = new AccessToken2.ServiceRtm(userId); - - serviceRtm.addPrivilegeRtm(AccessToken2.PrivilegeRtm.PRIVILEGE_LOGIN, expire); - accessToken.addService(serviceRtm); - - try { - return accessToken.build(); - } catch (Exception e) { - e.printStackTrace(); - return ""; - } - } -} diff --git a/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/sample/AccessTokenInspector.java b/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/sample/AccessTokenInspector.java index 80d2715a..0d16d60f 100644 --- a/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/sample/AccessTokenInspector.java +++ b/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/sample/AccessTokenInspector.java @@ -33,13 +33,6 @@ String toServiceStr(AccessToken2.Service service) { AccessToken2.ServiceRtc serviceRtc = (AccessToken2.ServiceRtc) service; return String.format("type:rtc, channel:%s, uid: %s, privileges: [%s]}", serviceRtc.getChannelName(), serviceRtc.getUid(), toRtcPrivileges(serviceRtc.getPrivileges())); - } else if (service.getServiceType() == AccessToken2.SERVICE_TYPE_RTM) { - AccessToken2.ServiceRtm serviceRtm = (AccessToken2.ServiceRtm) service; - return String.format("type:rtm, user_id:%s, privileges:[%s]", serviceRtm.getUserId(), - toRtmPrivileges(serviceRtm.getPrivileges())); - } else if (service.getServiceType() == AccessToken2.SERVICE_TYPE_STREAMING) { - AccessToken2.ServiceStreaming serviceStreaming = (AccessToken2.ServiceStreaming) service; - return String.format("type:streaming, privileges:[%s]", toStreamingPrivileges(serviceStreaming.getPrivileges())); } else if (service.getServiceType() == AccessToken2.SERVICE_TYPE_CHAT) { AccessToken2.ServiceChat serviceChat = (AccessToken2.ServiceChat) service; return String.format("type:chat, user_id:%s, privileges:[%s]", serviceChat.getUserId(), @@ -48,8 +41,6 @@ String toServiceStr(AccessToken2.Service service) { return "unknown"; } - - private String toRtcPrivileges(TreeMap privileges) { List privilegeStrList = new ArrayList<>(privileges.size()); if (privileges.containsKey(AccessToken2.PrivilegeRtc.PRIVILEGE_JOIN_CHANNEL.intValue)) { @@ -71,28 +62,6 @@ private String toRtcPrivileges(TreeMap privileges) { return String.join(",", privilegeStrList); } - private String toRtmPrivileges(TreeMap privileges) { - List privilegeStrList = new ArrayList<>(privileges.size()); - if (privileges.containsKey(AccessToken2.PrivilegeRtm.PRIVILEGE_LOGIN.intValue)) { - privilegeStrList.add(String.format("JOIN_LOGIN(%d)", - privileges.get(AccessToken2.PrivilegeRtm.PRIVILEGE_LOGIN.intValue))); - } - return String.join(",", privilegeStrList); - } - - private String toStreamingPrivileges(TreeMap privileges) { - List privilegeStrList = new ArrayList<>(privileges.size()); - if (privileges.containsKey(AccessToken2.PrivilegeStreaming.PRIVILEGE_PUBLISH_MIX_STREAM.intValue)) { - privilegeStrList.add(String.format("PUBLISH_MIX_STREAM(%d)", - privileges.get(AccessToken2.PrivilegeStreaming.PRIVILEGE_PUBLISH_MIX_STREAM.intValue))); - } - if (privileges.containsKey(AccessToken2.PrivilegeStreaming.PRIVILEGE_PUBLISH_RAW_STREAM.intValue)) { - privilegeStrList.add(String.format("PUBLISH_RAW_STREAM(%d)", - privileges.get(AccessToken2.PrivilegeStreaming.PRIVILEGE_PUBLISH_RAW_STREAM.intValue))); - } - return String.join(",", privilegeStrList); - } - private String toChatPrivileges(TreeMap privileges) { List privilegeStrList = new ArrayList<>(privileges.size()); if (privileges.containsKey(AccessToken2.PrivilegeChat.PRIVILEGE_CHAT_USER.intValue)) { diff --git a/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/sample/FpaTokenBuilderSample.java b/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/sample/FpaTokenBuilderSample.java deleted file mode 100644 index 24973fb9..00000000 --- a/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/sample/FpaTokenBuilderSample.java +++ /dev/null @@ -1,14 +0,0 @@ -package io.agora.sample; - -import io.agora.media.FpaTokenBuilder; - -public class FpaTokenBuilderSample { - static String appId = "970CA35de60c44645bbae8a215061b33"; - static String appCertificate = "5CFd2fd1755d40ecb72977518be15d3b"; - - public static void main(String[] args) { - FpaTokenBuilder token = new FpaTokenBuilder(); - String result = token.buildToken(appId, appCertificate); - System.out.println("Token with FPA service: " + result); - } -} diff --git a/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/sample/RtmTokenBuilder2Sample.java b/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/sample/RtmTokenBuilder2Sample.java deleted file mode 100644 index b50c236d..00000000 --- a/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/sample/RtmTokenBuilder2Sample.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.agora.sample; - -import io.agora.rtm.RtmTokenBuilder2; - -public class RtmTokenBuilder2Sample { - private static String appId = "970CA35de60c44645bbae8a215061b33"; - private static String appCertificate = "5CFd2fd1755d40ecb72977518be15d3b"; - private static String userId = "test_user_id"; - private static int expirationInSeconds = 3600; - - public static void main(String[] args) { - RtmTokenBuilder2 token = new RtmTokenBuilder2(); - String result = token.buildToken(appId, appCertificate, userId, expirationInSeconds); - System.out.println("Rtm Token: " + result); - } -} diff --git a/DynamicKey/AgoraDynamicKey/java/src/test/java/io/agora/media/AccessToken2Test.java b/DynamicKey/AgoraDynamicKey/java/src/test/java/io/agora/media/AccessToken2Test.java index 5daf77de..3157b243 100644 --- a/DynamicKey/AgoraDynamicKey/java/src/test/java/io/agora/media/AccessToken2Test.java +++ b/DynamicKey/AgoraDynamicKey/java/src/test/java/io/agora/media/AccessToken2Test.java @@ -82,21 +82,6 @@ public void build_ServiceRtc_account() throws Exception { assertEquals("007eJxTYBBbsMMnKq7p9Hf/HcIX5kce9b518kCiQgSr5Zrp4X1Tu6UUGCzNDZwdjU1TUs0Mkk1MzExMk5ISUy0SjQxNDcwMk4yN3b8IMEQwMTAwMoAwBIL4CgzmKeZGxmamqUmWFsYmFqbGluapxqnGaZYpJmYGSSkpiVwMRhYWRsYmhkbmxgDCaiTj", token); } - @Test - public void build_ServiceRtm() throws Exception { - AccessToken2 accessToken = new AccessToken2(appId, appCertificate, expire); - accessToken.issueTs = issueTs; - accessToken.salt = salt; - - AccessToken2.ServiceRtm serviceRtm = new AccessToken2.ServiceRtm(userId); - serviceRtm.addPrivilegeRtm(AccessToken2.PrivilegeRtm.PRIVILEGE_LOGIN, expire); - - accessToken.addService(serviceRtm); - String expected = "007eJxTYOCdJftjyTM2zxW6Xhm/5T0j5LdcUt/xYVt48fb5Mp3PX9coMFiaGzg7GpumpJoZJJuYmJmYJiUlplokGhmaGpgZJhkbu38RYIhgYmBgZABhJiBmBPM5GUpSi0viS4tTiwBZVh6A"; - - assertEquals(expected, accessToken.build()); - } - @Test public void build_ServiceChat_userToken() throws Exception { AccessToken2 accessToken = new AccessToken2(appId, appCertificate, expire); @@ -140,19 +125,14 @@ public void build_multi_service() throws Exception { serviceRtc.addPrivilegeRtc(AccessToken2.PrivilegeRtc.PRIVILEGE_PUBLISH_DATA_STREAM, expire); accessToken.addService(serviceRtc); - AccessToken2.ServiceRtm serviceRtm = new AccessToken2.ServiceRtm(userId); - serviceRtm.addPrivilegeRtm(AccessToken2.PrivilegeRtm.PRIVILEGE_LOGIN, expire); - accessToken.addService(serviceRtm); - AccessToken2.ServiceChat serviceChat = new AccessToken2.ServiceChat(uid); serviceChat.addPrivilegeChat(AccessToken2.PrivilegeChat.PRIVILEGE_CHAT_USER, expire); accessToken.addService(serviceChat); assertEquals(channelName, serviceRtc.channelName); assertEquals(uid, serviceRtc.uid); - assertEquals(userId, serviceRtm.userId); - String expected = "007eJxTYPg19dsX8xO2Nys/bpSeoH/0j9CvSs1JWib9291PKC53l85UYLA0N3B2NDZNSTUzSDYxMTMxTUpKTLVINDI0NTAzTDI2dv8iwBDBxMDAyMDAwAwkWYAYxGcCk8xgkgVMKjCYp5gbGZuZpiZZWhibWJgaW5qnGqcap1mmmJgZJKWkJHIxGFlYGBmbGBqZGzMBzYGYxMlQklpcEl9anFrEChdEVgoAw6ct/Q=="; + String expected = "007eJxTYLh59YaCUHZeRLXJsRSTDvfv2SV2uddsV+m05Vx5HaP59bMCg6W5gbOjsWlKqplBsomJmYlpUlJiqkWikaGpgZlhkrGx+xcBhggmBgZGBgYGJiDJAsQgPhOYZAaTLGBSgcE8xdzI2Mw0NcnSwtjEwtTY0jzVONU4zTLFxMwgKSUlkYvByMLCyNjE0MjcmBVoDsQkZFEAlCcpOg=="; String token = accessToken.build(); assertEquals(expected, token); } @@ -174,9 +154,9 @@ public void parse_TokenRtc() { } @Test - public void parse_TokenRtc_Rtm_MultiService() { + public void parse_Token_MultiService() { AccessToken2 accessToken = new AccessToken2(); - boolean res = accessToken.parse("007eJxTYOAQsrQ5s3TfH+1tvy8zZZ46EpCc0V43JXdGd2jS8porKo4KDJbmBs6OxqYpqWYGySYmZiamSUmJqRaJRoamBmaGScbG7l8EGCKYGBgYGRgYmIAkCxCD+ExgkhlMsoBJBQbzFHMjYzPT1CRLC2MTC1NjS/NU41TjNMsUEzODpJSURC4GIwsLI2MTQyNzY5BZEJM4GUpSi0viS4tTiwAipyp4"); + boolean res = accessToken.parse("007eJxTYLh59YaCUHZeRLXJsRSTDvfv2SV2uddsV+m05Vx5HaP59bMCg6W5gbOjsWlKqplBsomJmYlpUlJiqkWikaGpgZlhkrGx+xcBhggmBgZGBgYGJiDJAsQgPhOYZAaTLGBSgcE8xdzI2Mw0NcnSwtjEwtTY0jzVONU4zTLFxMwgKSUlkYvByMLCyNjE0MjcmBVoDsQkZFEAlCcpOg=="); assertTrue(res); assertEquals(appId, accessToken.appId); assertEquals(expire, accessToken.expire); @@ -185,24 +165,8 @@ public void parse_TokenRtc_Rtm_MultiService() { assertEquals(2, accessToken.services.size()); assertEquals(channelName, ((AccessToken2.ServiceRtc)accessToken.services.get(AccessToken2.SERVICE_TYPE_RTC)).getChannelName()); assertEquals(uid, ((AccessToken2.ServiceRtc)accessToken.services.get(AccessToken2.SERVICE_TYPE_RTC)).getUid()); - assertEquals(userId, ((AccessToken2.ServiceRtm)accessToken.services.get(AccessToken2.SERVICE_TYPE_RTM)).getUserId()); assertEquals(expire, (int) accessToken.services.get(AccessToken2.SERVICE_TYPE_RTC).getPrivileges().get(AccessToken2.PrivilegeRtc.PRIVILEGE_JOIN_CHANNEL.intValue)); assertEquals(expire, (int) accessToken.services.get(AccessToken2.SERVICE_TYPE_RTC).getPrivileges().getOrDefault(AccessToken2.PrivilegeRtc.PRIVILEGE_PUBLISH_AUDIO_STREAM.intValue, 0)); - assertEquals(expire, (int)accessToken.services.get(AccessToken2.SERVICE_TYPE_RTM).getPrivileges().get(AccessToken2.PrivilegeRtm.PRIVILEGE_LOGIN.intValue)); - } - - @Test - public void parse_TokenRtm() { - AccessToken2 accessToken = new AccessToken2(); - boolean res = accessToken.parse("007eJxSYOCdJftjyTM2zxW6Xhm/5T0j5LdcUt/xYVt48fb5Mp3PX9coMFiaGzg7GpumpJoZJJuYmJmYJiUlplokGhmaGpgZJhkbu38RYIhgYmBgZABhJgZGBkYwn5OhJLW4JL60OLUIEAAA//9ZVh6A"); - assertTrue(res); - assertEquals(appId, accessToken.appId); - assertEquals(expire, accessToken.expire); - assertEquals(issueTs, accessToken.issueTs); - assertEquals(salt, accessToken.salt); - assertEquals(1, accessToken.services.size()); - assertEquals(userId, ((AccessToken2.ServiceRtm)accessToken.services.get(AccessToken2.SERVICE_TYPE_RTM)).getUserId()); - assertEquals(expire, (int)accessToken.services.get(AccessToken2.SERVICE_TYPE_RTM).getPrivileges().get(AccessToken2.PrivilegeRtm.PRIVILEGE_LOGIN.intValue)); } @Test diff --git a/DynamicKey/AgoraDynamicKey/java/src/test/java/io/agora/media/FpaTokenBuilderTest.java b/DynamicKey/AgoraDynamicKey/java/src/test/java/io/agora/media/FpaTokenBuilderTest.java deleted file mode 100644 index 11bc4128..00000000 --- a/DynamicKey/AgoraDynamicKey/java/src/test/java/io/agora/media/FpaTokenBuilderTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package io.agora.media; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class FpaTokenBuilderTest { - private String appId = "970CA35de60c44645bbae8a215061b33"; - private String appCertificate = "5CFd2fd1755d40ecb72977518be15d3b"; - private int expire = 24 * 3600; - - @Test - public void buildToken() { - FpaTokenBuilder fpaTokenBuilder = new FpaTokenBuilder(); - String token = fpaTokenBuilder.buildToken(appId, appCertificate); - AccessToken2 accessToken = new AccessToken2(); - accessToken.parse(token); - - assertEquals(appId, accessToken.appId); - assertEquals(expire, accessToken.expire); - assertEquals(0, (int) accessToken.services.get(AccessToken2.SERVICE_TYPE_FPA).getPrivileges().get(AccessToken2.PrivilegeFpa.PRIVILEGE_LOGIN.intValue)); - } -} \ No newline at end of file diff --git a/DynamicKey/AgoraDynamicKey/java/src/test/java/io/agora/rtm/RtmTokenBuilder2Test.java b/DynamicKey/AgoraDynamicKey/java/src/test/java/io/agora/rtm/RtmTokenBuilder2Test.java deleted file mode 100644 index 76bbfb37..00000000 --- a/DynamicKey/AgoraDynamicKey/java/src/test/java/io/agora/rtm/RtmTokenBuilder2Test.java +++ /dev/null @@ -1,26 +0,0 @@ -package io.agora.rtm; - -import io.agora.media.AccessToken2; -import org.junit.Test; - -import static org.junit.Assert.*; - -public class RtmTokenBuilder2Test { - private String appId = "970CA35de60c44645bbae8a215061b33"; - private String appCertificate = "5CFd2fd1755d40ecb72977518be15d3b"; - private String userId = "test_user"; - private int expire = 600; - - @Test - public void buildToken() { - RtmTokenBuilder2 rtmTokenBuilder = new RtmTokenBuilder2(); - String token = rtmTokenBuilder.buildToken(appId, appCertificate, userId, expire); - AccessToken2 accessToken = new AccessToken2(); - accessToken.parse(token); - - assertEquals(appId, accessToken.appId); - assertEquals(expire, accessToken.expire); - assertEquals(userId, ((AccessToken2.ServiceRtm)accessToken.services.get(AccessToken2.SERVICE_TYPE_RTM)).getUserId()); - assertEquals(expire, (int)accessToken.services.get(AccessToken2.SERVICE_TYPE_RTM).getPrivileges().get(AccessToken2.PrivilegeRtm.PRIVILEGE_LOGIN.intValue)); - } -} \ No newline at end of file From fa67e5ccec34e23cee993032474232f73e2ca6a5 Mon Sep 17 00:00:00 2001 From: lixinhui Date: Tue, 21 Dec 2021 21:20:14 +0800 Subject: [PATCH 10/21] just support Rtc/Chat service --- .../AgoraDynamicKey/ruby/lib/dynamic_key2.rb | 2 - .../ruby/lib/dynamic_key2/access_token.rb | 60 +++---------------- .../lib/dynamic_key2/fpa_token_builder.rb | 20 ------- .../lib/dynamic_key2/rtm_token_builder.rb | 26 -------- .../ruby/sample/fpa_token_builder_sample.rb | 7 --- .../test/dynamic_key2/access_token_spec.rb | 28 ++------- .../dynamic_key2/fpa_token_builder_spec.rb | 21 ------- .../dynamic_key2/rtm_token_builder_spec.rb | 23 ------- 8 files changed, 15 insertions(+), 172 deletions(-) delete mode 100644 DynamicKey/AgoraDynamicKey/ruby/lib/dynamic_key2/fpa_token_builder.rb delete mode 100644 DynamicKey/AgoraDynamicKey/ruby/lib/dynamic_key2/rtm_token_builder.rb delete mode 100644 DynamicKey/AgoraDynamicKey/ruby/sample/fpa_token_builder_sample.rb delete mode 100644 DynamicKey/AgoraDynamicKey/ruby/test/dynamic_key2/fpa_token_builder_spec.rb delete mode 100644 DynamicKey/AgoraDynamicKey/ruby/test/dynamic_key2/rtm_token_builder_spec.rb diff --git a/DynamicKey/AgoraDynamicKey/ruby/lib/dynamic_key2.rb b/DynamicKey/AgoraDynamicKey/ruby/lib/dynamic_key2.rb index 2b0f3916..9c9534cc 100644 --- a/DynamicKey/AgoraDynamicKey/ruby/lib/dynamic_key2.rb +++ b/DynamicKey/AgoraDynamicKey/ruby/lib/dynamic_key2.rb @@ -1,7 +1,5 @@ require_relative 'dynamic_key2/access_token' require_relative 'dynamic_key2/rtc_token_builder' -require_relative 'dynamic_key2/rtm_token_builder' -require_relative 'dynamic_key2/fpa_token_builder' require_relative 'dynamic_key2/util' module AgoraDynamicKey2 diff --git a/DynamicKey/AgoraDynamicKey/ruby/lib/dynamic_key2/access_token.rb b/DynamicKey/AgoraDynamicKey/ruby/lib/dynamic_key2/access_token.rb index ef2d4877..38e7dd56 100644 --- a/DynamicKey/AgoraDynamicKey/ruby/lib/dynamic_key2/access_token.rb +++ b/DynamicKey/AgoraDynamicKey/ruby/lib/dynamic_key2/access_token.rb @@ -56,77 +56,35 @@ def unpack(data) end end - class ServiceRtm < Service - attr_accessor :user_id + class ServiceChat < Service + attr_accessor :uid - SERVICE_TYPE = 2 - PRIVILEGE_JOIN_LOGIN = 1 + SERVICE_TYPE = 5 + PRIVILEGE_USER = 1 + PRIVILEGE_APP = 2 - def initialize(user_id = '') + def initialize(uid = '') super(SERVICE_TYPE) - @user_id = user_id - end - - def pack - super() + Util.pack_string(@user_id) - end - - def unpack(data) - _, data = super(data) - @user_id, data = Util.unpack_string(data) - end - end - - class ServiceStreaming < Service - attr_accessor :channel_name, :uid - - SERVICE_TYPE = 3 - PRIVILEGE_PUBLISH_MIX_STREAM = 1 - PRIVILEGE_PUBLISH_RAW_STREAM = 2 - - def initialize(channel_name = '', uid = '') - super(SERVICE_TYPE) - @channel_name = channel_name @uid = fetch_uid(uid) end def pack - super() + Util.pack_string(@channel_name) + Util.pack_string(@uid) + super() + Util.pack_string(@uid) end def unpack(data) _, data = super(data) - @channel_name, data = Util.unpack_string(data) @uid, data = Util.unpack_string(data) end end - class ServiceFpa < Service - SERVICE_TYPE = 4 - PRIVILEGE_LOGIN = 1 - - def initialize() - super(SERVICE_TYPE) - end - - def pack - super() - end - - def unpack(data) - _, data = super(data) - end - end - class AccessToken attr_accessor :app_cert, :app_id, :expire, :issue_ts, :salt, :services VERSION = '007'.freeze VERSION_LENGTH = 3 - SERVICES = {ServiceRtc::SERVICE_TYPE => ServiceRtc, - ServiceRtm::SERVICE_TYPE => ServiceRtm, - ServiceStreaming::SERVICE_TYPE => ServiceStreaming, - ServiceFpa::SERVICE_TYPE => ServiceFpa}.freeze + SERVICES = { ServiceRtc::SERVICE_TYPE => ServiceRtc, + ServiceChat::SERVICE_TYPE => ServiceChat }.freeze def initialize(app_id = '', app_cert = '', expire = 900) @app_id = app_id diff --git a/DynamicKey/AgoraDynamicKey/ruby/lib/dynamic_key2/fpa_token_builder.rb b/DynamicKey/AgoraDynamicKey/ruby/lib/dynamic_key2/fpa_token_builder.rb deleted file mode 100644 index d98afda4..00000000 --- a/DynamicKey/AgoraDynamicKey/ruby/lib/dynamic_key2/fpa_token_builder.rb +++ /dev/null @@ -1,20 +0,0 @@ -module AgoraDynamicKey2 - class FpaTokenBuilder - # Build the FPA token. - # - # @param app_id The App ID issued to you by Agora. Apply for a new App ID from Agora Dashboard if it is missing - # from your kit. See Get an App ID. - # @param app_certificate Certificate of the application that you registered in the Agora Dashboard. - # See Get an App Certificate. - # @return The FPA token. - def self.build_token(app_id, app_certificate) - access_token = AgoraDynamicKey2::AccessToken.new(app_id, app_certificate, 24 * 3600) - - service_fpa = AgoraDynamicKey2::ServiceFpa.new - service_fpa.add_privilege(AgoraDynamicKey2::ServiceFpa::PRIVILEGE_LOGIN, 0) - access_token.add_service(service_fpa) - - access_token.build - end - end -end diff --git a/DynamicKey/AgoraDynamicKey/ruby/lib/dynamic_key2/rtm_token_builder.rb b/DynamicKey/AgoraDynamicKey/ruby/lib/dynamic_key2/rtm_token_builder.rb deleted file mode 100644 index 070b1867..00000000 --- a/DynamicKey/AgoraDynamicKey/ruby/lib/dynamic_key2/rtm_token_builder.rb +++ /dev/null @@ -1,26 +0,0 @@ -module AgoraDynamicKey2 - class RtmTokenBuilder - ROLE_PUBLISHER = 1 - ROLE_SUBSCRIBER = 2 - - # Build the RTM token. - # - # @param app_id: The App ID issued to you by Agora. Apply for a new App ID from - # Agora Dashboard if it is missing from your kit. See Get an App ID. - # @param app_certificate: Certificate of the application that you registered in - # the Agora Dashboard. See Get an App Certificate. - # @param user_id: The user's account, max length is 64 Bytes. - # @param expire: represented by the number of seconds elapsed since now. If, for example, you want to access the - # Agora Service within 10 minutes after the token is generated, set expireTimestamp as 600(seconds). - # @return The RTM token. - def self.build_token(app_id, app_certificate, user_id, expire) - access_token = AgoraDynamicKey2::AccessToken.new(app_id, app_certificate, expire) - service_rtm = AgoraDynamicKey2::ServiceRtm.new(user_id) - - service_rtm.add_privilege(AgoraDynamicKey2::ServiceRtm::PRIVILEGE_JOIN_LOGIN, expire) - access_token.add_service(service_rtm) - access_token.build - end - end -end - diff --git a/DynamicKey/AgoraDynamicKey/ruby/sample/fpa_token_builder_sample.rb b/DynamicKey/AgoraDynamicKey/ruby/sample/fpa_token_builder_sample.rb deleted file mode 100644 index f8fa2c52..00000000 --- a/DynamicKey/AgoraDynamicKey/ruby/sample/fpa_token_builder_sample.rb +++ /dev/null @@ -1,7 +0,0 @@ -require_relative '../lib/dynamic_key2' - -app_id = '970CA35de60c44645bbae8a215061b33' -app_certificate = '5CFd2fd1755d40ecb72977518be15d3b' - -token = AgoraDynamicKey2::FpaTokenBuilder.build_token(app_id, app_certificate) -puts "Token with FPA service: #{token}" diff --git a/DynamicKey/AgoraDynamicKey/ruby/test/dynamic_key2/access_token_spec.rb b/DynamicKey/AgoraDynamicKey/ruby/test/dynamic_key2/access_token_spec.rb index 923ff826..34f36318 100644 --- a/DynamicKey/AgoraDynamicKey/ruby/test/dynamic_key2/access_token_spec.rb +++ b/DynamicKey/AgoraDynamicKey/ruby/test/dynamic_key2/access_token_spec.rb @@ -63,12 +63,12 @@ service_rtc.add_privilege(AgoraDynamicKey2::ServiceRtc::PRIVILEGE_PUBLISH_DATA_STREAM, expire) access_token.add_service(service_rtc) - service_rtm = AgoraDynamicKey2::ServiceRtm.new(user_id) - service_rtm.add_privilege(AgoraDynamicKey2::ServiceRtm::PRIVILEGE_JOIN_LOGIN, expire) - access_token.add_service(service_rtm) + service_chat = AgoraDynamicKey2::ServiceChat.new(uid_s) + service_chat.add_privilege(AgoraDynamicKey2::ServiceChat::PRIVILEGE_USER, expire) + access_token.add_service(service_chat) token = access_token.build - expect(token).to eq('007eJxTYOAQsrQ5s3TfH+1tvy8zZZ46EpCc0V43JXdGd2jS8porKo4KDJbmBs6OxqYpqWYGySYmZiamSUmJqRaJRoamBmaGScbG7l8EGCKYGBgYGRgYmIAkCxCD+ExgkhlMsoBJBQbzFHMjYzPT1CRLC2MTC1NjS/NU41TjNMsUEzODpJSURC4GIwsLI2MTQyNzY5BZEJM4GUpSi0viS4tTiwAipyp4') + expect(token).to eq('007eJxTYLh59YaCUHZeRLXJsRSTDvfv2SV2uddsV+m05Vx5HaP59bMCg6W5gbOjsWlKqplBsomJmYlpUlJiqkWikaGpgZlhkrGx+xcBhggmBgZGBgYGJiDJAsQgPhOYZAaTLGBSgcE8xdzI2Mw0NcnSwtjEwtTY0jzVONU4zTLFxMwgKSUlkYvByMLCyNjE0MjcmBVoDsQkZFEAlCcpOg==') end it 'test_parse_TokenRtc' do @@ -90,9 +90,9 @@ expect(access_token.services[AgoraDynamicKey2::ServiceRtc::SERVICE_TYPE].privileges[AgoraDynamicKey2::ServiceRtc::PRIVILEGE_PUBLISH_DATA_STREAM]).to eq(nil) end - it 'test_parse_TokenRtc_Rtm_MultiService' do + it 'test_parse_Token_MultiService' do access_token = AgoraDynamicKey2::AccessToken.new - res = access_token.parse('007eJxTYOAQsrQ5s3TfH+1tvy8zZZ46EpCc0V43JXdGd2jS8porKo4KDJbmBs6OxqYpqWYGySYmZiamSUmJqRaJRoamBmaGScbG7l8EGCKYGBgYGRgYmIAkCxCD+ExgkhlMsoBJBQbzFHMjYzPT1CRLC2MTC1NjS/NU41TjNMsUEzODpJSURC4GIwsLI2MTQyNzY5BZEJM4GUpSi0viS4tTiwAipyp4') + res = access_token.parse('007eJxTYLh59YaCUHZeRLXJsRSTDvfv2SV2uddsV+m05Vx5HaP59bMCg6W5gbOjsWlKqplBsomJmYlpUlJiqkWikaGpgZlhkrGx+xcBhggmBgZGBgYGJiDJAsQgPhOYZAaTLGBSgcE8xdzI2Mw0NcnSwtjEwtTY0jzVONU4zTLFxMwgKSUlkYvByMLCyNjE0MjcmBVoDsQkZFEAlCcpOg==') expect(res).to eq(true) expect(access_token.app_id).to eq(app_id) @@ -103,26 +103,10 @@ expect(access_token.services[AgoraDynamicKey2::ServiceRtc::SERVICE_TYPE].channel_name).to eq(channel_name) expect(access_token.services[AgoraDynamicKey2::ServiceRtc::SERVICE_TYPE].uid).to eq(uid_s) expect(access_token.services[AgoraDynamicKey2::ServiceRtc::SERVICE_TYPE].type).to eq(AgoraDynamicKey2::ServiceRtc::SERVICE_TYPE) - expect(access_token.services[AgoraDynamicKey2::ServiceRtm::SERVICE_TYPE].user_id).to eq(user_id) expect(access_token.services[AgoraDynamicKey2::ServiceRtc::SERVICE_TYPE].privileges[AgoraDynamicKey2::ServiceRtc::PRIVILEGE_JOIN_CHANNEL]).to eq(expire) expect(access_token.services[AgoraDynamicKey2::ServiceRtc::SERVICE_TYPE].privileges[AgoraDynamicKey2::ServiceRtc::PRIVILEGE_PUBLISH_AUDIO_STREAM]).to eq(expire) expect(access_token.services[AgoraDynamicKey2::ServiceRtc::SERVICE_TYPE].privileges[AgoraDynamicKey2::ServiceRtc::PRIVILEGE_PUBLISH_VIDEO_STREAM]).to eq(expire) expect(access_token.services[AgoraDynamicKey2::ServiceRtc::SERVICE_TYPE].privileges[AgoraDynamicKey2::ServiceRtc::PRIVILEGE_PUBLISH_DATA_STREAM]).to eq(expire) - expect(access_token.services[AgoraDynamicKey2::ServiceRtm::SERVICE_TYPE].privileges[AgoraDynamicKey2::ServiceRtm::PRIVILEGE_JOIN_LOGIN]).to eq(expire) - end - - it 'test_parse_TokenRtm' do - access_token = AgoraDynamicKey2::AccessToken.new - res = access_token.parse('007eJxSYOCdJftjyTM2zxW6Xhm/5T0j5LdcUt/xYVt48fb5Mp3PX9coMFiaGzg7GpumpJoZJJuYmJmYJiUlplokGhmaGpgZJhkbu38RYIhgYmBgZABhJgZGBkYwn5OhJLW4JL60OLUIEAAA//9ZVh6A') - - expect(res).to eq(true) - expect(access_token.app_id).to eq(app_id) - expect(access_token.expire).to eq(expire) - expect(access_token.issue_ts).to eq(issue_ts) - expect(access_token.salt).to eq(salt) - expect(access_token.services.size).to eq(1) - expect(access_token.services[AgoraDynamicKey2::ServiceRtm::SERVICE_TYPE].type).to eq(AgoraDynamicKey2::ServiceRtm::SERVICE_TYPE) - expect(access_token.services[AgoraDynamicKey2::ServiceRtm::SERVICE_TYPE].privileges[AgoraDynamicKey2::ServiceRtm::PRIVILEGE_JOIN_LOGIN]).to eq(expire) end it 'test_Service_fetch_uid' do diff --git a/DynamicKey/AgoraDynamicKey/ruby/test/dynamic_key2/fpa_token_builder_spec.rb b/DynamicKey/AgoraDynamicKey/ruby/test/dynamic_key2/fpa_token_builder_spec.rb deleted file mode 100644 index 559c2309..00000000 --- a/DynamicKey/AgoraDynamicKey/ruby/test/dynamic_key2/fpa_token_builder_spec.rb +++ /dev/null @@ -1,21 +0,0 @@ -require 'rspec' -require_relative '../../lib/dynamic_key2' - -describe 'AgoraDynamicKey2::FpaTokenBuilder' do - let(:app_id) { '970CA35de60c44645bbae8a215061b33' } - let(:app_certificate) { '5CFd2fd1755d40ecb72977518be15d3b' } - let(:expire) { 24 * 3600 } - - it 'test_build_token' do - token = AgoraDynamicKey2::FpaTokenBuilder.build_token(app_id, app_certificate) - access_token = AgoraDynamicKey2::AccessToken.new - res = access_token.parse(token) - - expect(res).to eq(true) - expect(access_token.app_id).to eq(app_id) - expect(access_token.expire).to eq(expire) - expect(access_token.services.size).to eq(1) - expect(access_token.services[AgoraDynamicKey2::ServiceFpa::SERVICE_TYPE].type).to eq(AgoraDynamicKey2::ServiceFpa::SERVICE_TYPE) - expect(access_token.services[AgoraDynamicKey2::ServiceFpa::SERVICE_TYPE].privileges[AgoraDynamicKey2::ServiceFpa::PRIVILEGE_LOGIN]).to eq(0) - end -end diff --git a/DynamicKey/AgoraDynamicKey/ruby/test/dynamic_key2/rtm_token_builder_spec.rb b/DynamicKey/AgoraDynamicKey/ruby/test/dynamic_key2/rtm_token_builder_spec.rb deleted file mode 100644 index d779c25c..00000000 --- a/DynamicKey/AgoraDynamicKey/ruby/test/dynamic_key2/rtm_token_builder_spec.rb +++ /dev/null @@ -1,23 +0,0 @@ -require 'rspec' -require_relative '../../lib/dynamic_key2' - -describe 'AgoraDynamicKey2::RtmTokenBuilder' do - let(:app_id) { '970CA35de60c44645bbae8a215061b33' } - let(:app_certificate) { '5CFd2fd1755d40ecb72977518be15d3b' } - let(:expire) { 600 } - let(:user_id) { 'test_user' } - - it 'test_build_token' do - token = AgoraDynamicKey2::RtmTokenBuilder.build_token(app_id, app_certificate, user_id, expire) - access_token = AgoraDynamicKey2::AccessToken.new - res = access_token.parse(token) - - expect(res).to eq(true) - expect(access_token.app_id).to eq(app_id) - expect(access_token.expire).to eq(expire) - expect(access_token.services.size).to eq(1) - expect(access_token.services[AgoraDynamicKey2::ServiceRtm::SERVICE_TYPE].user_id).to eq(user_id) - expect(access_token.services[AgoraDynamicKey2::ServiceRtm::SERVICE_TYPE].type).to eq(AgoraDynamicKey2::ServiceRtm::SERVICE_TYPE) - expect(access_token.services[AgoraDynamicKey2::ServiceRtm::SERVICE_TYPE].privileges[AgoraDynamicKey2::ServiceRtm::PRIVILEGE_JOIN_LOGIN]).to eq(expire) - end -end From fe46f98a4bb85697436ae460afd367f643b70c3a Mon Sep 17 00:00:00 2001 From: aldam70 Date: Wed, 29 Dec 2021 12:32:49 +0800 Subject: [PATCH 11/21] new param for token life cycle control in access token 2 --- .../cpp/sample/RtcTokenBuilder2Sample.cpp | 4 +- .../cpp/src/RtcTokenBuilder2.h | 42 +++++++++++-------- 2 files changed, 26 insertions(+), 20 deletions(-) diff --git a/DynamicKey/AgoraDynamicKey/cpp/sample/RtcTokenBuilder2Sample.cpp b/DynamicKey/AgoraDynamicKey/cpp/sample/RtcTokenBuilder2Sample.cpp index efa5fc68..df4af413 100644 --- a/DynamicKey/AgoraDynamicKey/cpp/sample/RtcTokenBuilder2Sample.cpp +++ b/DynamicKey/AgoraDynamicKey/cpp/sample/RtcTokenBuilder2Sample.cpp @@ -24,12 +24,12 @@ int main(int argc, char const *argv[]) { std::string result; result = RtcTokenBuilder2::BuildTokenWithUid( app_id, app_certificate, channel_name, uid, UserRole::kRolePublisher, - privilege_expiration_in_seconds); + token_expiration_in_seconds, privilege_expiration_in_seconds); std::cout << "Token With Int Uid:" << result << std::endl; result = RtcTokenBuilder2::BuildTokenWithUserAccount( app_id, app_certificate, channel_name, account, UserRole::kRolePublisher, - privilege_expiration_in_seconds); + token_expiration_in_seconds, privilege_expiration_in_seconds); std::cout << "Token With UserAccount:" << result << std::endl; result = RtcTokenBuilder2::BuildTokenWithUid( diff --git a/DynamicKey/AgoraDynamicKey/cpp/src/RtcTokenBuilder2.h b/DynamicKey/AgoraDynamicKey/cpp/src/RtcTokenBuilder2.h index c4e1aed3..04f065b0 100644 --- a/DynamicKey/AgoraDynamicKey/cpp/src/RtcTokenBuilder2.h +++ b/DynamicKey/AgoraDynamicKey/cpp/src/RtcTokenBuilder2.h @@ -57,17 +57,21 @@ class RtcTokenBuilder2 { In order for this role to take effect, please contact our support team to enable authentication for Hosting-in for you. Otherwise, Role_Subscriber still has the same privileges as Role_Publisher. - @param expire represented by the number of seconds elapsed since now. If, for - example, you want to access the Agora Service within 10 minutes after the - token is generated (both for token life cycle and privilege life cycle), - set expireTimestamp as 600(seconds). + @param token_expire represented by the number of seconds elapsed since now. If, + for example, you want to access the Agora Service within 10 minutes after the + token is generated, set token_expire as 600(seconds). + @param privilege_expire represented by the number of seconds elapsed since now. If, for + example, you want to enable your privilege for 10 minutes, set privilege_expire + as 600(seconds). @return The new Token. */ + static std::string BuildTokenWithUid(const std::string& app_id, const std::string& app_certificate, const std::string& channel_name, uint32_t uid, UserRole role, - uint32_t expire = 0); + uint32_t token_expire, + uint32_t privilege_expire = 0); /** Builds an RTC token using a string userAccount. @@ -94,16 +98,18 @@ class RtcTokenBuilder2 { In order for this role to take effect, please contact our support team to enable authentication for Hosting-in for you. Otherwise, Role_Subscriber still has the same privileges as Role_Publisher. - @param expire represented by the number of seconds elapsed since now. If, for - example, you want to access the Agora Service within 10 minutes after the - token is generated, (both for token life cycle and privilege life cycle), - set expireTimestamp as 600(seconds). + @param token_expire represented by the number of seconds elapsed since now. If, + for example, you want to access the Agora Service within 10 minutes after the + token is generated, set token_expire as 600(seconds). + @param privilege_expire represented by the number of seconds elapsed since now. If, for + example, you want to enable your privilege for 10 minutes, set privilege_expire + as 600(seconds). @return The new Token. */ static std::string BuildTokenWithUserAccount( const std::string& app_id, const std::string& app_certificate, const std::string& channel_name, const std::string& user_account, - UserRole role, uint32_t expire = 0); + UserRole role, uint32_t token_expire, uint32_t privilege_expire = 0); /** * Generates a RTC token with specified privileges. @@ -214,29 +220,29 @@ class RtcTokenBuilder2 { inline std::string RtcTokenBuilder2::BuildTokenWithUid( const std::string& app_id, const std::string& app_certificate, const std::string& channel_name, uint32_t uid, UserRole role, - uint32_t expire) { + uint32_t token_expire, uint32_t privilege_expire) { std::string account; if (uid != 0) { account = std::to_string(uid); } return RtcTokenBuilder2::BuildTokenWithUserAccount( - app_id, app_certificate, channel_name, account, role, expire); + app_id, app_certificate, channel_name, account, role, token_expire, privilege_expire); } inline std::string RtcTokenBuilder2::BuildTokenWithUserAccount( const std::string& app_id, const std::string& app_certificate, const std::string& channel_name, const std::string& user_account, - UserRole role, uint32_t expire) { + UserRole role, uint32_t token_expire, uint32_t privilege_expire) { std::unique_ptr service( new ServiceRtc(channel_name, user_account)); - service->AddPrivilege(ServiceRtc::kPrivilegeJoinChannel, expire); + service->AddPrivilege(ServiceRtc::kPrivilegeJoinChannel, privilege_expire); if (role == UserRole::kRolePublisher) { - service->AddPrivilege(ServiceRtc::kPrivilegePublishAudioStream, expire); - service->AddPrivilege(ServiceRtc::kPrivilegePublishVideoStream, expire); - service->AddPrivilege(ServiceRtc::kPrivilegePublishDataStream, expire); + service->AddPrivilege(ServiceRtc::kPrivilegePublishAudioStream, privilege_expire); + service->AddPrivilege(ServiceRtc::kPrivilegePublishVideoStream, privilege_expire); + service->AddPrivilege(ServiceRtc::kPrivilegePublishDataStream, privilege_expire); } - AccessToken2 generator(app_id, app_certificate, 0, expire); + AccessToken2 generator(app_id, app_certificate, 0, token_expire); generator.AddService(std::move(service)); return generator.Build(); From 87f5fabbd9b55a05effc305689ed904d911b4eea Mon Sep 17 00:00:00 2001 From: lixinhui Date: Wed, 29 Dec 2021 15:56:42 +0800 Subject: [PATCH 12/21] support setting token and privilege expiration time --- .../python/sample/RtcTokenBuilder2Sample.py | 17 +++++---- .../python/src/RtcTokenBuilder2.py | 36 ++++++++++++------- .../python/test/RtcTokenBuilder2Test.py | 5 +-- 3 files changed, 37 insertions(+), 21 deletions(-) diff --git a/DynamicKey/AgoraDynamicKey/python/sample/RtcTokenBuilder2Sample.py b/DynamicKey/AgoraDynamicKey/python/sample/RtcTokenBuilder2Sample.py index 150b9178..f2362aef 100644 --- a/DynamicKey/AgoraDynamicKey/python/sample/RtcTokenBuilder2Sample.py +++ b/DynamicKey/AgoraDynamicKey/python/sample/RtcTokenBuilder2Sample.py @@ -15,24 +15,27 @@ def main(): channel_name = "7d72365eb983485397e3e3f9d460bdda" uid = 2882341273 account = "2882341273" - expiration_in_seconds = 3600 + token_expiration_in_seconds = 3600 + privilege_expiration_in_seconds = 3600 token = RtcTokenBuilder.build_token_with_uid(app_id, app_certificate, channel_name, uid, Role_Subscriber, - expiration_in_seconds) + token_expiration_in_seconds, privilege_expiration_in_seconds) print("Token with int uid: {}".format(token)) token = RtcTokenBuilder.build_token_with_user_account(app_id, app_certificate, channel_name, account, - Role_Subscriber, expiration_in_seconds) + Role_Subscriber, token_expiration_in_seconds, + privilege_expiration_in_seconds) print("Token with user account: {}".format(token)) token = RtcTokenBuilder.build_token_with_uid_and_privilege( - app_id, app_certificate, channel_name, uid, expiration_in_seconds, expiration_in_seconds, - expiration_in_seconds, expiration_in_seconds, expiration_in_seconds) + app_id, app_certificate, channel_name, uid, privilege_expiration_in_seconds, privilege_expiration_in_seconds, + privilege_expiration_in_seconds, privilege_expiration_in_seconds, privilege_expiration_in_seconds) print("Token with int uid and privilege: {}".format(token)) token = RtcTokenBuilder.build_token_with_user_account_and_privilege( - app_id, app_certificate, channel_name, account, expiration_in_seconds, expiration_in_seconds, - expiration_in_seconds, expiration_in_seconds, expiration_in_seconds) + app_id, app_certificate, channel_name, account, privilege_expiration_in_seconds, + privilege_expiration_in_seconds, + privilege_expiration_in_seconds, privilege_expiration_in_seconds, privilege_expiration_in_seconds) print("Token with user account and privilege: {}".format(token)) diff --git a/DynamicKey/AgoraDynamicKey/python/src/RtcTokenBuilder2.py b/DynamicKey/AgoraDynamicKey/python/src/RtcTokenBuilder2.py index e6af97a0..11090daf 100755 --- a/DynamicKey/AgoraDynamicKey/python/src/RtcTokenBuilder2.py +++ b/DynamicKey/AgoraDynamicKey/python/src/RtcTokenBuilder2.py @@ -9,7 +9,7 @@ class RtcTokenBuilder: @staticmethod - def build_token_with_uid(app_id, app_certificate, channel_name, uid, role, expire): + def build_token_with_uid(app_id, app_certificate, channel_name, uid, role, token_expire, privilege_expire=0): """ Build the RTC token with uid. :param app_id: The App ID issued to you by Agora. Apply for a new App ID from Agora Dashboard if it is missing @@ -22,14 +22,21 @@ def build_token_with_uid(app_id, app_certificate, channel_name, uid, role, expir :param role: Role_Publisher: A broadcaster/host in a live-broadcast profile. Role_Subscriber: An audience(default) in a live-broadcast profile. - :param expire: represented by the number of seconds elapsed since now. If, for example, you want to access the - Agora Service within 10 minutes after the token is generated, set expireTimestamp as 600(seconds). + :param token_expire: + represented by the number of seconds elapsed since now. If, for example, + you want to access the Agora Service within 10 minutes after the token is generated, + set token_expire as 600(seconds). + :param privilege_expire: + represented by the number of seconds elapsed since now. If, for example, + you want to enable your privilege for 10 minutes, set privilege_expire as 600(seconds). :return: The RTC token. """ - return RtcTokenBuilder.build_token_with_user_account(app_id, app_certificate, channel_name, uid, role, expire) + return RtcTokenBuilder.build_token_with_user_account(app_id, app_certificate, channel_name, uid, role, + token_expire, privilege_expire) @staticmethod - def build_token_with_user_account(app_id, app_certificate, channel_name, account, role, expire): + def build_token_with_user_account(app_id, app_certificate, channel_name, account, role, token_expire, + privilege_expire=0): """ Build the RTC token with account. :param app_id: The App ID issued to you by Agora. Apply for a new App ID from Agora Dashboard if it is missing @@ -41,18 +48,23 @@ def build_token_with_user_account(app_id, app_certificate, channel_name, account :param role: Role_Publisher: A broadcaster/host in a live-broadcast profile. Role_Subscriber: An audience(default) in a live-broadcast profile. - :param expire: represented by the number of seconds elapsed since now. If, for example, you want to access the - Agora Service within 10 minutes after the token is generated, set expireTimestamp as 600(seconds). + :param token_expire: + represented by the number of seconds elapsed since now. If, for example, + you want to access the Agora Service within 10 minutes after the token is generated, + set token_expire as 600(seconds). + :param privilege_expire: + represented by the number of seconds elapsed since now. If, for example, + you want to enable your privilege for 10 minutes, set privilege_expire as 600(seconds). :return: The RTC token. """ - token = AccessToken(app_id, app_certificate, expire=expire) + token = AccessToken(app_id, app_certificate, expire=token_expire) rtc_service = ServiceRtc(channel_name, account) - rtc_service.add_privilege(ServiceRtc.kPrivilegeJoinChannel, expire) + rtc_service.add_privilege(ServiceRtc.kPrivilegeJoinChannel, privilege_expire) if role == Role_Publisher: - rtc_service.add_privilege(ServiceRtc.kPrivilegePublishAudioStream, expire) - rtc_service.add_privilege(ServiceRtc.kPrivilegePublishVideoStream, expire) - rtc_service.add_privilege(ServiceRtc.kPrivilegePublishDataStream, expire) + rtc_service.add_privilege(ServiceRtc.kPrivilegePublishAudioStream, privilege_expire) + rtc_service.add_privilege(ServiceRtc.kPrivilegePublishVideoStream, privilege_expire) + rtc_service.add_privilege(ServiceRtc.kPrivilegePublishDataStream, privilege_expire) token.add_service(rtc_service) return token.build() diff --git a/DynamicKey/AgoraDynamicKey/python/test/RtcTokenBuilder2Test.py b/DynamicKey/AgoraDynamicKey/python/test/RtcTokenBuilder2Test.py index 7ecd60bb..975648ed 100644 --- a/DynamicKey/AgoraDynamicKey/python/test/RtcTokenBuilder2Test.py +++ b/DynamicKey/AgoraDynamicKey/python/test/RtcTokenBuilder2Test.py @@ -24,7 +24,7 @@ def setUp(self): def test_build_token_with_uid(self): token = RtcTokenBuilder.build_token_with_uid(self.__app_id, self.__app_cert, self.__channel_name, self.__uid, - Role_Subscriber, self.__expire) + Role_Subscriber, self.__expire, self.__expire) parser = AccessToken() parser.from_string(token) @@ -44,7 +44,8 @@ def test_build_token_with_uid(self): def test_build_token_with_user_account(self): token = RtcTokenBuilder.build_token_with_user_account(self.__app_id, self.__app_cert, self.__channel_name, - self.__account, Role_Subscriber, self.__expire) + self.__account, Role_Subscriber, self.__expire, + self.__expire) parser = AccessToken() parser.from_string(token) From dcf76f73b8ba571fc25242a844a6b10f3edc5e79 Mon Sep 17 00:00:00 2001 From: lixinhui Date: Wed, 29 Dec 2021 16:01:48 +0800 Subject: [PATCH 13/21] support setting token and privilege expiration time --- .../python3/sample/RtcTokenBuilder2Sample.py | 17 +++++---- .../python3/src/RtcTokenBuilder2.py | 36 ++++++++++++------- .../python3/test/RtcTokenBuilder2Test.py | 4 +-- 3 files changed, 36 insertions(+), 21 deletions(-) diff --git a/DynamicKey/AgoraDynamicKey/python3/sample/RtcTokenBuilder2Sample.py b/DynamicKey/AgoraDynamicKey/python3/sample/RtcTokenBuilder2Sample.py index 150b9178..f2362aef 100644 --- a/DynamicKey/AgoraDynamicKey/python3/sample/RtcTokenBuilder2Sample.py +++ b/DynamicKey/AgoraDynamicKey/python3/sample/RtcTokenBuilder2Sample.py @@ -15,24 +15,27 @@ def main(): channel_name = "7d72365eb983485397e3e3f9d460bdda" uid = 2882341273 account = "2882341273" - expiration_in_seconds = 3600 + token_expiration_in_seconds = 3600 + privilege_expiration_in_seconds = 3600 token = RtcTokenBuilder.build_token_with_uid(app_id, app_certificate, channel_name, uid, Role_Subscriber, - expiration_in_seconds) + token_expiration_in_seconds, privilege_expiration_in_seconds) print("Token with int uid: {}".format(token)) token = RtcTokenBuilder.build_token_with_user_account(app_id, app_certificate, channel_name, account, - Role_Subscriber, expiration_in_seconds) + Role_Subscriber, token_expiration_in_seconds, + privilege_expiration_in_seconds) print("Token with user account: {}".format(token)) token = RtcTokenBuilder.build_token_with_uid_and_privilege( - app_id, app_certificate, channel_name, uid, expiration_in_seconds, expiration_in_seconds, - expiration_in_seconds, expiration_in_seconds, expiration_in_seconds) + app_id, app_certificate, channel_name, uid, privilege_expiration_in_seconds, privilege_expiration_in_seconds, + privilege_expiration_in_seconds, privilege_expiration_in_seconds, privilege_expiration_in_seconds) print("Token with int uid and privilege: {}".format(token)) token = RtcTokenBuilder.build_token_with_user_account_and_privilege( - app_id, app_certificate, channel_name, account, expiration_in_seconds, expiration_in_seconds, - expiration_in_seconds, expiration_in_seconds, expiration_in_seconds) + app_id, app_certificate, channel_name, account, privilege_expiration_in_seconds, + privilege_expiration_in_seconds, + privilege_expiration_in_seconds, privilege_expiration_in_seconds, privilege_expiration_in_seconds) print("Token with user account and privilege: {}".format(token)) diff --git a/DynamicKey/AgoraDynamicKey/python3/src/RtcTokenBuilder2.py b/DynamicKey/AgoraDynamicKey/python3/src/RtcTokenBuilder2.py index 1fa26edd..e8cd7c27 100755 --- a/DynamicKey/AgoraDynamicKey/python3/src/RtcTokenBuilder2.py +++ b/DynamicKey/AgoraDynamicKey/python3/src/RtcTokenBuilder2.py @@ -9,7 +9,7 @@ class RtcTokenBuilder: @staticmethod - def build_token_with_uid(app_id, app_certificate, channel_name, uid, role, expire): + def build_token_with_uid(app_id, app_certificate, channel_name, uid, role, token_expire, privilege_expire=0): """ Build the RTC token with uid. :param app_id: The App ID issued to you by Agora. Apply for a new App ID from Agora Dashboard if it is missing @@ -22,14 +22,21 @@ def build_token_with_uid(app_id, app_certificate, channel_name, uid, role, expir :param role: Role_Publisher: A broadcaster/host in a live-broadcast profile. Role_Subscriber: An audience(default) in a live-broadcast profile. - :param expire: represented by the number of seconds elapsed since now. If, for example, you want to access the - Agora Service within 10 minutes after the token is generated, set expireTimestamp as 600(seconds). + :param token_expire: + represented by the number of seconds elapsed since now. If, for example, + you want to access the Agora Service within 10 minutes after the token is generated, + set token_expire as 600(seconds). + :param privilege_expire: + represented by the number of seconds elapsed since now. If, for example, + you want to enable your privilege for 10 minutes, set privilege_expire as 600(seconds). :return: The RTC token. """ - return RtcTokenBuilder.build_token_with_user_account(app_id, app_certificate, channel_name, uid, role, expire) + return RtcTokenBuilder.build_token_with_user_account(app_id, app_certificate, channel_name, uid, role, + token_expire, privilege_expire) @staticmethod - def build_token_with_user_account(app_id, app_certificate, channel_name, account, role, expire): + def build_token_with_user_account(app_id, app_certificate, channel_name, account, role, token_expire, + privilege_expire=0): """ Build the RTC token with account. :param app_id: The App ID issued to you by Agora. Apply for a new App ID from Agora Dashboard if it is missing @@ -41,18 +48,23 @@ def build_token_with_user_account(app_id, app_certificate, channel_name, account :param role: Role_Publisher: A broadcaster/host in a live-broadcast profile. Role_Subscriber: An audience(default) in a live-broadcast profile. - :param expire: represented by the number of seconds elapsed since now. If, for example, you want to access the - Agora Service within 10 minutes after the token is generated, set expireTimestamp as 600(seconds). + :param token_expire: + represented by the number of seconds elapsed since now. If, for example, + you want to access the Agora Service within 10 minutes after the token is generated, + set token_expire as 600(seconds). + :param privilege_expire: + represented by the number of seconds elapsed since now. If, for example, + you want to enable your privilege for 10 minutes, set privilege_expire as 600(seconds). :return: The RTC token. """ - token = AccessToken(app_id, app_certificate, expire=expire) + token = AccessToken(app_id, app_certificate, expire=token_expire) service_rtc = ServiceRtc(channel_name, account) - service_rtc.add_privilege(ServiceRtc.kPrivilegeJoinChannel, expire) + service_rtc.add_privilege(ServiceRtc.kPrivilegeJoinChannel, privilege_expire) if role == Role_Publisher: - service_rtc.add_privilege(ServiceRtc.kPrivilegePublishAudioStream, expire) - service_rtc.add_privilege(ServiceRtc.kPrivilegePublishVideoStream, expire) - service_rtc.add_privilege(ServiceRtc.kPrivilegePublishDataStream, expire) + service_rtc.add_privilege(ServiceRtc.kPrivilegePublishAudioStream, privilege_expire) + service_rtc.add_privilege(ServiceRtc.kPrivilegePublishVideoStream, privilege_expire) + service_rtc.add_privilege(ServiceRtc.kPrivilegePublishDataStream, privilege_expire) token.add_service(service_rtc) return token.build() diff --git a/DynamicKey/AgoraDynamicKey/python3/test/RtcTokenBuilder2Test.py b/DynamicKey/AgoraDynamicKey/python3/test/RtcTokenBuilder2Test.py index e3765c0a..c5a6201e 100644 --- a/DynamicKey/AgoraDynamicKey/python3/test/RtcTokenBuilder2Test.py +++ b/DynamicKey/AgoraDynamicKey/python3/test/RtcTokenBuilder2Test.py @@ -24,7 +24,7 @@ def setUp(self) -> None: def test_build_token_with_uid(self): token = RtcTokenBuilder.build_token_with_uid(self.__app_id, self.__app_cert, self.__channel_name, self.__uid, - Role_Subscriber, self.__expire) + Role_Subscriber, self.__expire, self.__expire) parser = AccessToken() parser.from_string(token) @@ -44,7 +44,7 @@ def test_build_token_with_uid(self): def test_build_token_with_user_account(self): token = RtcTokenBuilder.build_token_with_user_account(self.__app_id, self.__app_cert, self.__channel_name, - self.__account, Role_Subscriber, self.__expire) + self.__account, Role_Subscriber, self.__expire, self.__expire) parser = AccessToken() parser.from_string(token) From 90dc8466cbc9874f58ff5b2203962eb3cf03bfdd Mon Sep 17 00:00:00 2001 From: lixinhui Date: Wed, 29 Dec 2021 16:26:27 +0800 Subject: [PATCH 14/21] support setting token and privilege expiration time --- .../go/sample/rtctokenbuilder2/sample.go | 80 +++---- .../src/rtctokenbuilder2/rtctokenbuilder.go | 114 ++++----- .../rtctokenbuilder2/rtctokenbuilder_test.go | 219 +++++++++--------- 3 files changed, 211 insertions(+), 202 deletions(-) diff --git a/DynamicKey/AgoraDynamicKey/go/sample/rtctokenbuilder2/sample.go b/DynamicKey/AgoraDynamicKey/go/sample/rtctokenbuilder2/sample.go index 59ef4d23..79ba36c5 100644 --- a/DynamicKey/AgoraDynamicKey/go/sample/rtctokenbuilder2/sample.go +++ b/DynamicKey/AgoraDynamicKey/go/sample/rtctokenbuilder2/sample.go @@ -1,46 +1,48 @@ package main import ( - "fmt" - rtctokenbuilder "github.com/AgoraIO/Tools/DynamicKey/AgoraDynamicKey/go/src/rtctokenbuilder2" + "fmt" + + rtctokenbuilder "github.com/AgoraIO/Tools/DynamicKey/AgoraDynamicKey/go/src/rtctokenbuilder2" ) func main() { - appID := "970CA35de60c44645bbae8a215061b33" - appCertificate := "5CFd2fd1755d40ecb72977518be15d3b" - channelName := "7d72365eb983485397e3e3f9d460bdda" - uid := uint32(2882341273) - uidStr := "2882341273" - expirationInSeconds := uint32(3600) - - result, err := rtctokenbuilder.BuildTokenWithUid(appID, appCertificate, channelName, uid, rtctokenbuilder.RoleSubscriber, expirationInSeconds) - if err != nil { - fmt.Println(err) - } else { - fmt.Printf("Token with int uid: %s\n", result) - } - - result, err = rtctokenbuilder.BuildTokenWithUserAccount(appID, appCertificate, channelName, uidStr, rtctokenbuilder.RoleSubscriber, expirationInSeconds) - if err != nil { - fmt.Println(err) - } else { - fmt.Printf("Token with user account: %s\n", result) - } - - result, err1 := rtctokenbuilder.BuildTokenWithUidAndPrivilege(appID, appCertificate, channelName, uid, - expirationInSeconds, expirationInSeconds, expirationInSeconds, expirationInSeconds, expirationInSeconds) - if err1 != nil { - fmt.Println(err) - } else { - fmt.Printf("Token with int uid and privilege: %s\n", result) - } - - result, err1 = rtctokenbuilder.BuildTokenWithUserAccountAndPrivilege(appID, appCertificate, channelName, uidStr, - expirationInSeconds, expirationInSeconds, expirationInSeconds, expirationInSeconds, expirationInSeconds) - - if err1 != nil { - fmt.Println(err) - } else { - fmt.Printf("Token with user account and privilege: %s\n", result) - } + appID := "970CA35de60c44645bbae8a215061b33" + appCertificate := "5CFd2fd1755d40ecb72977518be15d3b" + channelName := "7d72365eb983485397e3e3f9d460bdda" + uid := uint32(2882341273) + uidStr := "2882341273" + tokenExpirationInSeconds := uint32(3600) + privilegeExpirationInSeconds := uint32(3600) + + result, err := rtctokenbuilder.BuildTokenWithUid(appID, appCertificate, channelName, uid, rtctokenbuilder.RoleSubscriber, tokenExpirationInSeconds, privilegeExpirationInSeconds) + if err != nil { + fmt.Println(err) + } else { + fmt.Printf("Token with int uid: %s\n", result) + } + + result, err = rtctokenbuilder.BuildTokenWithUserAccount(appID, appCertificate, channelName, uidStr, rtctokenbuilder.RoleSubscriber, tokenExpirationInSeconds, privilegeExpirationInSeconds) + if err != nil { + fmt.Println(err) + } else { + fmt.Printf("Token with user account: %s\n", result) + } + + result, err1 := rtctokenbuilder.BuildTokenWithUidAndPrivilege(appID, appCertificate, channelName, uid, + privilegeExpirationInSeconds, privilegeExpirationInSeconds, privilegeExpirationInSeconds, privilegeExpirationInSeconds, privilegeExpirationInSeconds) + if err1 != nil { + fmt.Println(err) + } else { + fmt.Printf("Token with int uid and privilege: %s\n", result) + } + + result, err1 = rtctokenbuilder.BuildTokenWithUserAccountAndPrivilege(appID, appCertificate, channelName, uidStr, + privilegeExpirationInSeconds, privilegeExpirationInSeconds, privilegeExpirationInSeconds, privilegeExpirationInSeconds, privilegeExpirationInSeconds) + + if err1 != nil { + fmt.Println(err) + } else { + fmt.Printf("Token with user account and privilege: %s\n", result) + } } diff --git a/DynamicKey/AgoraDynamicKey/go/src/rtctokenbuilder2/rtctokenbuilder.go b/DynamicKey/AgoraDynamicKey/go/src/rtctokenbuilder2/rtctokenbuilder.go index 0dd2c4e5..076bc8a6 100644 --- a/DynamicKey/AgoraDynamicKey/go/src/rtctokenbuilder2/rtctokenbuilder.go +++ b/DynamicKey/AgoraDynamicKey/go/src/rtctokenbuilder2/rtctokenbuilder.go @@ -1,64 +1,70 @@ package rtctokenbuilder2 import ( - accesstoken "github.com/AgoraIO/Tools/DynamicKey/AgoraDynamicKey/go/src/accesstoken2" + accesstoken "github.com/AgoraIO/Tools/DynamicKey/AgoraDynamicKey/go/src/accesstoken2" ) // Role type type Role uint16 const ( - RolePublisher = 1 // for live broadcaster - RoleSubscriber = 2 // default, for live audience + RolePublisher = 1 // for live broadcaster + RoleSubscriber = 2 // default, for live audience ) -// Build the RTC token with uid. -// -// appId: The App ID issued to you by Agora. Apply for a new App ID from -// Agora Dashboard if it is missing from your kit. See Get an App ID. -// appCertificate: Certificate of the application that you registered in -// the Agora Dashboard. See Get an App Certificate. -// channelName: Unique channel name for the AgoraRTC session in the string format -// uid: User ID. A 32-bit unsigned integer with a value ranging from 1 to (232-1). -// optionalUid must be unique. -// role: RolePublisher: A broadcaster/host in a live-broadcast profile. -// RoleSubscriber: An audience(default) in a live-broadcast profile. -// expire: represented by the number of seconds elapsed since now. If, for example, you want to access the -// Agora Service within 10 minutes after the token is generated, set expireTimestamp as 600(seconds). +// BuildTokenWithUid Build the RTC token with uid. +// appId: The App ID issued to you by Agora. Apply for a new App ID from +// Agora Dashboard if it is missing from your kit. See Get an App ID. +// appCertificate: Certificate of the application that you registered in +// the Agora Dashboard. See Get an App Certificate. +// channelName: Unique channel name for the AgoraRTC session in the string format +// uid: User ID. A 32-bit unsigned integer with a value ranging from 1 to (232-1). optionalUid must be unique. +// role: RolePublisher: A broadcaster/host in a live-broadcast profile. +// RoleSubscriber: An audience(default) in a live-broadcast profile. +// expire: represented by the number of seconds elapsed since now. If, for example, you want to access the +// Agora Service within 10 minutes after the token is generated, set expireTimestamp as 600(seconds). +// tokenExpire: represented by the number of seconds elapsed since now. If, for example, +// you want to access the Agora Service within 10 minutes after the token is generated, +// set token_expire as 600(seconds). +// privilegeExpire: represented by the number of seconds elapsed since now. If, for example, +// you want to enable your privilege for 10 minutes, set privilege_expire as 600(seconds). // return The RTC token. -func BuildTokenWithUid(appId string, appCertificate string, channelName string, uid uint32, role Role, expire uint32) (string, error) { - return BuildTokenWithUserAccount(appId, appCertificate, channelName, accesstoken.GetUidStr(uid), role, expire) +func BuildTokenWithUid(appId string, appCertificate string, channelName string, uid uint32, role Role, tokenExpire uint32, privilegeExpire uint32) (string, error) { + return BuildTokenWithUserAccount(appId, appCertificate, channelName, accesstoken.GetUidStr(uid), role, tokenExpire, privilegeExpire) } -// Build the RTC token with account. +// BuildTokenWithUserAccount Build the RTC token with account. // -// appId: The App ID issued to you by Agora. Apply for a new App ID from -// Agora Dashboard if it is missing from your kit. See Get an App ID. -// appCertificate: Certificate of the application that you registered in -// the Agora Dashboard. See Get an App Certificate. -// channelName: Unique channel name for the AgoraRTC session in the string format -// account: The user's account, max length is 255 Bytes. -// role: RolePublisher: A broadcaster/host in a live-broadcast profile. -// RoleSubscriber: An audience(default) in a live-broadcast profile. -// expire: represented by the number of seconds elapsed since now. If, for example, you want to access the -// Agora Service within 10 minutes after the token is generated, set expireTimestamp as 600(seconds). +// appId: The App ID issued to you by Agora. Apply for a new App ID from +// Agora Dashboard if it is missing from your kit. See Get an App ID. +// appCertificate: Certificate of the application that you registered in +// the Agora Dashboard. See Get an App Certificate. +// channelName: Unique channel name for the AgoraRTC session in the string format +// account: The user's account, max length is 255 Bytes. +// role: RolePublisher: A broadcaster/host in a live-broadcast profile. +// RoleSubscriber: An audience(default) in a live-broadcast profile. +// tokenExpire: represented by the number of seconds elapsed since now. If, for example, +// you want to access the Agora Service within 10 minutes after the token is generated, +// set token_expire as 600(seconds). +// privilegeExpire: represented by the number of seconds elapsed since now. If, for example, +// you want to enable your privilege for 10 minutes, set privilege_expire as 600(seconds). // return The RTC token. -func BuildTokenWithUserAccount(appId string, appCertificate string, channelName string, account string, role Role, expire uint32) (string, error) { - token := accesstoken.NewAccessToken(appId, appCertificate, expire) +func BuildTokenWithUserAccount(appId string, appCertificate string, channelName string, account string, role Role, tokenExpire uint32, privilegeExpire uint32) (string, error) { + token := accesstoken.NewAccessToken(appId, appCertificate, tokenExpire) - serviceRtc := accesstoken.NewServiceRtc(channelName, account) - serviceRtc.AddPrivilege(accesstoken.PrivilegeJoinChannel, expire) - if role == RolePublisher { - serviceRtc.AddPrivilege(accesstoken.PrivilegePublishAudioStream, expire) - serviceRtc.AddPrivilege(accesstoken.PrivilegePublishVideoStream, expire) - serviceRtc.AddPrivilege(accesstoken.PrivilegePublishDataStream, expire) - } - token.AddService(serviceRtc) + serviceRtc := accesstoken.NewServiceRtc(channelName, account) + serviceRtc.AddPrivilege(accesstoken.PrivilegeJoinChannel, privilegeExpire) + if role == RolePublisher { + serviceRtc.AddPrivilege(accesstoken.PrivilegePublishAudioStream, privilegeExpire) + serviceRtc.AddPrivilege(accesstoken.PrivilegePublishVideoStream, privilegeExpire) + serviceRtc.AddPrivilege(accesstoken.PrivilegePublishDataStream, privilegeExpire) + } + token.AddService(serviceRtc) - return token.Build() + return token.Build() } -// Generates an RTC token with the specified privilege. +// BuildTokenWithUidAndPrivilege Generates an RTC token with the specified privilege. // // This method supports generating a token with the following privileges: // - Joining an RTC channel. @@ -109,12 +115,12 @@ func BuildTokenWithUserAccount(appId string, appCertificate string, channelName // current timestamp plus 600 seconds, the token expires in 10 minutes. If you do not want to enable this privilege, // set pubDataStreamPrivilegeExpire as the current Unix timestamp. func BuildTokenWithUidAndPrivilege(appId string, appCertificate string, channelName string, uid uint32, - tokenExpire uint32, joinChannelPrivilegeExpire uint32, pubAudioPrivilegeExpire uint32, pubVideoPrivilegeExpire uint32, pubDataStreamPrivilegeExpire uint32) (string, error) { - return BuildTokenWithUserAccountAndPrivilege(appId, appCertificate, channelName, accesstoken.GetUidStr(uid), tokenExpire, - joinChannelPrivilegeExpire, pubAudioPrivilegeExpire, pubVideoPrivilegeExpire, pubDataStreamPrivilegeExpire) + tokenExpire uint32, joinChannelPrivilegeExpire uint32, pubAudioPrivilegeExpire uint32, pubVideoPrivilegeExpire uint32, pubDataStreamPrivilegeExpire uint32) (string, error) { + return BuildTokenWithUserAccountAndPrivilege(appId, appCertificate, channelName, accesstoken.GetUidStr(uid), tokenExpire, + joinChannelPrivilegeExpire, pubAudioPrivilegeExpire, pubVideoPrivilegeExpire, pubDataStreamPrivilegeExpire) } -// Generates an RTC token with the specified privilege. +// BuildTokenWithUserAccountAndPrivilege Generates an RTC token with the specified privilege. // // This method supports generating a token with the following privileges: // - Joining an RTC channel. @@ -165,15 +171,15 @@ func BuildTokenWithUidAndPrivilege(appId string, appCertificate string, channelN // current timestamp plus 600 seconds, the token expires in 10 minutes. If you do not want to enable this privilege, // set pubDataStreamPrivilegeExpire as the current Unix timestamp. func BuildTokenWithUserAccountAndPrivilege(appId string, appCertificate string, channelName string, account string, - tokenExpire uint32, joinChannelPrivilegeExpire uint32, pubAudioPrivilegeExpire uint32, pubVideoPrivilegeExpire uint32, pubDataStreamPrivilegeExpire uint32) (string, error) { - token := accesstoken.NewAccessToken(appId, appCertificate, tokenExpire) + tokenExpire uint32, joinChannelPrivilegeExpire uint32, pubAudioPrivilegeExpire uint32, pubVideoPrivilegeExpire uint32, pubDataStreamPrivilegeExpire uint32) (string, error) { + token := accesstoken.NewAccessToken(appId, appCertificate, tokenExpire) - serviceRtc := accesstoken.NewServiceRtc(channelName, account) - serviceRtc.AddPrivilege(accesstoken.PrivilegeJoinChannel, joinChannelPrivilegeExpire) - serviceRtc.AddPrivilege(accesstoken.PrivilegePublishAudioStream, pubAudioPrivilegeExpire) - serviceRtc.AddPrivilege(accesstoken.PrivilegePublishVideoStream, pubVideoPrivilegeExpire) - serviceRtc.AddPrivilege(accesstoken.PrivilegePublishDataStream, pubDataStreamPrivilegeExpire) - token.AddService(serviceRtc) + serviceRtc := accesstoken.NewServiceRtc(channelName, account) + serviceRtc.AddPrivilege(accesstoken.PrivilegeJoinChannel, joinChannelPrivilegeExpire) + serviceRtc.AddPrivilege(accesstoken.PrivilegePublishAudioStream, pubAudioPrivilegeExpire) + serviceRtc.AddPrivilege(accesstoken.PrivilegePublishVideoStream, pubVideoPrivilegeExpire) + serviceRtc.AddPrivilege(accesstoken.PrivilegePublishDataStream, pubDataStreamPrivilegeExpire) + token.AddService(serviceRtc) - return token.Build() + return token.Build() } diff --git a/DynamicKey/AgoraDynamicKey/go/src/rtctokenbuilder2/rtctokenbuilder_test.go b/DynamicKey/AgoraDynamicKey/go/src/rtctokenbuilder2/rtctokenbuilder_test.go index 1b4996aa..e26ab554 100644 --- a/DynamicKey/AgoraDynamicKey/go/src/rtctokenbuilder2/rtctokenbuilder_test.go +++ b/DynamicKey/AgoraDynamicKey/go/src/rtctokenbuilder2/rtctokenbuilder_test.go @@ -1,134 +1,135 @@ package rtctokenbuilder2 import ( - accesstoken "github.com/AgoraIO/Tools/DynamicKey/AgoraDynamicKey/go/src/accesstoken2" - "testing" + "testing" + + accesstoken "github.com/AgoraIO/Tools/DynamicKey/AgoraDynamicKey/go/src/accesstoken2" ) const ( - DataMockAccount = "2882341273" - DataMockAppCertificate = "5CFd2fd1755d40ecb72977518be15d3b" - DataMockAppId = "970CA35de60c44645bbae8a215061b33" - DataMockChannelName = "7d72365eb983485397e3e3f9d460bdda" - DataMockExpire = uint32(600) - DataMockJoinChannelPrivilegeExpire = uint32(600) - DataMockPubAudioPrivilegeExpire = uint32(600) - DataMockPubVideoPrivilegeExpire = uint32(600) - DataMockPubDataStreamPrivilegeExpire = uint32(600) - DataMockUid = uint32(2882341273) - DataMockUidStr = "2882341273" + DataMockAccount = "2882341273" + DataMockAppCertificate = "5CFd2fd1755d40ecb72977518be15d3b" + DataMockAppId = "970CA35de60c44645bbae8a215061b33" + DataMockChannelName = "7d72365eb983485397e3e3f9d460bdda" + DataMockExpire = uint32(600) + DataMockJoinChannelPrivilegeExpire = uint32(600) + DataMockPubAudioPrivilegeExpire = uint32(600) + DataMockPubVideoPrivilegeExpire = uint32(600) + DataMockPubDataStreamPrivilegeExpire = uint32(600) + DataMockUid = uint32(2882341273) + DataMockUidStr = "2882341273" ) func Test_BuildTokenWithUid_RolePublisher(t *testing.T) { - token, err := BuildTokenWithUid(DataMockAppId, DataMockAppCertificate, DataMockChannelName, DataMockUid, RolePublisher, DataMockExpire) - accesstoken.AssertNil(t, err) - - accessToken := accesstoken.CreateAccessToken() - accessToken.Parse(token) - - accesstoken.AssertEqual(t, DataMockAppId, accessToken.AppId) - accesstoken.AssertEqual(t, DataMockExpire, accessToken.Expire) - accesstoken.AssertEqual(t, true, accessToken.Services[accesstoken.ServiceTypeRtc] != nil) - accesstoken.AssertEqual(t, DataMockChannelName, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).ChannelName) - accesstoken.AssertEqual(t, DataMockUidStr, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Uid) - accesstoken.AssertEqual(t, uint16(accesstoken.ServiceTypeRtc), accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Type) - accesstoken.AssertEqual(t, DataMockExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegeJoinChannel]) - accesstoken.AssertEqual(t, DataMockExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishAudioStream]) - accesstoken.AssertEqual(t, DataMockExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishVideoStream]) - accesstoken.AssertEqual(t, DataMockExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishDataStream]) + token, err := BuildTokenWithUid(DataMockAppId, DataMockAppCertificate, DataMockChannelName, DataMockUid, RolePublisher, DataMockExpire, DataMockExpire) + accesstoken.AssertNil(t, err) + + accessToken := accesstoken.CreateAccessToken() + accessToken.Parse(token) + + accesstoken.AssertEqual(t, DataMockAppId, accessToken.AppId) + accesstoken.AssertEqual(t, DataMockExpire, accessToken.Expire) + accesstoken.AssertEqual(t, true, accessToken.Services[accesstoken.ServiceTypeRtc] != nil) + accesstoken.AssertEqual(t, DataMockChannelName, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).ChannelName) + accesstoken.AssertEqual(t, DataMockUidStr, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Uid) + accesstoken.AssertEqual(t, uint16(accesstoken.ServiceTypeRtc), accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Type) + accesstoken.AssertEqual(t, DataMockExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegeJoinChannel]) + accesstoken.AssertEqual(t, DataMockExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishAudioStream]) + accesstoken.AssertEqual(t, DataMockExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishVideoStream]) + accesstoken.AssertEqual(t, DataMockExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishDataStream]) } func Test_BuildTokenWithUid_RoleSubscriber(t *testing.T) { - token, err := BuildTokenWithUid(DataMockAppId, DataMockAppCertificate, DataMockChannelName, DataMockUid, RoleSubscriber, DataMockExpire) - accesstoken.AssertNil(t, err) - - accessToken := accesstoken.CreateAccessToken() - accessToken.Parse(token) - - accesstoken.AssertEqual(t, DataMockAppId, accessToken.AppId) - accesstoken.AssertEqual(t, DataMockExpire, accessToken.Expire) - accesstoken.AssertEqual(t, true, accessToken.Services[accesstoken.ServiceTypeRtc] != nil) - accesstoken.AssertEqual(t, DataMockChannelName, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).ChannelName) - accesstoken.AssertEqual(t, DataMockUidStr, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Uid) - accesstoken.AssertEqual(t, uint16(accesstoken.ServiceTypeRtc), accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Type) - accesstoken.AssertEqual(t, DataMockExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegeJoinChannel]) - accesstoken.AssertEqual(t, uint32(0), accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishAudioStream]) - accesstoken.AssertEqual(t, uint32(0), accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishVideoStream]) - accesstoken.AssertEqual(t, uint32(0), accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishDataStream]) + token, err := BuildTokenWithUid(DataMockAppId, DataMockAppCertificate, DataMockChannelName, DataMockUid, RoleSubscriber, DataMockExpire, DataMockExpire) + accesstoken.AssertNil(t, err) + + accessToken := accesstoken.CreateAccessToken() + accessToken.Parse(token) + + accesstoken.AssertEqual(t, DataMockAppId, accessToken.AppId) + accesstoken.AssertEqual(t, DataMockExpire, accessToken.Expire) + accesstoken.AssertEqual(t, true, accessToken.Services[accesstoken.ServiceTypeRtc] != nil) + accesstoken.AssertEqual(t, DataMockChannelName, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).ChannelName) + accesstoken.AssertEqual(t, DataMockUidStr, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Uid) + accesstoken.AssertEqual(t, uint16(accesstoken.ServiceTypeRtc), accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Type) + accesstoken.AssertEqual(t, DataMockExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegeJoinChannel]) + accesstoken.AssertEqual(t, uint32(0), accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishAudioStream]) + accesstoken.AssertEqual(t, uint32(0), accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishVideoStream]) + accesstoken.AssertEqual(t, uint32(0), accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishDataStream]) } func Test_BuildTokenWithUserAccount_RolePublisher(t *testing.T) { - token, err := BuildTokenWithUserAccount(DataMockAppId, DataMockAppCertificate, DataMockChannelName, DataMockAccount, RolePublisher, DataMockExpire) - accesstoken.AssertNil(t, err) - - accessToken := accesstoken.CreateAccessToken() - accessToken.Parse(token) - - accesstoken.AssertEqual(t, DataMockAppId, accessToken.AppId) - accesstoken.AssertEqual(t, DataMockExpire, accessToken.Expire) - accesstoken.AssertEqual(t, true, accessToken.Services[accesstoken.ServiceTypeRtc] != nil) - accesstoken.AssertEqual(t, DataMockChannelName, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).ChannelName) - accesstoken.AssertEqual(t, DataMockAccount, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Uid) - accesstoken.AssertEqual(t, uint16(accesstoken.ServiceTypeRtc), accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Type) - accesstoken.AssertEqual(t, DataMockExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegeJoinChannel]) - accesstoken.AssertEqual(t, DataMockExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishAudioStream]) - accesstoken.AssertEqual(t, DataMockExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishVideoStream]) - accesstoken.AssertEqual(t, DataMockExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishDataStream]) + token, err := BuildTokenWithUserAccount(DataMockAppId, DataMockAppCertificate, DataMockChannelName, DataMockAccount, RolePublisher, DataMockExpire, DataMockExpire) + accesstoken.AssertNil(t, err) + + accessToken := accesstoken.CreateAccessToken() + accessToken.Parse(token) + + accesstoken.AssertEqual(t, DataMockAppId, accessToken.AppId) + accesstoken.AssertEqual(t, DataMockExpire, accessToken.Expire) + accesstoken.AssertEqual(t, true, accessToken.Services[accesstoken.ServiceTypeRtc] != nil) + accesstoken.AssertEqual(t, DataMockChannelName, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).ChannelName) + accesstoken.AssertEqual(t, DataMockAccount, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Uid) + accesstoken.AssertEqual(t, uint16(accesstoken.ServiceTypeRtc), accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Type) + accesstoken.AssertEqual(t, DataMockExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegeJoinChannel]) + accesstoken.AssertEqual(t, DataMockExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishAudioStream]) + accesstoken.AssertEqual(t, DataMockExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishVideoStream]) + accesstoken.AssertEqual(t, DataMockExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishDataStream]) } func Test_BuildTokenWithUserAccount_RoleSubscriber(t *testing.T) { - token, err := BuildTokenWithUserAccount(DataMockAppId, DataMockAppCertificate, DataMockChannelName, DataMockAccount, RoleSubscriber, DataMockExpire) - accesstoken.AssertNil(t, err) - - accessToken := accesstoken.CreateAccessToken() - accessToken.Parse(token) - - accesstoken.AssertEqual(t, DataMockAppId, accessToken.AppId) - accesstoken.AssertEqual(t, DataMockExpire, accessToken.Expire) - accesstoken.AssertEqual(t, true, accessToken.Services[accesstoken.ServiceTypeRtc] != nil) - accesstoken.AssertEqual(t, DataMockChannelName, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).ChannelName) - accesstoken.AssertEqual(t, DataMockAccount, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Uid) - accesstoken.AssertEqual(t, uint16(accesstoken.ServiceTypeRtc), accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Type) - accesstoken.AssertEqual(t, DataMockExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegeJoinChannel]) - accesstoken.AssertEqual(t, uint32(0), accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishAudioStream]) - accesstoken.AssertEqual(t, uint32(0), accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishVideoStream]) - accesstoken.AssertEqual(t, uint32(0), accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishDataStream]) + token, err := BuildTokenWithUserAccount(DataMockAppId, DataMockAppCertificate, DataMockChannelName, DataMockAccount, RoleSubscriber, DataMockExpire, DataMockExpire) + accesstoken.AssertNil(t, err) + + accessToken := accesstoken.CreateAccessToken() + accessToken.Parse(token) + + accesstoken.AssertEqual(t, DataMockAppId, accessToken.AppId) + accesstoken.AssertEqual(t, DataMockExpire, accessToken.Expire) + accesstoken.AssertEqual(t, true, accessToken.Services[accesstoken.ServiceTypeRtc] != nil) + accesstoken.AssertEqual(t, DataMockChannelName, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).ChannelName) + accesstoken.AssertEqual(t, DataMockAccount, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Uid) + accesstoken.AssertEqual(t, uint16(accesstoken.ServiceTypeRtc), accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Type) + accesstoken.AssertEqual(t, DataMockExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegeJoinChannel]) + accesstoken.AssertEqual(t, uint32(0), accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishAudioStream]) + accesstoken.AssertEqual(t, uint32(0), accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishVideoStream]) + accesstoken.AssertEqual(t, uint32(0), accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishDataStream]) } func Test_BuildTokenWithUidAndPrivilege(t *testing.T) { - token, err := BuildTokenWithUidAndPrivilege(DataMockAppId, DataMockAppCertificate, DataMockChannelName, DataMockUid, DataMockExpire, DataMockJoinChannelPrivilegeExpire, DataMockPubAudioPrivilegeExpire, DataMockPubVideoPrivilegeExpire, DataMockPubDataStreamPrivilegeExpire) - accesstoken.AssertNil(t, err) - - accessToken := accesstoken.CreateAccessToken() - accessToken.Parse(token) - - accesstoken.AssertEqual(t, DataMockAppId, accessToken.AppId) - accesstoken.AssertEqual(t, DataMockExpire, accessToken.Expire) - accesstoken.AssertEqual(t, true, accessToken.Services[accesstoken.ServiceTypeRtc] != nil) - accesstoken.AssertEqual(t, DataMockChannelName, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).ChannelName) - accesstoken.AssertEqual(t, DataMockUidStr, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Uid) - accesstoken.AssertEqual(t, uint16(accesstoken.ServiceTypeRtc), accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Type) - accesstoken.AssertEqual(t, DataMockJoinChannelPrivilegeExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegeJoinChannel]) - accesstoken.AssertEqual(t, DataMockPubAudioPrivilegeExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishAudioStream]) - accesstoken.AssertEqual(t, DataMockPubVideoPrivilegeExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishVideoStream]) - accesstoken.AssertEqual(t, DataMockPubDataStreamPrivilegeExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishDataStream]) + token, err := BuildTokenWithUidAndPrivilege(DataMockAppId, DataMockAppCertificate, DataMockChannelName, DataMockUid, DataMockExpire, DataMockJoinChannelPrivilegeExpire, DataMockPubAudioPrivilegeExpire, DataMockPubVideoPrivilegeExpire, DataMockPubDataStreamPrivilegeExpire) + accesstoken.AssertNil(t, err) + + accessToken := accesstoken.CreateAccessToken() + accessToken.Parse(token) + + accesstoken.AssertEqual(t, DataMockAppId, accessToken.AppId) + accesstoken.AssertEqual(t, DataMockExpire, accessToken.Expire) + accesstoken.AssertEqual(t, true, accessToken.Services[accesstoken.ServiceTypeRtc] != nil) + accesstoken.AssertEqual(t, DataMockChannelName, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).ChannelName) + accesstoken.AssertEqual(t, DataMockUidStr, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Uid) + accesstoken.AssertEqual(t, uint16(accesstoken.ServiceTypeRtc), accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Type) + accesstoken.AssertEqual(t, DataMockJoinChannelPrivilegeExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegeJoinChannel]) + accesstoken.AssertEqual(t, DataMockPubAudioPrivilegeExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishAudioStream]) + accesstoken.AssertEqual(t, DataMockPubVideoPrivilegeExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishVideoStream]) + accesstoken.AssertEqual(t, DataMockPubDataStreamPrivilegeExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishDataStream]) } func Test_BuildTokenWithUserAccountAndPrivilege(t *testing.T) { - token, err := BuildTokenWithUserAccountAndPrivilege(DataMockAppId, DataMockAppCertificate, DataMockChannelName, DataMockAccount, DataMockExpire, DataMockJoinChannelPrivilegeExpire, DataMockPubAudioPrivilegeExpire, DataMockPubVideoPrivilegeExpire, DataMockPubDataStreamPrivilegeExpire) - accesstoken.AssertNil(t, err) - - accessToken := accesstoken.CreateAccessToken() - accessToken.Parse(token) - - accesstoken.AssertEqual(t, DataMockAppId, accessToken.AppId) - accesstoken.AssertEqual(t, DataMockExpire, accessToken.Expire) - accesstoken.AssertEqual(t, true, accessToken.Services[accesstoken.ServiceTypeRtc] != nil) - accesstoken.AssertEqual(t, DataMockChannelName, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).ChannelName) - accesstoken.AssertEqual(t, DataMockAccount, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Uid) - accesstoken.AssertEqual(t, uint16(accesstoken.ServiceTypeRtc), accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Type) - accesstoken.AssertEqual(t, DataMockJoinChannelPrivilegeExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegeJoinChannel]) - accesstoken.AssertEqual(t, DataMockPubAudioPrivilegeExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishAudioStream]) - accesstoken.AssertEqual(t, DataMockPubVideoPrivilegeExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishVideoStream]) - accesstoken.AssertEqual(t, DataMockPubDataStreamPrivilegeExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishDataStream]) + token, err := BuildTokenWithUserAccountAndPrivilege(DataMockAppId, DataMockAppCertificate, DataMockChannelName, DataMockAccount, DataMockExpire, DataMockJoinChannelPrivilegeExpire, DataMockPubAudioPrivilegeExpire, DataMockPubVideoPrivilegeExpire, DataMockPubDataStreamPrivilegeExpire) + accesstoken.AssertNil(t, err) + + accessToken := accesstoken.CreateAccessToken() + accessToken.Parse(token) + + accesstoken.AssertEqual(t, DataMockAppId, accessToken.AppId) + accesstoken.AssertEqual(t, DataMockExpire, accessToken.Expire) + accesstoken.AssertEqual(t, true, accessToken.Services[accesstoken.ServiceTypeRtc] != nil) + accesstoken.AssertEqual(t, DataMockChannelName, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).ChannelName) + accesstoken.AssertEqual(t, DataMockAccount, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Uid) + accesstoken.AssertEqual(t, uint16(accesstoken.ServiceTypeRtc), accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Type) + accesstoken.AssertEqual(t, DataMockJoinChannelPrivilegeExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegeJoinChannel]) + accesstoken.AssertEqual(t, DataMockPubAudioPrivilegeExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishAudioStream]) + accesstoken.AssertEqual(t, DataMockPubVideoPrivilegeExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishVideoStream]) + accesstoken.AssertEqual(t, DataMockPubDataStreamPrivilegeExpire, accessToken.Services[accesstoken.ServiceTypeRtc].(*accesstoken.ServiceRtc).Privileges[accesstoken.PrivilegePublishDataStream]) } From 4a456eb78877efd0d3e1cc531c48a9f7bde848c6 Mon Sep 17 00:00:00 2001 From: lixinhui Date: Wed, 29 Dec 2021 20:15:40 +0800 Subject: [PATCH 15/21] modify comment --- .../python3/src/RtcTokenBuilder2.py | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/DynamicKey/AgoraDynamicKey/python3/src/RtcTokenBuilder2.py b/DynamicKey/AgoraDynamicKey/python3/src/RtcTokenBuilder2.py index e8cd7c27..466ccef8 100755 --- a/DynamicKey/AgoraDynamicKey/python3/src/RtcTokenBuilder2.py +++ b/DynamicKey/AgoraDynamicKey/python3/src/RtcTokenBuilder2.py @@ -19,15 +19,12 @@ def build_token_with_uid(app_id, app_certificate, channel_name, uid, role, token :param channel_name: Unique channel name for the AgoraRTC session in the string format. :param uid: User ID. A 32-bit unsigned integer with a value ranging from 1 to (232-1). optionalUid must be unique. - :param role: - Role_Publisher: A broadcaster/host in a live-broadcast profile. + :param role: Role_Publisher: A broadcaster/host in a live-broadcast profile. Role_Subscriber: An audience(default) in a live-broadcast profile. - :param token_expire: - represented by the number of seconds elapsed since now. If, for example, + :param token_expire: represented by the number of seconds elapsed since now. If, for example, you want to access the Agora Service within 10 minutes after the token is generated, set token_expire as 600(seconds). - :param privilege_expire: - represented by the number of seconds elapsed since now. If, for example, + :param privilege_expire: represented by the number of seconds elapsed since now. If, for example, you want to enable your privilege for 10 minutes, set privilege_expire as 600(seconds). :return: The RTC token. """ @@ -45,15 +42,12 @@ def build_token_with_user_account(app_id, app_certificate, channel_name, account See Get an App Certificate. :param channel_name: Unique channel name for the AgoraRTC session in the string format. :param account: The user's account, max length is 255 Bytes. - :param role: - Role_Publisher: A broadcaster/host in a live-broadcast profile. + :param role: Role_Publisher: A broadcaster/host in a live-broadcast profile. Role_Subscriber: An audience(default) in a live-broadcast profile. - :param token_expire: - represented by the number of seconds elapsed since now. If, for example, + :param token_expire: represented by the number of seconds elapsed since now. If, for example, you want to access the Agora Service within 10 minutes after the token is generated, set token_expire as 600(seconds). - :param privilege_expire: - represented by the number of seconds elapsed since now. If, for example, + :param privilege_expire: represented by the number of seconds elapsed since now. If, for example, you want to enable your privilege for 10 minutes, set privilege_expire as 600(seconds). :return: The RTC token. """ From 58d79b853343728673ef706313b914daeb690260 Mon Sep 17 00:00:00 2001 From: lixinhui Date: Wed, 29 Dec 2021 20:20:13 +0800 Subject: [PATCH 16/21] support setting token and privilege expiration time --- .../lib/dynamic_key2/rtc_token_builder.rb | 82 ++++++++++--------- .../ruby/sample/rtc_token_builder2_sample.rb | 19 +++-- .../dynamic_key2/rtc_token_builder_spec.rb | 6 +- 3 files changed, 59 insertions(+), 48 deletions(-) diff --git a/DynamicKey/AgoraDynamicKey/ruby/lib/dynamic_key2/rtc_token_builder.rb b/DynamicKey/AgoraDynamicKey/ruby/lib/dynamic_key2/rtc_token_builder.rb index 032f727a..7cce55bd 100644 --- a/DynamicKey/AgoraDynamicKey/ruby/lib/dynamic_key2/rtc_token_builder.rb +++ b/DynamicKey/AgoraDynamicKey/ruby/lib/dynamic_key2/rtc_token_builder.rb @@ -5,45 +5,51 @@ class RtcTokenBuilder # Build the RTC token with uid. # - # :param app_id: The App ID issued to you by Agora. Apply for a new App ID from Agora Dashboard if it is missing - # from your kit. See Get an App ID. - # :param app_certificate: Certificate of the application that you registered in the Agora Dashboard. - # See Get an App Certificate. - # :param channel_name: Unique channel name for the AgoraRTC session in the string format. - # :param uid: User ID. A 32-bit unsigned integer with a value ranging from 1 to (232-1). - # optionalUid must be unique. - # :param role: ROLE_PUBLISHER: A broadcaster/host in a live-broadcast profile. - # ROLE_SUBSCRIBER: An audience(default) in a live-broadcast profile. - # :param expire: represented by the number of seconds elapsed since now. If, for example, you want to access the - # Agora Service within 10 minutes after the token is generated, set expireTimestamp as 600(seconds). - # :return: The RTC token. - def self.build_token_with_uid(app_id, app_certificate, channel_name, uid, role, expire) - build_token_with_user_account(app_id, app_certificate, channel_name, uid, role, expire) + # app_id: The App ID issued to you by Agora. Apply for a new App ID from Agora Dashboard if it is missing + # from your kit. See Get an App ID. + # app_certificate: Certificate of the application that you registered in the Agora Dashboard. + # See Get an App Certificate. + # channel_name: Unique channel name for the AgoraRTC session in the string format. + # uid: User ID. A 32-bit unsigned integer with a value ranging from 1 to (232-1). + # optionalUid must be unique. + # role: ROLE_PUBLISHER: A broadcaster/host in a live-broadcast profile. + # ROLE_SUBSCRIBER: An audience(default) in a live-broadcast profile. + # token_expire: represented by the number of seconds elapsed since now. If, for example, + # you want to access the Agora Service within 10 minutes after the token is generated, + # set token_expire as 600(seconds). + # privilege_expire: represented by the number of seconds elapsed since now. If, for example, + # you want to enable your privilege for 10 minutes, set privilege_expire as 600(seconds). + # return: The RTC token. + def self.build_token_with_uid(app_id, app_certificate, channel_name, uid, role, token_expire, privilege_expire = 0) + build_token_with_user_account(app_id, app_certificate, channel_name, uid, role, token_expire, privilege_expire) end # Build the RTC token with uid. # - # :param app_id: The App ID issued to you by Agora. Apply for a new App ID from Agora Dashboard if it is missing - # from your kit. See Get an App ID. - # :param app_certificate: Certificate of the application that you registered in the Agora Dashboard. - # See Get an App Certificate. - # :param channel_name: Unique channel name for the AgoraRTC session in the string format. - # :param uid: User ID. A 32-bit unsigned integer with a value ranging from 1 to (232-1). - # optionalUid must be unique. - # :param role: ROLE_PUBLISHER: A broadcaster/host in a live-broadcast profile. - # ROLE_SUBSCRIBER: An audience(default) in a live-broadcast profile. - # :param expire: represented by the number of seconds elapsed since now. If, for example, you want to access the - # Agora Service within 10 minutes after the token is generated, set expireTimestamp as 600(seconds). - # :return: The RTC token. - def self.build_token_with_user_account(app_id, app_certificate, channel_name, account, role, expire) - access_token = AgoraDynamicKey2::AccessToken.new(app_id, app_certificate, expire) + # app_id: The App ID issued to you by Agora. Apply for a new App ID from Agora Dashboard if it is missing + # from your kit. See Get an App ID. + # app_certificate: Certificate of the application that you registered in the Agora Dashboard. + # See Get an App Certificate. + # channel_name: Unique channel name for the AgoraRTC session in the string format. + # uid: User ID. A 32-bit unsigned integer with a value ranging from 1 to (232-1). + # optionalUid must be unique. + # role: ROLE_PUBLISHER: A broadcaster/host in a live-broadcast profile. + # ROLE_SUBSCRIBER: An audience(default) in a live-broadcast profile. + # token_expire: represented by the number of seconds elapsed since now. If, for example, + # you want to access the Agora Service within 10 minutes after the token is generated, + # set token_expire as 600(seconds). + # privilege_expire: represented by the number of seconds elapsed since now. If, for example, + # you want to enable your privilege for 10 minutes, set privilege_expire as 600(seconds). + # return: The RTC token. + def self.build_token_with_user_account(app_id, app_certificate, channel_name, account, role, token_expire, privilege_expire = 0) + access_token = AgoraDynamicKey2::AccessToken.new(app_id, app_certificate, token_expire) service_rtc = AgoraDynamicKey2::ServiceRtc.new(channel_name, account) - service_rtc.add_privilege(AgoraDynamicKey2::ServiceRtc::PRIVILEGE_JOIN_CHANNEL, expire) + service_rtc.add_privilege(AgoraDynamicKey2::ServiceRtc::PRIVILEGE_JOIN_CHANNEL, privilege_expire) if role == ROLE_PUBLISHER - service_rtc.add_privilege(AgoraDynamicKey2::ServiceRtc::PRIVILEGE_PUBLISH_AUDIO_STREAM, expire) - service_rtc.add_privilege(AgoraDynamicKey2::ServiceRtc::PRIVILEGE_PUBLISH_VIDEO_STREAM, expire) - service_rtc.add_privilege(AgoraDynamicKey2::ServiceRtc::PRIVILEGE_PUBLISH_DATA_STREAM, expire) + service_rtc.add_privilege(AgoraDynamicKey2::ServiceRtc::PRIVILEGE_PUBLISH_AUDIO_STREAM, privilege_expire) + service_rtc.add_privilege(AgoraDynamicKey2::ServiceRtc::PRIVILEGE_PUBLISH_VIDEO_STREAM, privilege_expire) + service_rtc.add_privilege(AgoraDynamicKey2::ServiceRtc::PRIVILEGE_PUBLISH_DATA_STREAM, privilege_expire) end access_token.add_service(service_rtc) access_token.build @@ -101,11 +107,11 @@ def self.build_token_with_user_account(app_id, app_certificate, channel_name, ac # set pub_data_stream_privilege_expire as the current Unix timestamp. # @return The new Token def self.build_token_with_uid_and_privilege(app_id, app_certificate, channel_name, uid, token_expire, - join_channel_privilege_expire, pub_audio_privilege_expire, - pub_video_privilege_expire, pub_data_stream_privilege_expire) + join_channel_privilege_expire, pub_audio_privilege_expire, + pub_video_privilege_expire, pub_data_stream_privilege_expire) build_token_with_user_account_and_privilege( - app_id, app_certificate, channel_name, uid, token_expire, join_channel_privilege_expire, - pub_audio_privilege_expire, pub_video_privilege_expire, pub_data_stream_privilege_expire) + app_id, app_certificate, channel_name, uid, token_expire, join_channel_privilege_expire, + pub_audio_privilege_expire, pub_video_privilege_expire, pub_data_stream_privilege_expire) end # Generates an RTC token with the specified privilege. @@ -160,8 +166,8 @@ def self.build_token_with_uid_and_privilege(app_id, app_certificate, channel_nam # set pub_data_stream_privilege_expire as the current Unix timestamp. # @return The new Token def self.build_token_with_user_account_and_privilege(app_id, app_certificate, channel_name, account, token_expire, - join_channel_privilege_expire, pub_audio_privilege_expire, - pub_video_privilege_expire, pub_data_stream_privilege_expire) + join_channel_privilege_expire, pub_audio_privilege_expire, + pub_video_privilege_expire, pub_data_stream_privilege_expire) access_token = AgoraDynamicKey2::AccessToken.new(app_id, app_certificate, token_expire) service_rtc = AgoraDynamicKey2::ServiceRtc.new(channel_name, account) diff --git a/DynamicKey/AgoraDynamicKey/ruby/sample/rtc_token_builder2_sample.rb b/DynamicKey/AgoraDynamicKey/ruby/sample/rtc_token_builder2_sample.rb index eff3b2e2..e3c7dd08 100644 --- a/DynamicKey/AgoraDynamicKey/ruby/sample/rtc_token_builder2_sample.rb +++ b/DynamicKey/AgoraDynamicKey/ruby/sample/rtc_token_builder2_sample.rb @@ -5,20 +5,25 @@ channel_name = '7d72365eb983485397e3e3f9d460bdda' uid = 2882341273 account = "2882341273" -expiration_in_seconds = 3600 +token_expiration_in_seconds = 3600 +privilege_expiration_in_seconds = 3600 -token = AgoraDynamicKey2::RtcTokenBuilder.build_token_with_uid(app_id, app_certificate, channel_name, uid, AgoraDynamicKey2::RtcTokenBuilder::ROLE_SUBSCRIBER, expiration_in_seconds) +token = AgoraDynamicKey2::RtcTokenBuilder.build_token_with_uid( + app_id, app_certificate, channel_name, uid, + AgoraDynamicKey2::RtcTokenBuilder::ROLE_SUBSCRIBER, token_expiration_in_seconds, privilege_expiration_in_seconds) puts "Token with int uid: #{token}" -token = AgoraDynamicKey2::RtcTokenBuilder.build_token_with_user_account(app_id, app_certificate, channel_name, account, AgoraDynamicKey2::RtcTokenBuilder::ROLE_SUBSCRIBER, expiration_in_seconds) +token = AgoraDynamicKey2::RtcTokenBuilder.build_token_with_user_account( + app_id, app_certificate, channel_name, account, + AgoraDynamicKey2::RtcTokenBuilder::ROLE_SUBSCRIBER, token_expiration_in_seconds, privilege_expiration_in_seconds) puts "Token with user account: #{token}" token = AgoraDynamicKey2::RtcTokenBuilder.build_token_with_uid_and_privilege( - app_id, app_certificate, channel_name, uid, expiration_in_seconds, expiration_in_seconds, - expiration_in_seconds, expiration_in_seconds, expiration_in_seconds) + app_id, app_certificate, channel_name, uid, privilege_expiration_in_seconds, privilege_expiration_in_seconds, + privilege_expiration_in_seconds, privilege_expiration_in_seconds, privilege_expiration_in_seconds) puts "Token with int uid and privilege: #{token}" token = AgoraDynamicKey2::RtcTokenBuilder.build_token_with_user_account_and_privilege( - app_id, app_certificate, channel_name, account, expiration_in_seconds, expiration_in_seconds, - expiration_in_seconds, expiration_in_seconds, expiration_in_seconds) + app_id, app_certificate, channel_name, account, privilege_expiration_in_seconds, privilege_expiration_in_seconds, + privilege_expiration_in_seconds, privilege_expiration_in_seconds, privilege_expiration_in_seconds) puts "Token with user account and privilege: #{token}" \ No newline at end of file diff --git a/DynamicKey/AgoraDynamicKey/ruby/test/dynamic_key2/rtc_token_builder_spec.rb b/DynamicKey/AgoraDynamicKey/ruby/test/dynamic_key2/rtc_token_builder_spec.rb index 2cef9087..ba9d8773 100644 --- a/DynamicKey/AgoraDynamicKey/ruby/test/dynamic_key2/rtc_token_builder_spec.rb +++ b/DynamicKey/AgoraDynamicKey/ruby/test/dynamic_key2/rtc_token_builder_spec.rb @@ -10,7 +10,7 @@ let(:uid_s) { '2882341273' } it 'test_build_token_with_uid_ROLE_PUBLISHER' do - token = AgoraDynamicKey2::RtcTokenBuilder.build_token_with_uid(app_id, app_certificate, channel_name, uid, AgoraDynamicKey2::RtcTokenBuilder::ROLE_PUBLISHER, expire) + token = AgoraDynamicKey2::RtcTokenBuilder.build_token_with_uid(app_id, app_certificate, channel_name, uid, AgoraDynamicKey2::RtcTokenBuilder::ROLE_PUBLISHER, expire, expire) access_token = AgoraDynamicKey2::AccessToken.new res = access_token.parse(token) @@ -28,7 +28,7 @@ end it 'test_build_token_with_user_account_ROLE_PUBLISHER' do - token = AgoraDynamicKey2::RtcTokenBuilder.build_token_with_user_account(app_id, app_certificate, channel_name, uid_s, AgoraDynamicKey2::RtcTokenBuilder::ROLE_PUBLISHER, expire) + token = AgoraDynamicKey2::RtcTokenBuilder.build_token_with_user_account(app_id, app_certificate, channel_name, uid_s, AgoraDynamicKey2::RtcTokenBuilder::ROLE_PUBLISHER, expire, expire) access_token = AgoraDynamicKey2::AccessToken.new res = access_token.parse(token) @@ -46,7 +46,7 @@ end it 'test_build_token_with_user_account_ROLE_SUBSCRIBER' do - token = AgoraDynamicKey2::RtcTokenBuilder.build_token_with_user_account(app_id, app_certificate, channel_name, uid_s, AgoraDynamicKey2::RtcTokenBuilder::ROLE_SUBSCRIBER, expire) + token = AgoraDynamicKey2::RtcTokenBuilder.build_token_with_user_account(app_id, app_certificate, channel_name, uid_s, AgoraDynamicKey2::RtcTokenBuilder::ROLE_SUBSCRIBER, expire, expire) access_token = AgoraDynamicKey2::AccessToken.new res = access_token.parse(token) From 082688683dc7d4bd613cd5c3833553bc806ea49d Mon Sep 17 00:00:00 2001 From: lixinhui Date: Wed, 29 Dec 2021 20:21:50 +0800 Subject: [PATCH 17/21] modify comment --- .../python/src/RtcTokenBuilder2.py | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/DynamicKey/AgoraDynamicKey/python/src/RtcTokenBuilder2.py b/DynamicKey/AgoraDynamicKey/python/src/RtcTokenBuilder2.py index 11090daf..c7eb3817 100755 --- a/DynamicKey/AgoraDynamicKey/python/src/RtcTokenBuilder2.py +++ b/DynamicKey/AgoraDynamicKey/python/src/RtcTokenBuilder2.py @@ -19,15 +19,12 @@ def build_token_with_uid(app_id, app_certificate, channel_name, uid, role, token :param channel_name: Unique channel name for the AgoraRTC session in the string format. :param uid: User ID. A 32-bit unsigned integer with a value ranging from 1 to (232-1). optionalUid must be unique. - :param role: - Role_Publisher: A broadcaster/host in a live-broadcast profile. + :param role: Role_Publisher: A broadcaster/host in a live-broadcast profile. Role_Subscriber: An audience(default) in a live-broadcast profile. - :param token_expire: - represented by the number of seconds elapsed since now. If, for example, + :param token_expire: represented by the number of seconds elapsed since now. If, for example, you want to access the Agora Service within 10 minutes after the token is generated, set token_expire as 600(seconds). - :param privilege_expire: - represented by the number of seconds elapsed since now. If, for example, + :param privilege_expire: represented by the number of seconds elapsed since now. If, for example, you want to enable your privilege for 10 minutes, set privilege_expire as 600(seconds). :return: The RTC token. """ @@ -45,15 +42,12 @@ def build_token_with_user_account(app_id, app_certificate, channel_name, account See Get an App Certificate. :param channel_name: Unique channel name for the AgoraRTC session in the string format. :param account: The user's account, max length is 255 Bytes. - :param role: - Role_Publisher: A broadcaster/host in a live-broadcast profile. + :param role: Role_Publisher: A broadcaster/host in a live-broadcast profile. Role_Subscriber: An audience(default) in a live-broadcast profile. - :param token_expire: - represented by the number of seconds elapsed since now. If, for example, + :param token_expire: represented by the number of seconds elapsed since now. If, for example, you want to access the Agora Service within 10 minutes after the token is generated, set token_expire as 600(seconds). - :param privilege_expire: - represented by the number of seconds elapsed since now. If, for example, + :param privilege_expire: represented by the number of seconds elapsed since now. If, for example, you want to enable your privilege for 10 minutes, set privilege_expire as 600(seconds). :return: The RTC token. """ From a1448d53f1196b14e1469c5b4b1c0d5515b95aa4 Mon Sep 17 00:00:00 2001 From: liwenjie-sh <17351105097@163.com> Date: Thu, 30 Dec 2021 15:05:26 +0800 Subject: [PATCH 18/21] add rtc2 privilege code --- .../nodejs/sample/RtcTokenBuilder2Sample.js | 6 +++-- .../nodejs/src/RtcTokenBuilder2.js | 26 ++++++++++--------- 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/DynamicKey/AgoraDynamicKey/nodejs/sample/RtcTokenBuilder2Sample.js b/DynamicKey/AgoraDynamicKey/nodejs/sample/RtcTokenBuilder2Sample.js index 4d702def..d4b72ca1 100644 --- a/DynamicKey/AgoraDynamicKey/nodejs/sample/RtcTokenBuilder2Sample.js +++ b/DynamicKey/AgoraDynamicKey/nodejs/sample/RtcTokenBuilder2Sample.js @@ -8,13 +8,15 @@ const uid = 2882341273 const account = "2882341273" const role = RtcRole.PUBLISHER const expirationInSeconds = 3600 +const tokenExpirationInSecond = 3600 +const privilegeExpirationInSecond = 3600 // Build token with uid -const tokenA = RtcTokenBuilder.buildTokenWithUid(appID, appCertificate, channelName, uid, role, expirationInSeconds) +const tokenA = RtcTokenBuilder.buildTokenWithUid(appID, appCertificate, channelName, uid, role, tokenExpirationInSecond, privilegeExpirationInSecond) console.log("Token with int uid: " + tokenA) // Build token with user account -const tokenB = RtcTokenBuilder.buildTokenWithUserAccount(appID, appCertificate, channelName, account, role, expirationInSeconds) +const tokenB = RtcTokenBuilder.buildTokenWithUserAccount(appID, appCertificate, channelName, account, role, tokenExpirationInSecond, privilegeExpirationInSecond) console.log("Token with user account: " + tokenB) const tokenC = RtcTokenBuilder.buildTokenWithUidAndPrivilege(appID, appCertificate, channelName, uid, diff --git a/DynamicKey/AgoraDynamicKey/nodejs/src/RtcTokenBuilder2.js b/DynamicKey/AgoraDynamicKey/nodejs/src/RtcTokenBuilder2.js index ad7c4a90..a09fcc4c 100644 --- a/DynamicKey/AgoraDynamicKey/nodejs/src/RtcTokenBuilder2.js +++ b/DynamicKey/AgoraDynamicKey/nodejs/src/RtcTokenBuilder2.js @@ -24,11 +24,12 @@ class RtcTokenBuilder { * @param {*} role See #userRole. * - Role.PUBLISHER; RECOMMENDED. Use this role for a voice/video call or a live broadcast. * - Role.SUBSCRIBER: ONLY use this role if your live-broadcast scenario requires authentication for [Hosting-in](https://docs.agora.io/en/Agora%20Platform/terms?platform=All%20Platforms#hosting-in). In order for this role to take effect, please contact our support team to enable authentication for Hosting-in for you. Otherwise, Role_Subscriber still has the same privileges as Role_Publisher. - * @param {*} expire represented by the number of seconds elapsed since 1/1/1970. If, for example, you want to access the Agora Service within 10 minutes after the token is generated, set expireTimestamp as the current timestamp + 600 (seconds). - * @return The new Token. + * @param {*} token_expire epresented by the number of seconds elapsed since now. If, for example, you want to access the Agora Service within 10 minutes after the token is generated, set token_expire as 600(seconds) + * @param {*} privilege_expire represented by the number of seconds elapsed since now. If, for example, you want to enable your privilege for 10 minutes, set privilege_expire as 600(seconds). + * @return The new Token. */ - static buildTokenWithUid(appId, appCertificate, channelName, uid, role, expire) { - return this.buildTokenWithUserAccount(appId, appCertificate, channelName, uid, role, expire) + static buildTokenWithUid(appId, appCertificate, channelName, uid, role, token_expire, privilege_expire = 0) { + return this.buildTokenWithUserAccount(appId, appCertificate, channelName, uid, role, token_expire, privilege_expire) } /** @@ -45,18 +46,19 @@ class RtcTokenBuilder { * @param {*} role See #userRole. * - Role.PUBLISHER; RECOMMENDED. Use this role for a voice/video call or a live broadcast. * - Role.SUBSCRIBER: ONLY use this role if your live-broadcast scenario requires authentication for [Hosting-in](https://docs.agora.io/en/Agora%20Platform/terms?platform=All%20Platforms#hosting-in). In order for this role to take effect, please contact our support team to enable authentication for Hosting-in for you. Otherwise, Role_Subscriber still has the same privileges as Role_Publisher. - * @param {*} expire represented by the number of seconds elapsed since 1/1/1970. If, for example, you want to access the Agora Service within 10 minutes after the token is generated, set expireTimestamp as the current timestamp + 600 (seconds). - * @return The new Token. + * @param {*} token_expire epresented by the number of seconds elapsed since now. If, for example, you want to access the Agora Service within 10 minutes after the token is generated, set token_expire as 600(seconds) + * @param {*} privilege_expire represented by the number of seconds elapsed since now. If, for example, you want to enable your privilege for 10 minutes, set privilege_expire as 600(seconds). + * @return The new Token. */ - static buildTokenWithUserAccount(appId, appCertificate, channelName, account, role, expire) { - let token = new AccessToken(appId, appCertificate, 0, expire) + static buildTokenWithUserAccount(appId, appCertificate, channelName, account, role, token_expire, privilege_expire = 0) { + let token = new AccessToken(appId, appCertificate, 0, token_expire) let serviceRtc = new ServiceRtc(channelName, account) - serviceRtc.add_privilege(ServiceRtc.kPrivilegeJoinChannel, expire) + serviceRtc.add_privilege(ServiceRtc.kPrivilegeJoinChannel, privilege_expire) if (role == Role.PUBLISHER) { - serviceRtc.add_privilege(ServiceRtc.kPrivilegePublishAudioStream, expire) - serviceRtc.add_privilege(ServiceRtc.kPrivilegePublishVideoStream, expire) - serviceRtc.add_privilege(ServiceRtc.kPrivilegePublishDataStream, expire) + serviceRtc.add_privilege(ServiceRtc.kPrivilegePublishAudioStream, privilege_expire) + serviceRtc.add_privilege(ServiceRtc.kPrivilegePublishVideoStream, privilege_expire) + serviceRtc.add_privilege(ServiceRtc.kPrivilegePublishDataStream, privilege_expire) } token.add_service(serviceRtc) From bac85e0d4f099ef19cc47e3125d0c3289049275f Mon Sep 17 00:00:00 2001 From: lixinhui Date: Thu, 30 Dec 2021 15:11:43 +0800 Subject: [PATCH 19/21] support setting token and privilege expiration time --- .../java/io/agora/media/RtcTokenBuilder2.java | 64 ++++++++++--------- .../agora/sample/RtcTokenBuilder2Sample.java | 11 ++-- .../io/agora/media/RtcTokenBuilder2Test.java | 6 +- 3 files changed, 44 insertions(+), 37 deletions(-) diff --git a/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/media/RtcTokenBuilder2.java b/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/media/RtcTokenBuilder2.java index ddb8a061..eb6da6c0 100644 --- a/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/media/RtcTokenBuilder2.java +++ b/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/media/RtcTokenBuilder2.java @@ -16,47 +16,53 @@ public enum Role { /** * Build the RTC token with uid. * - * @param appId: The App ID issued to you by Agora. Apply for a new App ID from - * Agora Dashboard if it is missing from your kit. See Get an App ID. - * @param appCertificate: Certificate of the application that you registered in - * the Agora Dashboard. See Get an App Certificate. - * @param channelName: Unique channel name for the AgoraRTC session in the string format - * @param uid: User ID. A 32-bit unsigned integer with a value ranging from 1 to (232-1). - * optionalUid must be unique. - * @param role: ROLE_PUBLISHER: A broadcaster/host in a live-broadcast profile. - * ROLE_SUBSCRIBER: An audience(default) in a live-broadcast profile. - * @param expire: represented by the number of seconds elapsed since now. If, for example, you want to access the - * Agora Service within 10 minutes after the token is generated, set expireTimestamp as 600(seconds). + * @param appId: The App ID issued to you by Agora. Apply for a new App ID from + * Agora Dashboard if it is missing from your kit. See Get an App ID. + * @param appCertificate: Certificate of the application that you registered in + * the Agora Dashboard. See Get an App Certificate. + * @param channelName: Unique channel name for the AgoraRTC session in the string format + * @param uid: User ID. A 32-bit unsigned integer with a value ranging from 1 to (232-1). + * optionalUid must be unique. + * @param role: ROLE_PUBLISHER: A broadcaster/host in a live-broadcast profile. + * ROLE_SUBSCRIBER: An audience(default) in a live-broadcast profile. + * @param token_expire: represented by the number of seconds elapsed since now. If, for example, + * you want to access the Agora Service within 10 minutes after the token is generated, + * set token_expire as 600(seconds). + * @param privilege_expire: represented by the number of seconds elapsed since now. If, for example, + * you want to enable your privilege for 10 minutes, set privilege_expire as 600(seconds). * @return The RTC token. */ - public String buildTokenWithUid(String appId, String appCertificate, String channelName, int uid, Role role, int expire) { - return buildTokenWithUserAccount(appId, appCertificate, channelName, AccessToken2.getUidStr(uid), role, expire); + public String buildTokenWithUid(String appId, String appCertificate, String channelName, int uid, Role role, int token_expire, int privilege_expire) { + return buildTokenWithUserAccount(appId, appCertificate, channelName, AccessToken2.getUidStr(uid), role, token_expire, privilege_expire); } /** * Build the RTC token with account. * - * @param appId: The App ID issued to you by Agora. Apply for a new App ID from - * Agora Dashboard if it is missing from your kit. See Get an App ID. - * @param appCertificate: Certificate of the application that you registered in - * the Agora Dashboard. See Get an App Certificate. - * @param channelName: Unique channel name for the AgoraRTC session in the string format - * @param account: The user's account, max length is 255 Bytes. - * @param role: ROLE_PUBLISHER: A broadcaster/host in a live-broadcast profile. - * ROLE_SUBSCRIBER: An audience(default) in a live-broadcast profile. - * @param expire: represented by the number of seconds elapsed since now. If, for example, you want to access the - * Agora Service within 10 minutes after the token is generated, set expireTimestamp as 600(seconds). + * @param appId: The App ID issued to you by Agora. Apply for a new App ID from + * Agora Dashboard if it is missing from your kit. See Get an App ID. + * @param appCertificate: Certificate of the application that you registered in + * the Agora Dashboard. See Get an App Certificate. + * @param channelName: Unique channel name for the AgoraRTC session in the string format + * @param account: The user's account, max length is 255 Bytes. + * @param role: ROLE_PUBLISHER: A broadcaster/host in a live-broadcast profile. + * ROLE_SUBSCRIBER: An audience(default) in a live-broadcast profile. + * @param token_expire: represented by the number of seconds elapsed since now. If, for example, + * you want to access the Agora Service within 10 minutes after the token is generated, + * set token_expire as 600(seconds). + * @param privilege_expire: represented by the number of seconds elapsed since now. If, for example, + * you want to enable your privilege for 10 minutes, set privilege_expire as 600(seconds). * @return The RTC token. */ - public String buildTokenWithUserAccount(String appId, String appCertificate, String channelName, String account, Role role, int expire) { - AccessToken2 accessToken = new AccessToken2(appId, appCertificate, expire); + public String buildTokenWithUserAccount(String appId, String appCertificate, String channelName, String account, Role role, int token_expire, int privilege_expire) { + AccessToken2 accessToken = new AccessToken2(appId, appCertificate, token_expire); AccessToken2.Service serviceRtc = new AccessToken2.ServiceRtc(channelName, account); - serviceRtc.addPrivilegeRtc(AccessToken2.PrivilegeRtc.PRIVILEGE_JOIN_CHANNEL, expire); + serviceRtc.addPrivilegeRtc(AccessToken2.PrivilegeRtc.PRIVILEGE_JOIN_CHANNEL, privilege_expire); if (role == Role.ROLE_PUBLISHER) { - serviceRtc.addPrivilegeRtc(AccessToken2.PrivilegeRtc.PRIVILEGE_PUBLISH_AUDIO_STREAM, expire); - serviceRtc.addPrivilegeRtc(AccessToken2.PrivilegeRtc.PRIVILEGE_PUBLISH_VIDEO_STREAM, expire); - serviceRtc.addPrivilegeRtc(AccessToken2.PrivilegeRtc.PRIVILEGE_PUBLISH_DATA_STREAM, expire); + serviceRtc.addPrivilegeRtc(AccessToken2.PrivilegeRtc.PRIVILEGE_PUBLISH_AUDIO_STREAM, privilege_expire); + serviceRtc.addPrivilegeRtc(AccessToken2.PrivilegeRtc.PRIVILEGE_PUBLISH_VIDEO_STREAM, privilege_expire); + serviceRtc.addPrivilegeRtc(AccessToken2.PrivilegeRtc.PRIVILEGE_PUBLISH_DATA_STREAM, privilege_expire); } accessToken.addService(serviceRtc); diff --git a/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/sample/RtcTokenBuilder2Sample.java b/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/sample/RtcTokenBuilder2Sample.java index 01d0d8e0..93f78214 100644 --- a/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/sample/RtcTokenBuilder2Sample.java +++ b/DynamicKey/AgoraDynamicKey/java/src/main/java/io/agora/sample/RtcTokenBuilder2Sample.java @@ -9,20 +9,21 @@ public class RtcTokenBuilder2Sample { static String channelName = "7d72365eb983485397e3e3f9d460bdda"; static String account = "2082341273"; static int uid = 2082341273; - static int expirationInSeconds = 3600; + static int tokenExpirationInSeconds = 3600; + static int privilegeExpirationInSeconds = 3600; public static void main(String[] args) { RtcTokenBuilder2 token = new RtcTokenBuilder2(); - String result = token.buildTokenWithUid(appId, appCertificate, channelName, uid, Role.ROLE_SUBSCRIBER, expirationInSeconds); + String result = token.buildTokenWithUid(appId, appCertificate, channelName, uid, Role.ROLE_SUBSCRIBER, tokenExpirationInSeconds, privilegeExpirationInSeconds); System.out.println("Token with uid: " + result); - result = token.buildTokenWithUserAccount(appId, appCertificate, channelName, account, Role.ROLE_SUBSCRIBER, expirationInSeconds); + result = token.buildTokenWithUserAccount(appId, appCertificate, channelName, account, Role.ROLE_SUBSCRIBER, tokenExpirationInSeconds, privilegeExpirationInSeconds); System.out.println("Token with account: " + result); - result = token.buildTokenWithUid(appId, appCertificate, channelName, uid, expirationInSeconds, expirationInSeconds, expirationInSeconds, expirationInSeconds, expirationInSeconds); + result = token.buildTokenWithUid(appId, appCertificate, channelName, uid, privilegeExpirationInSeconds, privilegeExpirationInSeconds, privilegeExpirationInSeconds, privilegeExpirationInSeconds, privilegeExpirationInSeconds); System.out.println("Token with uid and privilege: " + result); - result = token.buildTokenWithUserAccount(appId, appCertificate, channelName, account, expirationInSeconds, expirationInSeconds, expirationInSeconds, expirationInSeconds, expirationInSeconds); + result = token.buildTokenWithUserAccount(appId, appCertificate, channelName, account, privilegeExpirationInSeconds, privilegeExpirationInSeconds, privilegeExpirationInSeconds, privilegeExpirationInSeconds, privilegeExpirationInSeconds); System.out.println("Token with account and privilege: " + result); } } diff --git a/DynamicKey/AgoraDynamicKey/java/src/test/java/io/agora/media/RtcTokenBuilder2Test.java b/DynamicKey/AgoraDynamicKey/java/src/test/java/io/agora/media/RtcTokenBuilder2Test.java index 807a44b9..b172b397 100644 --- a/DynamicKey/AgoraDynamicKey/java/src/test/java/io/agora/media/RtcTokenBuilder2Test.java +++ b/DynamicKey/AgoraDynamicKey/java/src/test/java/io/agora/media/RtcTokenBuilder2Test.java @@ -15,7 +15,7 @@ public class RtcTokenBuilder2Test { @Test public void buildTokenWithUid_ROLE_PUBLISHER() { RtcTokenBuilder2 rtcTokenBuilder = new RtcTokenBuilder2(); - String token = rtcTokenBuilder.buildTokenWithUid(appId, appCertificate, channelName, uid, RtcTokenBuilder2.Role.ROLE_PUBLISHER, expire); + String token = rtcTokenBuilder.buildTokenWithUid(appId, appCertificate, channelName, uid, RtcTokenBuilder2.Role.ROLE_PUBLISHER, expire, expire); AccessToken2 accessToken = new AccessToken2(); accessToken.parse(token); @@ -32,7 +32,7 @@ public void buildTokenWithUid_ROLE_PUBLISHER() { @Test public void buildTokenWithUserAccount_ROLE_PUBLISHER() { RtcTokenBuilder2 rtcTokenBuilder = new RtcTokenBuilder2(); - String token = rtcTokenBuilder.buildTokenWithUserAccount(appId, appCertificate, channelName, uidStr, RtcTokenBuilder2.Role.ROLE_PUBLISHER, expire); + String token = rtcTokenBuilder.buildTokenWithUserAccount(appId, appCertificate, channelName, uidStr, RtcTokenBuilder2.Role.ROLE_PUBLISHER, expire, expire); AccessToken2 accessToken = new AccessToken2(); accessToken.parse(token); @@ -49,7 +49,7 @@ public void buildTokenWithUserAccount_ROLE_PUBLISHER() { @Test public void buildTokenWithUserAccount_ROLE_SUBSCRIBER() { RtcTokenBuilder2 rtcTokenBuilder = new RtcTokenBuilder2(); - String token = rtcTokenBuilder.buildTokenWithUserAccount(appId, appCertificate, channelName, uidStr, RtcTokenBuilder2.Role.ROLE_SUBSCRIBER, expire); + String token = rtcTokenBuilder.buildTokenWithUserAccount(appId, appCertificate, channelName, uidStr, RtcTokenBuilder2.Role.ROLE_SUBSCRIBER, expire, expire); AccessToken2 accessToken = new AccessToken2(); accessToken.parse(token); From af805b934d08c434549da8a76dbf4ae0b0c81100 Mon Sep 17 00:00:00 2001 From: luyucheng Date: Thu, 30 Dec 2021 15:29:22 +0800 Subject: [PATCH 20/21] support setting token and privilege expiration time --- .../php/sample/RtcTokenBuilder2Sample.php | 11 +++++---- .../php/src/RtcTokenBuilder2.php | 24 +++++++++---------- .../php/test/RtcTokenBuilder2Test.php | 6 ++--- 3 files changed, 21 insertions(+), 20 deletions(-) diff --git a/DynamicKey/AgoraDynamicKey/php/sample/RtcTokenBuilder2Sample.php b/DynamicKey/AgoraDynamicKey/php/sample/RtcTokenBuilder2Sample.php index d56af75d..5367340e 100644 --- a/DynamicKey/AgoraDynamicKey/php/sample/RtcTokenBuilder2Sample.php +++ b/DynamicKey/AgoraDynamicKey/php/sample/RtcTokenBuilder2Sample.php @@ -6,16 +6,17 @@ $channelName = "7d72365eb983485397e3e3f9d460bdda"; $uid = 2882341273; $uidStr = "2882341273"; -$expirationInSeconds = 3600; +$tokenExpirationInSeconds = 3600 +$privilegeExpirationInSeconds = 3600 -$token = RtcTokenBuilder2::buildTokenWithUid($appId, $appCertificate, $channelName, $uid, RtcTokenBuilder2::ROLE_PUBLISHER, $expirationInSeconds); +$token = RtcTokenBuilder2::buildTokenWithUid($appId, $appCertificate, $channelName, $uid, RtcTokenBuilder2::ROLE_PUBLISHER, $tokenExpirationInSeconds, $privilegeExpirationInSeconds); echo 'Token with int uid: ' . $token . PHP_EOL; -$token = RtcTokenBuilder2::buildTokenWithUserAccount($appId, $appCertificate, $channelName, $uidStr, RtcTokenBuilder2::ROLE_PUBLISHER, $expirationInSeconds); +$token = RtcTokenBuilder2::buildTokenWithUserAccount($appId, $appCertificate, $channelName, $uidStr, RtcTokenBuilder2::ROLE_PUBLISHER, $tokenExpirationInSeconds, $privilegeExpirationInSeconds); echo 'Token with user account: ' . $token . PHP_EOL; -$token = RtcTokenBuilder2::buildTokenWithUidAndPrivilege($appId, $appCertificate, $channelName, $uid, $expirationInSeconds, $expirationInSeconds, $expirationInSeconds, $expirationInSeconds, $expirationInSeconds); +$token = RtcTokenBuilder2::buildTokenWithUidAndPrivilege($appId, $appCertificate, $channelName, $uid, $privilegeExpirationInSeconds, $privilegeExpirationInSeconds, $privilegeExpirationInSeconds, $privilegeExpirationInSeconds, $privilegeExpirationInSeconds); echo 'Token with int uid and privilege: ' . $token . PHP_EOL; -$token = RtcTokenBuilder2::buildTokenWithUserAccountAndPrivilege($appId, $appCertificate, $channelName, $uidStr, $expirationInSeconds, $expirationInSeconds, $expirationInSeconds, $expirationInSeconds, $expirationInSeconds); +$token = RtcTokenBuilder2::buildTokenWithUserAccountAndPrivilege($appId, $appCertificate, $channelName, $uidStr, $privilegeExpirationInSeconds, $privilegeExpirationInSeconds, $privilegeExpirationInSeconds, $privilegeExpirationInSeconds, $privilegeExpirationInSeconds); echo 'Token with user account and privilege: ' . $token . PHP_EOL; diff --git a/DynamicKey/AgoraDynamicKey/php/src/RtcTokenBuilder2.php b/DynamicKey/AgoraDynamicKey/php/src/RtcTokenBuilder2.php index c2d7fc5a..48f94498 100644 --- a/DynamicKey/AgoraDynamicKey/php/src/RtcTokenBuilder2.php +++ b/DynamicKey/AgoraDynamicKey/php/src/RtcTokenBuilder2.php @@ -19,13 +19,13 @@ class RtcTokenBuilder2 * optionalUid must be unique. * @param $role : ROLE_PUBLISHER: A broadcaster/host in a live-broadcast profile. * ROLE_SUBSCRIBER: An audience(default) in a live-broadcast profile. - * @param $expire : represented by the number of seconds elapsed since now. If, for example, you want to access the - * Agora Service within 10 minutes after the token is generated, set expireTimestamp as 600(seconds). + * @param $tokenExpire : Represented by the number of seconds elapsed since now. If, for example, you want to access the Agora Service within 10 minutes after the token is generated, set $tokenExpire as 600(seconds). + * @param $privilegeExpire :Represented by the number of seconds elapsed since now. If, for example, you want to enable your privilege for 10 minutes, set $privilegeExpire as 600(seconds). * @return The RTC token. */ - public static function buildTokenWithUid($appId, $appCertificate, $channelName, $uid, $role, $expire) + public static function buildTokenWithUid($appId, $appCertificate, $channelName, $uid, $role, $tokenExpire, $privilegeExpire = 0) { - return self::buildTokenWithUserAccount($appId, $appCertificate, $channelName, $uid, $role, $expire); + return self::buildTokenWithUserAccount($appId, $appCertificate, $channelName, $uid, $role, $tokenExpire, $privilegeExpire); } /** @@ -39,20 +39,20 @@ public static function buildTokenWithUid($appId, $appCertificate, $channelName, * @param $account : The user's account, max length is 255 Bytes. * @param $role : ROLE_PUBLISHER: A broadcaster/host in a live-broadcast profile. * ROLE_SUBSCRIBER: An audience(default) in a live-broadcast profile. - * @param $expire : represented by the number of seconds elapsed since now. If, for example, you want to access the - * Agora Service within 10 minutes after the token is generated, set expireTimestamp as 600(seconds). + * @param $tokenExpire : Represented by the number of seconds elapsed since now. If, for example, you want to access the Agora Service within 10 minutes after the token is generated, set $tokenExpire as 600(seconds). + * @param $privilegeExpire :Represented by the number of seconds elapsed since now. If, for example, you want to enable your privilege for 10 minutes, set $privilegeExpire as 600(seconds). * @return The RTC token. */ - public static function buildTokenWithUserAccount($appId, $appCertificate, $channelName, $account, $role, $expire) + public static function buildTokenWithUserAccount($appId, $appCertificate, $channelName, $account, $role, $tokenExpire, $privilegeExpire = 0) { - $token = new AccessToken2($appId, $appCertificate, $expire); + $token = new AccessToken2($appId, $appCertificate, $tokenExpire); $serviceRtc = new ServiceRtc($channelName, $account); - $serviceRtc->addPrivilege($serviceRtc::PRIVILEGE_JOIN_CHANNEL, $expire); + $serviceRtc->addPrivilege($serviceRtc::PRIVILEGE_JOIN_CHANNEL, $privilegeExpire); if ($role == self::ROLE_PUBLISHER) { - $serviceRtc->addPrivilege($serviceRtc::PRIVILEGE_PUBLISH_AUDIO_STREAM, $expire); - $serviceRtc->addPrivilege($serviceRtc::PRIVILEGE_PUBLISH_VIDEO_STREAM, $expire); - $serviceRtc->addPrivilege($serviceRtc::PRIVILEGE_PUBLISH_DATA_STREAM, $expire); + $serviceRtc->addPrivilege($serviceRtc::PRIVILEGE_PUBLISH_AUDIO_STREAM, $privilegeExpire); + $serviceRtc->addPrivilege($serviceRtc::PRIVILEGE_PUBLISH_VIDEO_STREAM, $privilegeExpire); + $serviceRtc->addPrivilege($serviceRtc::PRIVILEGE_PUBLISH_DATA_STREAM, $privilegeExpire); } $token->addService($serviceRtc); diff --git a/DynamicKey/AgoraDynamicKey/php/test/RtcTokenBuilder2Test.php b/DynamicKey/AgoraDynamicKey/php/test/RtcTokenBuilder2Test.php index b289ae9c..9201e93c 100644 --- a/DynamicKey/AgoraDynamicKey/php/test/RtcTokenBuilder2Test.php +++ b/DynamicKey/AgoraDynamicKey/php/test/RtcTokenBuilder2Test.php @@ -24,7 +24,7 @@ public function run() public function test_buildTokenWithUid_ROLE_PUBLISHER() { - $token = RtcTokenBuilder2::buildTokenWithUid($this->appId, $this->appCertificate, $this->channelName, $this->uid, RtcTokenBuilder2::ROLE_PUBLISHER, $this->expire); + $token = RtcTokenBuilder2::buildTokenWithUid($this->appId, $this->appCertificate, $this->channelName, $this->uid, RtcTokenBuilder2::ROLE_PUBLISHER, $this->expire, $this->expire); $accessToken = new AccessToken2(); $accessToken->parse($token); @@ -41,7 +41,7 @@ public function test_buildTokenWithUid_ROLE_PUBLISHER() public function test_buildTokenWithUserAccount_ROLE_PUBLISHER() { - $token = RtcTokenBuilder2::buildTokenWithUserAccount($this->appId, $this->appCertificate, $this->channelName, $this->account, RtcTokenBuilder2::ROLE_PUBLISHER, $this->expire); + $token = RtcTokenBuilder2::buildTokenWithUserAccount($this->appId, $this->appCertificate, $this->channelName, $this->account, RtcTokenBuilder2::ROLE_PUBLISHER, $this->expire, $this->expire); $accessToken = new AccessToken2(); $accessToken->parse($token); @@ -58,7 +58,7 @@ public function test_buildTokenWithUserAccount_ROLE_PUBLISHER() public function test_buildTokenWithUserAccount_ROLE_SUBSCRIBER() { - $token = RtcTokenBuilder2::buildTokenWithUserAccount($this->appId, $this->appCertificate, $this->channelName, $this->account, RtcTokenBuilder2::ROLE_SUBSCRIBER, $this->expire); + $token = RtcTokenBuilder2::buildTokenWithUserAccount($this->appId, $this->appCertificate, $this->channelName, $this->account, RtcTokenBuilder2::ROLE_SUBSCRIBER, $this->expire, $this->expire); $accessToken = new AccessToken2(); $accessToken->parse($token); From a3559db55efec429d61e284b2fb7492ac0c50d18 Mon Sep 17 00:00:00 2001 From: liwenjie-sh <17351105097@163.com> Date: Thu, 30 Dec 2021 22:10:15 +0800 Subject: [PATCH 21/21] add ut code --- .../nodejs/test/RtcTokenBuilder2Test.js | 203 +++++++++--------- 1 file changed, 103 insertions(+), 100 deletions(-) diff --git a/DynamicKey/AgoraDynamicKey/nodejs/test/RtcTokenBuilder2Test.js b/DynamicKey/AgoraDynamicKey/nodejs/test/RtcTokenBuilder2Test.js index a7279be2..0bbbf765 100644 --- a/DynamicKey/AgoraDynamicKey/nodejs/test/RtcTokenBuilder2Test.js +++ b/DynamicKey/AgoraDynamicKey/nodejs/test/RtcTokenBuilder2Test.js @@ -3,103 +3,106 @@ * nodeunit test/RtcTokenBuilder2Test.js * see https://github.com/caolan/nodeunit */ -const RtcTokenBuilder = require('../src/RtcTokenBuilder2').RtcTokenBuilder -const Role = require('../src/RtcTokenBuilder2').Role -const {AccessToken2, ServiceRtc, kRtcServiceType} = require('../src/AccessToken2') - -const appId = "970CA35de60c44645bbae8a215061b33" -const appCertificate = "5CFd2fd1755d40ecb72977518be15d3b" -const channelName = "7d72365eb983485397e3e3f9d460bdda" -const uid = 2882341273 -const uidStr = "2882341273" -const expire = 600 - -exports.buildTokenWithUid_SUBSCRIBER_Test = function (test) { - let token = RtcTokenBuilder.buildTokenWithUid(appId, appCertificate, channelName, uid, Role.SUBSCRIBER, expire) - let accessToken = new AccessToken2('', '', 0, 0) - accessToken.from_string(token) - - test.equal(appId, accessToken.appId) - test.equal(expire, accessToken.expire) - test.equal(channelName, accessToken.services[kRtcServiceType].__channel_name) - test.equal(uidStr, accessToken.services[kRtcServiceType].__uid) - test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegeJoinChannel]) - test.done() -} - -exports.buildTokenWithUid_PUBLISHER_Test = function (test) { - let token = RtcTokenBuilder.buildTokenWithUid(appId, appCertificate, channelName, uid, Role.PUBLISHER, expire) - let accessToken = new AccessToken2('', '', 0, 0) - accessToken.from_string(token) - - test.equal(appId, accessToken.appId) - test.equal(expire, accessToken.expire) - test.equal(channelName, accessToken.services[kRtcServiceType].__channel_name) - test.equal(uidStr, accessToken.services[kRtcServiceType].__uid) - test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegeJoinChannel]) - test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegePublishAudioStream]) - test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegePublishVideoStream]) - test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegePublishDataStream]) - test.done() -} - -exports.buildTokenWithUserAccount_SUBSCRIBER_Test = function (test) { - let token = RtcTokenBuilder.buildTokenWithUserAccount(appId, appCertificate, channelName, uidStr, Role.SUBSCRIBER, expire) - let accessToken = new AccessToken2('', '', 0, 0) - accessToken.from_string(token) - - test.equal(appId, accessToken.appId) - test.equal(expire, accessToken.expire) - test.equal(channelName, accessToken.services[kRtcServiceType].__channel_name) - test.equal(uidStr, accessToken.services[kRtcServiceType].__uid) - test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegeJoinChannel]) - test.done() -} - -exports.buildTokenWithUserAccount_PUBLISHER_Test = function (test) { - let token = RtcTokenBuilder.buildTokenWithUserAccount(appId, appCertificate, channelName, uid, Role.PUBLISHER, expire) - let accessToken = new AccessToken2('', '', 0, 0) - accessToken.from_string(token) - - test.equal(appId, accessToken.appId) - test.equal(expire, accessToken.expire) - test.equal(channelName, accessToken.services[kRtcServiceType].__channel_name) - test.equal(uidStr, accessToken.services[kRtcServiceType].__uid) - test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegeJoinChannel]) - test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegePublishAudioStream]) - test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegePublishVideoStream]) - test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegePublishDataStream]) - test.done() -} - -exports.buildTokenWithUidAndPrivilege_Test = function (test) { - let token = RtcTokenBuilder.buildTokenWithUidAndPrivilege(appId, appCertificate, channelName, uid, expire, expire, expire, expire, expire) - let accessToken = new AccessToken2('', '', 0, 0) - accessToken.from_string(token) - - test.equal(appId, accessToken.appId) - test.equal(expire, accessToken.expire) - test.equal(channelName, accessToken.services[kRtcServiceType].__channel_name) - test.equal(uidStr, accessToken.services[kRtcServiceType].__uid) - test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegeJoinChannel]) - test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegePublishAudioStream]) - test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegePublishVideoStream]) - test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegePublishDataStream]) - test.done() -} - -exports.BuildTokenWithUserAccountAndPrivilege_Test = function (test) { - let token = RtcTokenBuilder.BuildTokenWithUserAccountAndPrivilege(appId, appCertificate, channelName, uidStr, expire, expire, expire, expire, expire) - let accessToken = new AccessToken2('', '', 0, 0) - accessToken.from_string(token) - - test.equal(appId, accessToken.appId) - test.equal(expire, accessToken.expire) - test.equal(channelName, accessToken.services[kRtcServiceType].__channel_name) - test.equal(uidStr, accessToken.services[kRtcServiceType].__uid) - test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegeJoinChannel]) - test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegePublishAudioStream]) - test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegePublishVideoStream]) - test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegePublishDataStream]) - test.done() -} \ No newline at end of file + const RtcTokenBuilder = require('../src/RtcTokenBuilder2').RtcTokenBuilder + const Role = require('../src/RtcTokenBuilder2').Role + const {AccessToken2, ServiceRtc, kRtcServiceType} = require('../src/AccessToken2') + + const appId = "970CA35de60c44645bbae8a215061b33" + const appCertificate = "5CFd2fd1755d40ecb72977518be15d3b" + const channelName = "7d72365eb983485397e3e3f9d460bdda" + const uid = 2882341273 + const uidStr = "2882341273" + const expire = 600 + + const tokenExpirationInSecond = 600 + const privilegeExpirationInSecond = 600 + + exports.buildTokenWithUid_SUBSCRIBER_Test = function (test) { + let token = RtcTokenBuilder.buildTokenWithUid(appId, appCertificate, channelName, uid, Role.SUBSCRIBER, tokenExpirationInSecond, privilegeExpirationInSecond) + let accessToken = new AccessToken2('', '', 0, 0) + accessToken.from_string(token) + + test.equal(appId, accessToken.appId) + test.equal(expire, accessToken.expire) + test.equal(channelName, accessToken.services[kRtcServiceType].__channel_name) + test.equal(uidStr, accessToken.services[kRtcServiceType].__uid) + test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegeJoinChannel]) + test.done() + } + + exports.buildTokenWithUid_PUBLISHER_Test = function (test) { + let token = RtcTokenBuilder.buildTokenWithUid(appId, appCertificate, channelName, uid, Role.PUBLISHER, tokenExpirationInSecond, privilegeExpirationInSecond) + let accessToken = new AccessToken2('', '', 0, 0) + accessToken.from_string(token) + + test.equal(appId, accessToken.appId) + test.equal(expire, accessToken.expire) + test.equal(channelName, accessToken.services[kRtcServiceType].__channel_name) + test.equal(uidStr, accessToken.services[kRtcServiceType].__uid) + test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegeJoinChannel]) + test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegePublishAudioStream]) + test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegePublishVideoStream]) + test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegePublishDataStream]) + test.done() + } + + exports.buildTokenWithUserAccount_SUBSCRIBER_Test = function (test) { + let token = RtcTokenBuilder.buildTokenWithUserAccount(appId, appCertificate, channelName, uidStr, Role.SUBSCRIBER, tokenExpirationInSecond, privilegeExpirationInSecond) + let accessToken = new AccessToken2('', '', 0, 0) + accessToken.from_string(token) + + test.equal(appId, accessToken.appId) + test.equal(expire, accessToken.expire) + test.equal(channelName, accessToken.services[kRtcServiceType].__channel_name) + test.equal(uidStr, accessToken.services[kRtcServiceType].__uid) + test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegeJoinChannel]) + test.done() + } + + exports.buildTokenWithUserAccount_PUBLISHER_Test = function (test) { + let token = RtcTokenBuilder.buildTokenWithUserAccount(appId, appCertificate, channelName, uid, Role.PUBLISHER, tokenExpirationInSecond, privilegeExpirationInSecond) + let accessToken = new AccessToken2('', '', 0, 0) + accessToken.from_string(token) + + test.equal(appId, accessToken.appId) + test.equal(expire, accessToken.expire) + test.equal(channelName, accessToken.services[kRtcServiceType].__channel_name) + test.equal(uidStr, accessToken.services[kRtcServiceType].__uid) + test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegeJoinChannel]) + test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegePublishAudioStream]) + test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegePublishVideoStream]) + test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegePublishDataStream]) + test.done() + } + + exports.buildTokenWithUidAndPrivilege_Test = function (test) { + let token = RtcTokenBuilder.buildTokenWithUidAndPrivilege(appId, appCertificate, channelName, uid, expire, expire, expire, expire, expire) + let accessToken = new AccessToken2('', '', 0, 0) + accessToken.from_string(token) + + test.equal(appId, accessToken.appId) + test.equal(expire, accessToken.expire) + test.equal(channelName, accessToken.services[kRtcServiceType].__channel_name) + test.equal(uidStr, accessToken.services[kRtcServiceType].__uid) + test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegeJoinChannel]) + test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegePublishAudioStream]) + test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegePublishVideoStream]) + test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegePublishDataStream]) + test.done() + } + + exports.BuildTokenWithUserAccountAndPrivilege_Test = function (test) { + let token = RtcTokenBuilder.BuildTokenWithUserAccountAndPrivilege(appId, appCertificate, channelName, uidStr, expire, expire, expire, expire, expire) + let accessToken = new AccessToken2('', '', 0, 0) + accessToken.from_string(token) + + test.equal(appId, accessToken.appId) + test.equal(expire, accessToken.expire) + test.equal(channelName, accessToken.services[kRtcServiceType].__channel_name) + test.equal(uidStr, accessToken.services[kRtcServiceType].__uid) + test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegeJoinChannel]) + test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegePublishAudioStream]) + test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegePublishVideoStream]) + test.equal(expire, accessToken.services[kRtcServiceType].__privileges[ServiceRtc.kPrivilegePublishDataStream]) + test.done() + } \ No newline at end of file