視頻聊天

必須使用HTTPS協議

/* Wait for the page to load */
$(function() {
    console.log("[DEMO] :: Rainbow Application started!");

    /**
     * 這裏的applicationID和applicationSecret 你需要去阿爾卡特官網註冊一個應用
     * 訪問  https://hub.myopenrainbow.com.cn/#/dashboard/applications
     * 點擊 Applications 創建一個應用 將創建好的applicationID和applicationSecret填寫在下方
     */
    // china prod
    var applicationID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    var applicationSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

    /* Bootstrap the SDK */
    angular.bootstrap(document, ["sdk"]).get("rainbowSDK");

    /* Callback for handling the event 'RAINBOW_ONREADY' */
    /* 準備召喚彩虹 */
    var onReady = function onReady() {
        console.log("[DEMO] :: On SDK Ready !");
        console.log("[DEMO] :: SDK version " + rainbowSDK.version());
        // do something when the SDK is ready
        // 當SDK準備好的時候做點什麼
        var myRainbowLogin = "[email protected]";         //用戶的賬號,也可以做好和自己的系統賬號做映射     Replace by your login
        var myRainbowPassword = '123456@501';       //用戶的登錄密碼    Replace by your password
        // 選項卡切換
        $("#tab li").click(function(){
            $(this).addClass("cur").siblings().removeClass("cur");
            var index = $(this).index();
            $("#boxwap .box").eq(index).addClass("active").siblings().removeClass("active");
        })

        // The SDK for Web is ready to be used, so you can sign in
        // Web的SDK已準備好使用,因此您可以登錄
        rainbowSDK.connection.signinOnRainbowHosted(myRainbowLogin, myRainbowPassword, "myopenrainbow.com.cn")
        .then(function(account) {
            // Successfully signed to Rainbow and the SDK is started completely. Rainbow data can be retrieved.
            // 已成功登錄彩虹,並且已完全啓動SDK。彩虹數據可以被檢索。
            console.log("[DEMO] :: Login success !");

            // setup mic and camera input devices
            // 設置麥克風和相機輸入設備
            setupDevices();

            // make video call
            // 打視頻電話
            makeVideoCall();

            // 獲取歷史消息 Get history message
            getHistoryMessageRecord(); 

            $("#send").click(function(){
                // IM聊天
                sendChatMessage(account.userData.displayName);
            })            

        })
        .catch(function(err) {
              // An error occurs (e.g. bad credentials). Application could be informed that sign in has failed
              console.log("[DEMO] :: Login failed !");
        });
    };

    /* Callback for handling the event 'RAINBOW_ONCONNECTIONSTATECHANGED' */
    /* 彩虹彩虹事件召喚 */
    var onLoaded = function onLoaded() {
        console.log("[DEMO] :: On SDK Loaded !");

        // Activate full SDK log
        // 激活完整的SDK日誌
        rainbowSDK.setVerboseLog(true);

        rainbowSDK
            .initialize(applicationID, applicationSecret)
            .then(function() {
                console.log("[DEMO] :: Rainbow SDK is initialized!");
            })
            .catch(function(err) {
                console.log("[DEMO] :: Something went wrong with the SDK...", err);
            });
    };

    /* Listen to the SDK event RAINBOW_ONREADY */
    /* 收聽SDK事件RAINBOW_ONREADY */
    $(document).on(rainbowSDK.RAINBOW_ONREADY, onReady);

    /* Listen to the SDK event RAINBOW_ONLOADED */
    /* 收聽加載的SDK事件RAINBOW */
    $(document).on(rainbowSDK.RAINBOW_ONLOADED, onLoaded);

    /* 當webrtc調用的狀態更改時,會觸發此事件 */
    $(document).on(rainbowSDK.webRTC.RAINBOW_ONWEBRTCCALLSTATECHANGED, onWebRTCCallChanged);
    $(document).on(rainbowSDK.webRTC.RAINBOW_ONWEBRTCTRACKCHANGED, onWebRTCTrackChanged);

    /* 監聽接收的文字信息 */
    // $(document).on(rainbowSDK.im.RAINBOW_ONNEWIMMESSAGERECEIVED, onNewMessageReceived);
    $(document).on(rainbowSDK.im.RAINBOW_ONNEWIMMESSAGERECEIVED, onNewMessageReceived);


    /* Load the SDK */
    /* 加載SDK */
    rainbowSDK.load();

    // 設置麥克風和相機輸入設備
    function setupDevices() {
        /* Somewhere in your application... Ask the user to authorize the application to access to the media devices */
        /* 在你的申請中。。。要求用戶授權應用程序訪問媒體設備 */
        navigator.mediaDevices.getUserMedia({audio: true, video: true}).then(function(stream) {
            /* Stream received which means that the user has authorized the application to access to the audio and video devices. Local stream can be stopped at this time */
            /* 接收到的流,這意味着用戶已授權應用程序訪問音頻和視頻設備。此時可以停止本地流 */
            stream.getTracks().forEach(function(track) {
                track.stop();
            });

            /*  Get the list of available devices */
            /* 獲取可用設備的列表 */
            navigator.mediaDevices.enumerateDevices().then(function(devices) {
                /* Do something for each device (e.g. add it to a selector list) */
                /* 爲每個設備做點什麼,如 將其添加到選擇器列表中 */
                var microphoneDevice = null;
                var speaker = null;
                var camera = null;

                devices.forEach(function(device) {
                    switch (device.kind) {
                        case "audioinput":
                            // This is a device of type 'microphone'
                            // 這是“麥克風”類型的設備
                            console.log("[DEMO] :: microphone ID:" + device.deviceId + " label:" + device.label);
                            if(microphoneDevice == null)
                                microphoneDevice = device;

                            break;
                        case "audiooutput":
                            // This is a device of type 'speaker'
                            // 這是一種“揚聲器”類型的設備
                            console.log("[DEMO] :: speaker ID:" + device.deviceId + " label:" + device.label);
                            if(speaker == null)
                                speaker = device;

                            break;
                        case "videoinput":
                            // This is a device of type 'camera'
                            // 這是“照相機”類型的設備
                            console.log("[DEMO] :: camera ID:" + device.deviceId + " label:" + device.label);
                            if(camera == null)
                                camera = device;
                            break;
                        default:
                            break;
                    }
                });

                /* Select the microphone to use */
                /* 選擇要使用的麥克風 */
                console.log("[DEMO] :: Set mic to " + microphoneDevice.deviceId + " " + microphoneDevice.label);
                rainbowSDK.webRTC.useMicrophone(microphoneDevice.deviceId);

                /* Select the speaker to use */
                /* 選擇要使用的揚聲器 */
                console.log("[DEMO] :: Set speaker to " + speaker.deviceId + " " + speaker.label);
                rainbowSDK.webRTC.useSpeaker(speaker.deviceId);

                /* Select the camera to use */
                /* 選擇要使用的相機 */
                console.log("[DEMO] :: Set camera to " + camera.deviceId + " " + camera.label);
                rainbowSDK.webRTC.useCamera(camera.deviceId);
            }).catch(function(error) {
                /* In case of error when enumerating the devices */
                /* 如果枚舉設備時出錯 */
            });
        }).catch(function(error) {
            /* In case of error when authorizing the application to access the media devices */
            /* 授權應用程序訪問媒體設備時出錯 */
        });
    };

    // make a video call
    // 打視頻電話
    function makeVideoCall() {
        // find your remote party ID using Rainbow CLI tool on sandbox platform
        // 使用sandbox平臺上的Rainbow CLI工具查找遠程參與方ID
        var remotePartyID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';         // 對方的遠程id

        // retrieve the remote party contact
        // 檢索遠程方聯繫人
        rainbowSDK.contacts.searchById(remotePartyID).then(function(entityFound) {
            if(entityFound) {
                // Do something with the entity found
                // 對找到的實體做些什麼
                console.log("[DEMO] :: Found remote party !");

                // make a video call to selected remote party
                // 對選定的遠程方進行視頻呼叫
                callInVideo(entityFound);
            } else {
                // No entity returned
                // 未返回任何實體
            }
        }).catch(function(error) {
            /* In case of error when searching for contact */
            /* 如果在搜索聯繫人時出錯 */
        });
    };

    function onWebRTCCallChanged(event) {
        console.log("[DEMO] :: onWebRTCCallChanged", event);
        let call = event.originalEvent.detail;
    
        /* Listen to WebRTC call state change */
        if (call.status.value === "incommingCall") {
            // You have an incoming call, do something about it:
            console.log("[DEMO] :: Incoming call");
    
            // Detect the type of incoming call
            if (call.remoteMedia === 3) {
                // The incoming call is of type audio + video
                rainbowSDK.webRTC.answerInVideo(call);
    
                // Populate the #minivideo and #largevideo elements with the video streams
                rainbowSDK.webRTC.showLocalVideo();
                rainbowSDK.webRTC.showRemoteVideo(call);
            } else if (call.remoteMedia === 1) {
                // The incoming call is of type audio
                rainbowSDK.webRTC.answerInAudio(call);
            }
        } else if (call.status.value == "active") {
            // call is active, show local video stream
            console.log("[DEMO] :: onWebRTCCallChanged active");
            rainbowSDK.webRTC.showLocalVideo(call);
        }

        /* Listen to WebRTC call state change */
        /* 偵聽WebRTC調用狀態更改 */
        // if (call.status.value === "incommingCall") {
        //     // You have an incoming call, do something about it:
        //     // 你有一個來電,做點什麼:
        //     console.log("[DEMO] :: Incoming call");

        //     // Detect the type of incoming call
        //     // 檢測傳入呼叫的類型
        //     if (call.remoteMedia === 3) {
        //         // The incoming call is of type audio + video
        //         // 來電類型爲音頻+視頻
        //         rainbowSDK.webRTC.answerInVideo(call);

        //         // Populate the #minivideo and #largevideo elements with the video streams
        //         // 用視頻流填充“minivideo”和“largevideo”元素
        //         rainbowSDK.webRTC.showLocalVideo();
        //         // 顯示遠程對方視頻
        //         rainbowSDK.webRTC.showRemoteVideo(call);
        //     } else if (call.remoteMedia === 1) {
        //         // The incoming call is of type audio
        //         // 來電類型爲音頻
        //         rainbowSDK.webRTC.answerInAudio(call);
        //     }
        // } else if (call.status.value == "active") {
        //     // call is active, show local video stream
        //     // 呼叫處於活動狀態,顯示本地視頻流
        //     rainbowSDK.webRTC.showLocalVideo(call);
        // }
    };

    // WebRTC tracks changed = video has been added or removed
    // WebRTC已經改變 = 已添加或刪除視頻
    var onWebRTCTrackChanged = function onWebRTCTrackChanged(event) {
        console.log("[DEMO] :: onWebRTCTrackChanged", event);
        let call = event.originalEvent.detail;
    
        // Manage remote video
        if (call.remoteMedia & call.Media.VIDEO) {
            rainbowSDK.webRTC.showRemoteVideo(call);
        } else {
            rainbowSDK.webRTC.hideRemoteVideo(call);
        }
        // Manage local video
        if (call.localMedia & call.Media.VIDEO) {
            rainbowSDK.webRTC.showLocalVideo(call);
        } else {
            rainbowSDK.webRTC.hideLocalVideo(call);
        }

        // // Manage remote video
        // // 管理遠程視頻
        // if (call.remoteMedia & call.Media.VIDEO) {
        //     // 顯示與呼叫關聯的遠程視頻 必須爲true
        //     rainbowSDK.webRTC.showRemoteVideo(call);
        // } else {
        //     // 隱藏與呼叫關聯的遠程視頻
        //     rainbowSDK.webRTC.hideRemoteVideo(call);
        // }
        // // Manage local video
        // // 管理本地視頻
        // if (call.localMedia & call.Media.VIDEO) {
        //     // 顯示本地視頻(圖片中的圖片) 必須爲true
        //     rainbowSDK.webRTC.showLocalVideo(call);
        // } else {
        //     // 隱藏本地視頻(圖片中的圖片) 必須爲true
        //     rainbowSDK.webRTC.hideLocalVideo(call);
        // }
    };

    function callInVideo(contact) {
        /* Call this API to call a contact using video */
        /* 調用此API以使用視頻調用聯繫人 */
        var res = rainbowSDK.webRTC.callInVideo(contact);
        if(res.label === "OK") {
            /* Your call has been correctly initiated. Waiting for the other peer to answer */
            /* 您的呼叫已正確啓動。等待對方回答 */
            console.log("[DEMO] :: call started !");
        } else {
            console.log("[DEMO] :: call failed ! ");
            console.dir(res);
        }
    };


    // send a chat message
    // 發送聊天信息
    function sendChatMessage(myName) {
        // find your remote party ID using Rainbow CLI tool on sandbox platform
        // 使用sandbox平臺上的Rainbow CLI工具查找遠程參與方ID
        var remotePartyID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
        
        /* 
        if remote party is in your contact list, you can use getContactByJID() or getContactById()
        else you can use searchContactByJid(), searchContactById() or searchContactByName().

        if you want to get your whole contact list, you can use getAll() and iterate through all the Contact objects
        */
        /**
            如果遠程方在聯繫人列表中,則可以使用getContactByJID()或getContactById()
            否則可以使用searchContactByJid()、searchContactById()或searchContactByName()。

            如果要獲取整個聯繫人列表,可以使用getAll()並遍歷所有聯繫人對象
        */

        // retrieve the remote party contact by ID
        // 按ID檢索遠程方聯繫人
        rainbowSDK.contacts.searchById(remotePartyID).then(function (entityFound) {
            if (entityFound) {
                // Do something with the entity found
                // 對找到的實體做些什麼
                console.log("[DEMO] :: Found remote party !", entityFound);
                // 建立連接
                rainbowSDK.conversations.openConversationForContact(entityFound).then(function(conversation) {
                    // 發生信息
                    // rainbowSDK.im.sendMessageToConversation(conversation, "Hello World222222");
                    rainbowSDK.im.sendMessageToConversation(conversation, $("#sendInput").val());
                    var masg = $("#sendInput").val()
                    // 添加到窗口
                    $("#chatwap").append("<div class='chatitemright'><div class='message'><div class='username'>沈總</div><div class='messagecon'>"+masg+"</div></div><div class='headPortrait'><img src='2.png'></div></div>");
                    // $("#chatwap").append("<div class='chatitemright'><div class='message'><div class='username'>"+myName+"</div><div class='messagecon'>"+masg+"</div></div><div class='headPortrait'><img src='2.png'></div></div>");
                    $("#sendInput").val("")

                    $("#boxwap").scrollTop($("#chatwap").height());
                }).catch(function(err) {
                    console.log("[DEMO] :: Error retrieving conversation");
                });
            } else {
                // No entity returned
                // 未返回任何實體
                console.log("[DEMO] :: No contact found")
            }
        }).catch(function (error) {
            /* In case of error when searching for contact */
            /* 如果在搜索聯繫人時出錯

    */
            console.log("[DEMO] :: Error retrieving contact", error);
        });
    };


    // 獲取歷史消息記錄 Get history message record
    function getHistoryMessageRecord(){
        var remotePartyID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
        rainbowSDK.contacts.searchById(remotePartyID).then(function (entityFound) {
            if (entityFound) {
                // Do something with the entity found
                // 對找到的實體做些什麼
                console.log("[DEMO] :: Found remote party !", entityFound);
                // 建立連接
                rainbowSDK.conversations.openConversationForContact(entityFound).then(function(conversation) {
                    // // 發生信息
                    // // rainbowSDK.im.sendMessageToConversation(conversation, "Hello World222222");
                    // rainbowSDK.im.sendMessageToConversation(conversation, $("#sendInput").val());

                    // 獲取歷史消息 Get history message
                    // getHistoryMessageRecord(conversation);
                        // var currentPage = 0;
                        rainbowSDK.im.getMessagesFromConversation(conversation, 30).then(function(resp) {
                            // The conversation object is updated with the messages retrieved from the server (same reference)
                            console.log("]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]")
                            console.log(resp)
                            console.log("]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]")
                            for(var i=0;i<resp.messages.length;i++){
                                if(resp.messages[i].data.indexOf("GMT+0800")==-1){   
                                    if(resp.messages[i].side=="R"){ // 自己
                                        $("#chatwap").append("<div class='chatitemright'><div class='message'><div class='username'>沈總</div><div class='messagecon'>"+resp.messages[i].data+"</div></div><div class='headPortrait'><img src='2.png'></div></div>");
                                        // $("#chatwap").append("<div class='chatitemright'><div class='message'><div class='username'>"+resp.messages[i].from.name.value+"</div><div class='messagecon'>"+resp.messages[i].data+"</div></div><div class='headPortrait'><img src='2.png'></div></div>");
                                    }else if(resp.messages[i].side=="L"){ // 對方
                                        $("#chatwap").append("<div class='chatitemleft'><div class='headPortrait'><img src='1.png'></div><div class='message'><div class='username'>"+resp.messages[i].from.name.value+"</div><div class='messagecon'>"+resp.messages[i].data+"</div></div></div>");
                                    }
                                }
                            }
                            console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
                            // Call a function to display the new messages received
                            // displayMessages(conversation, currentPage);
                            // Display something if there is possibly more messages on the server
                            if(!conversation.historyComplete) {
                                // e.g. display a button to get more messages
                            }
                        })
                }).catch(function(err) {
                    console.log("[DEMO] :: Error retrieving conversation");
                });
            } else {
                // No entity returned
                // 未返回任何實體
                console.log("[DEMO] :: No contact found")
            }
        }).catch(function (error) {
            /* In case of error when searching for contact */
            /* 如果在搜索聯繫人時出錯
            */
            console.log("[DEMO] :: Error retrieving contact", error);
        });
    }

    // 獲取新消息
    function onNewMessageReceived(event) {
        console.log("[DEMO] :: onNewMessageReceived", event);
        let msgObj = event.originalEvent.detail.message;
        let msg = msgObj.data;
        let fromContact = msgObj.from;
        $("#chatwap").append("<div class='chatitemleft'><div class='headPortrait'><img src='1.png'></div><div class='message'><div class='username'>"+fromContact.firstname+fromContact.lastname+"</div><div class='messagecon'>"+msg+"</div></div></div>");
        $("#boxwap").scrollTop($("#chatwap").height());
        console.log("--------------------------------------------------------------------------------------------------------------")
        console.log("[DEMO] :: new msg from " + fromContact.firstname + " " +fromContact.lastname + " " + msg);
    }
});

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章