chat-websocket.js 23.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
var socket;

// 名前空間
var CHAT_SOCKET = {};

CHAT_SOCKET.connectSocket = function () {
    if (IS_ONLINE == 'true') {
        socket = io(CHAT_SERVER_URL);
        setSocketAction();
    } else {
        //オフラインの場合、DBからルーム一覧を表示。
        if (CHAT_UTIL.isIOS()) {
             //TODO IOSの場合
        } else if (CHAT_UTIL.isAndroid()) {
Lee Munkyeong committed
15

16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
        }
    }
};

/* ---------------------------------------------------
 * Socket Connect/Disconnectc
 * --------------------------------------------------- */
function setSocketAction () {
    socket.on('connect', function() {
        // socketが接続されたらチャット画面で画面を更新する
        $('.overlay').removeClass('active undismissable');
        // loadingIndicatorを表示
        CHAT_UI.showLoadingIndicator();
        // チャットルームに入場する際、sid, loginId, shopName, roomId, roomNameの情報を取得しNodeJsに渡す
        if (CHAT_UTIL.isIOS()) {
            webkit.messageHandlers.loginInfoRequestMessageHandlerId.postMessage({});
        } else if (CHAT_UTIL.isAndroid()) {
            android.getLoginParameter();
        }
        CHAT_UI.dismissLoadingIndicator();
    });

38
    socket.on('disconnect', function() {
39 40 41 42 43 44
        //socketが切断されたら黒画面で画面を更新する
        $('.overlay').addClass('active undismissable');
        //alert('Disconnected from the server');
        CHAT_UI.dismissLoadingIndicator();
    });

45
    socket.on('connect_error', function() {
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
        CHAT_UI.dismissLoadingIndicator();
    });

    /* ----------------------------------------------------------------------
     *
     * Chat Room List Tab
     *
     * ---------------------------------------------------------------------- */

    // Update Room List
    //TODO APIの連動が終わったら削除予定
    /*socket.on('refreshRoomList', function(rooms, activeRoomId = null){
        CHAT.globalIsInvite = false;


        // #36146に対応
        let keywordSearchMode = false;
        if ($('#room-search').val().length > 0) {
            keywordSearchMode = true;
        }

        $('#room_list').html('');
        let roomListTitle = getLocalizedString("roomListTitle");
        $('.titleRoomName').text(roomListTitle);

        if (rooms.length === 0) {
            // #36146に対応
            // 検索結果がない場合のメッセージを追加
            if (!keywordSearchMode) {
                let emptyListString = getLocalizedString("roomListEmptyString")
                $('#room_list').append(`<center class="text-secondary">${emptyListString}</center>`);
            } else {
                let emptyListString = getLocalizedString("searchRoomListEmptyString")
                $('#room_list').append(`<center class="text-secondary">${emptyListString}</center>`);
            }
        }

        // チャットルームの様式を読み込む
        const template = $('#room-template').html();

        rooms.forEach( function(room) {
            room.profileImagePath = ASSET_PATH + 'images/user-profile.png'

            if (room.message) {
                room.message = room.message.toString()
            } else {
                room.message = getLocalizedString("noMessages")
            }

            let html = Mustache.render(template, {
                roomName: room.roomName,
                roomId: room.roomId,
                profileImage: room.profileImagePath,
                active: activeRoomId === room.roomId ? 'active_chat' : null, // 現在、入っているルームだとhilight表示
                lastMessage: room.message.includes('<img') ? getLocalizedString("image") : (keywordSearchMode ? `${room.message}${getLocalizedString("searchResult")}` : room.message) ,
                time: room.time ? CHAT_UTIL.formatDate(room.time.time).createdAt : '',
                unreadMsgCnt: room.unreadCnt,
                userCnt: room.userCnt
            });

            // Click event
            let obj = $(jQuery.parseHTML(html)).on('click',function(){
                if (activeRoomId === room.roomId) {
                    // 既存チャットルームをタッチする場合、チャット画面に遷移
                    $('#pills-chat-tab').tab('show');
                } else {
                    // loadingIndicatorを表示しない
                    CHAT_UI.showLoadingIndicator();
                    // 新しいチャットルームをタッチする場合、チャットルームの接続処理を実行
                    socket.emit('joinRoom', room.roomId, room.roomName, function (){
                        CHAT.saveRoomInfo(room.roomId, room.roomName);
                        $('#messages').html('');
                        // チャットルーム名を変更する
                        $('.titleRoomName').text(room.roomName).data('roomName', room.roomName);
                    });
                }
            });
            // チャットルームリストに追加する
            $('#room_list').append(obj);
        });

        // #36146に対応
        if(rooms.length > 0) {
            if(!keywordSearchMode) {
                $(".roomListIcon").show()
                $('#roomDeleteButton, #arrangeRooms').show()
            } else {
                $(".roomListIcon").show()
                $('#roomDeleteButton, #arrangeRooms').hide()
            }
        } else {
            if(!keywordSearchMode) {
                $(".roomListIcon").hide()
            } else {
                $(".roomListIcon").show()
                $('#roomDeleteButton, #arrangeRooms').hide()
            }
        }

        $('#createChatRoom').show()

        // Rotate
        if(CHAT_UI.isLandscapeMode()) {
            $(".chat_list").removeClass("col-12").addClass("col-6");
        }

        $("#userSelectionDeleteBtn").hide();
        // チャットルームリスト画面に遷移
        $('#pills-chatlist-tab').tab('show');

        // loadingIndicatorを表示しない
        CHAT_UI.dismissLoadingIndicator();
    });*/

    // New Message
    // #36170
162
    socket.on('newMessage', function(message, roomId, roomName) {
Lee Munkyeong committed
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
        var userMessageTemplate;
        $.get({ url: "./template/template_user_message.html", async: false }
          , function(text) {
            userMessageTemplate = text;
        });
        var myMessageTemplate;
        $.get({ url: "./template/template_my_message.html", async: false }
          , function(text) {
            myMessageTemplate = text;
        });
        var systemMessageTemplate;
        $.get({ url: "./template/template_system_message.html", async: false }
          , function(text) {
            systemMessageTemplate = text;
        });
178 179 180 181 182
        var openCollaborationMessageTemplate;
        $.get({ url: "./template/template_open_collaboration_message.html", async: false }
          , function(text) {
            openCollaborationMessageTemplate = text;
        });
Lee Munkyeong committed
183 184

        let template = userMessageTemplate;
185 186
        if (message.id === socket.id) {
            // ユーザーが送信したメッセージの場合、自分のメッセージ様式を適用して表示する
Lee Munkyeong committed
187
            template = myMessageTemplate;
188
        }
Lee Munkyeong committed
189 190 191 192 193 194 195
        let messageTime = CHAT_UTIL.formatDate(message.createdAt);
        message.profileImagePath = CHAT.getProfileImgUrl(message.profileImagePath)
        try {
            message.text = decodeURIComponent(message.text)
        } catch(e) {
            message.text = message.text
        }
196
        let type;
197
        let collaborationType;
Lee Munkyeong committed
198
        if ( message.text.includes(messageSeperator) ) {
199 200
            let text = message.text.split(messageSeperator);
            message.text = text[0];
201 202
            type = text[1];
            if (type == messageType.COMMUNICATIONSTART || type == messageType.COMMUNICATIONEND) {
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
                collaborationType = text[2];
                var userInCollaboration;
                if (CHAT_UTIL.isIOS()) {
                    userInCollaboration = JSON.parse(CHAT_DB.getUserInfoList(message.userId));
                } else if (CHAT_UTIL.isAndroid()) {
                    userInCollaboration = JSON.parse(android.getUserInfoList(message.userId));
                }
                userInCollaboration.forEach(function(user) {
                    user.profileUrl = CHAT.getProfileImgUrl(user.profileUrl);
                })
                template = openCollaborationMessageTemplate;
                let html = Mustache.render(template, {
                     roomName: roomName,
                     userCount: 1,
                     userList: userInCollaboration,
                     insertDate: message.insertDate,
                     collaborationType: collaborationType,
                     isToday: true,
                     createdAtDay: messageTime.createdAtDay,
                     createdAtTime: messageTime.createdAtTime,
                     isOtherYear: false
                 });
                 $('#messages').append(html);
            } else {
                var replacePath = message.text;
                replacePath = replacePath.replaceAll('?fileName=', '?sid=' + CHAT.globalLoginParameter.sid + '&fileName=');
                message.text = replacePath;
                //TODO newMessageの際にDB格納が必要。

                let html = Mustache.render(template, {
                    text: message.text,
                    from: message.from,
                    profileImage: message.profileImagePath,
                    shopMemberId: message.userId,
                    createdAtDay: messageTime.createdAtDay,
                    createdAtTime: messageTime.createdAtTime,
                    isToday: true
                });
                // イメージの場合、img tagを追加する
                html = message.text.includes('attachedImages') || message.text.includes('attachedVideos') ? CHAT_UTIL.htmlDecode(html) : html;
                $('#messages').append(html);
            }
Lee Munkyeong committed
245
        }
246

Lee Munkyeong committed
247
        // 画像、動画の描画を待ってからスクロール
248 249
        setTimeout(function () {
            CHAT_UI.scrollToBottom();
Lee Munkyeong committed
250
        }, 300);
251 252 253
    });

    // Notification
254
    socket.on('newNotification', function(keyword, event) {
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
        var notificationString = getLocalizedString(event, keyword)
        $('#messageNotification').finish().text(notificationString).delay(500).slideDown().delay(1500).slideUp();
    });

    // 新しいメッセージを受信する場合の処理
    // #36170
//    socket.on('loadMessages', function(messages, shopMemberId, users, roomId, roomName){
//        let jQueryMessages = $('#messages');
//        // スクロールの変化を防ぐため以前画面の高さを保存する
//        let beforeHeight = jQueryMessages.prop('scrollHeight');
//        // メッセージ文字列の生成
//        let workVal = "";
//        messages.forEach(function(message) {
//            let template = $('#message-template').html();
//            if (message.shopMemberId == shopMemberId) {
//                 template = $('#message-template-me').html();
//            }
//            let messageTime = CHAT_UTIL.formatDate(message.time.time);
//
//            if (users != undefined) {
//                let user = users.find((user) => user.loginId == message.loginId)
//
//                // userProfilePathが使えるpathかをcheckして使えないpathの場合、default画像の経路に変更
//                if (user) {
//                     message.profileImagePath = CHAT.getProfileImgUrl(user.profileImagePath)
//                } else {
//                     message.profileImagePath = CHAT.getProfileImgUrl("")
//                }
//            } else {
//                message.profileImagePath = CHAT.getProfileImgUrl(message.profileImagePath)
//            }
//
//             // #36147
//             message.message = message.message.toString();
//             var replacePath = message.message;
//             replacePath = replacePath.replaceAll('/acms',CHAT_SERVER_URL+'/acms');
//             message.message = replacePath;
//             let html = Mustache.render(template, {
//                 text: message.message,
//                 from: message.loginId,
//                 profileImage: message.profileImagePath,
//                 createdAtDay: messageTime.createdAtDay,
//                 createdAtTime: messageTime.createdAtTime
//             });
//             html = message.message.includes('attachedImages') || message.message.includes('attachedVideos') ? CHAT_UTIL.htmlDecode(html) : html;
//             workVal = html + workVal;
//        })
//
//        // メッセージの画面描画
//        jQueryMessages.prepend(workVal);
//        if (beforeHeight !== 0) {
//            // 追加のメッセージ読み込み時は読み込み前のスクロール位置を維持
//            setTimeout(function () {
//                jQueryMessages.scrollTop(jQueryMessages.prop('scrollHeight') - beforeHeight);
//            }, 400);
//        } else {
//            // 新規に入室の場合は最下部へスクロール
//            CHAT_UI.waitForLoadingImage(jQueryMessages, CHAT_UI.scrollToBottom);
//            // タブレット等、画面サイズが大きい場合、スクロール出来なくならないよう追加で10件メッセージを取得
//            if ($(window).height() > jQueryMessages.height()) {
//                $('#messages').scroll();
//            }
//        }
//
//        // ユーザ削除ボタン表示しない
//        $("#userSelectionDeleteBtn").hide();
//
//        CHAT_UI.dismissLoadingIndicator();// add some...
//
//        // チャットに遷移する
//        $('#pills-chat-tab').tab('show');
//    });

    // Update User List In Room
    // サイドバーのユーザーリストアップデート。
Lee Munkyeong committed
330 331 332 333
/*    socket.on('updateUserList', function(users, onlineUsers) {
        console.log(users);
        console.log(onlineUsers);

334 335 336 337 338
        if (users.length > 0) {
            $('#users').removeData();
            $('#users').data(users);
        } else {
            const data = $('#users').data();
339
            if (data && Object.keys(data).length > 0) {
340 341 342 343 344 345 346 347 348 349
                 users = Object.keys(data).map(function(key) {
                     return data[key];
                });
            }
        }

        const ul = $('<ul/>', {class: 'list-unstyled components'});
        // ユーザーリストを入れる前にユーザー招待ボタンを入れてくれる。
        let inviteString = getLocalizedString("inviteUsersButton")

350
        ul.append($('<li/>').append(`<a>${inviteString} <i class='fa fa-user-plus'><i/></a>`).on('click', function(event) {
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
            $('#dismiss').click();
            // loadingIndicatorを表示
            CHAT_UI.showLoadingIndicator();
            let isInvite = true;
            CHAT.globalIsInvite = isInvite;
            socket.emit('getGroupList', isInvite);
        }));

        // ユーザーリストを入れる
        users.forEach(function(user) {
             let li = $('<li/>');
             let a = $('<a/>').text(user);
             if (onlineUsers.includes(user)) {
             // 接続されているユーザにバッジを付ける。
             a.append($('<span/>',{class:'badge badge-success'}).text('online'));
            }
            li.append(a);
            ul.append(li);
        });
    $('#users').html(ul);
Lee Munkyeong committed
371
    });*/
372 373

    // Update Group List(Invite)
374
    socket.on('refreshGroupList', function(groups, isInvite) {
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
        $('#group_list').html('');
        const template = $('#group-template').html();
        if (groups.length === 0) {
            $('#group_list').append('<center class="text-secondary">'+ getLocalizedString(everyoneIsHere) +'</center>');
        }
        // グループ名と人数を表記する。
        groups.forEach(function(group) {
            let html = Mustache.render(template, {
                name: group.groupName,
                info: group.memberCnt + getLocalizedString("people")
            });
            // グループをクリックすると、該当グループのユーザーリストを読み込むようにイベントを与える
            let obj = $(jQuery.parseHTML(html)).on('click', function() {
                // loadingIndicatorを表示
                CHAT_UI.showLoadingIndicator();
                socket.emit('getUserListInGroup', group.groupId, isInvite);
                $('#groupName').text(group.groupName);
            });
            $('#group_list').append(obj);
        });

        // Rotate
        if (CHAT_UI.isLandscapeMode()) {
            $(".group_list").addClass("col-6").removeClass("col-12");
        }

        // Set Title
        let memberSelectTitle = getLocalizedString("groupSearch")

        $('#pills-group-tab').tab('show');

        $('#backButton').show();

        if (isInvite) {
            $('.titleRoomName').text(memberSelectTitle);
            $('#newRoomName, .roomListIcon, .chatRoomIcon').hide();
            $('#userSelectionConfirmBtn').show();
412
            $("#userSelectionConfirmBtn").off().on('click', function() {
413 414 415 416 417 418
                CHAT_UI.setConfirmButtonEvent(isInvite);
            });
        } else {
            $('.titleRoomName').text(memberSelectTitle);
            $('.roomListIcon, .chatRoomIcon, #newRoomName').hide();
            $('#userSelectionConfirmBtn').show();
419
            $("#userSelectionConfirmBtn").off().on('click', function() {
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
                CHAT_UI.setConfirmButtonEvent(isInvite);
            });
        }

        if (CHAT.globalSelectedUserList.length > 0) {
            $('#userSelectionLength').text(CHAT.globalSelectedUserList.length);
        } else {
            $('#userSelectionLength').text('');
        }

        $('#backButton').off().on('click', function() {
            // loadingIndicatorを表示
            CHAT_UI.showLoadingIndicator();
            if (isInvite) {
                $('#pills-chat-tab').tab('show');
            } else {
                if (IS_ONLINE == 'true') {
                    android.updateRoomList();
                    CHAT_UI.refreshRoomList(chatRoomType.DM);
                    CHAT_UI.dismissLoadingIndicator();
                }
            }
        });
    });

    // Update User List(Invite)
    // #36170
447
    socket.on('refreshUserListInGroup', function(users, groupId, isInvite) {
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
        $('#user_list').html('');
        const template = $('#user-template').html();

        // Set Title
        let memberSelectTitle = getLocalizedString("userSearch")
        $('.titleRoomName').text(memberSelectTitle);

        users.forEach( function(user) {
            // loadingIndicatorを表示
            CHAT_UI.showLoadingIndicator();

            user.profileImagePath = CHAT.getProfileImgUrl(user.profileImagePath)

            let html = Mustache.render(template, {
                id: user.shopMemberId,
                profileImage: user.profileImagePath,
                name: user.loginId
            });

            // クリックするとactive クラスを与え、チェック表示を出させる。
468
            let obj = $(jQuery.parseHTML(html)).on('click',function() {
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
                if ($(this).find('.userCheckBox.active').length > 0) {
                    // remove
                    CHAT.globalSelectedUserList = CHAT.globalSelectedUserList.filter(function(element) {
                        return user.loginId != element.loginId;
                    });
                } else {
                    // add
                    CHAT.globalSelectedUserList.push({loginId:user.loginId, shopMemberId : user.shopMemberId, profileImagePath: user.profileImagePath});
                }
                $(this).find('.userCheckBox').toggleClass('active');

                if (CHAT.globalSelectedUserList.length > 0) {
                    $('#userSelectionLength').text(CHAT.globalSelectedUserList.length);
                } else {
                    $('#userSelectionLength').text('');
                }
            });

            let findObj = CHAT.globalSelectedUserList.find(function(selectedUser) {
                return selectedUser.loginId == user.loginId;
            })

            if (findObj) {
                $(obj).find('.userCheckBox').toggleClass('active');
            }

            $('#user_list').append(obj);
        })
        $('.userCheckBox').show();

        // Rotate
        if (CHAT_UI.isLandscapeMode()) {
            $(".user_list").addClass("col-6").removeClass("col-12");
            $(".squareBoxContent span").addClass("landscape_span");
        }

        $('#backButton').off().on('click', function() {
            // loadingIndicatorを表示
            CHAT_UI.showLoadingIndicator();
            socket.emit('getGroupList', isInvite)
        });

511
        $("#userSelectionConfirmBtn").off().on('click', function() {
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
            // loadingIndicatorを表示
            CHAT_UI.showLoadingIndicator();
            CHAT_UI.setConfirmButtonEvent(isInvite);
        });

        $('#backButton').show();
        $('.roomListIcon, .chatRoomIcon').hide();
        $('#userSelectionConfirmBtn').show();
        $('.userCheckBox').show();
        $('#pills-user-tab').tab('show');
    });

    /* ---------------------------------------------------------------------- */
    /* Show Error Log */
    /* ---------------------------------------------------------------------- */

528
    socket.on('showServerError', function(message) {
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
        // #36174

        // #36215
        if (message.includes("SC_FORBIDDEN"))
        {
            alert('SC_FORBIDDEN');
            return;
        }

        if (message == 'server error Ocurred') {
            message = getLocalizedString("serverErrorOccured");
        } else if (message == 'Room not found') {
            message = getLocalizedString("errorRoomNotFound");
        }
        $("#customAlertTitle").text(message);
        $("#customAlertOk").text(getLocalizedString("yesTitle"));

        $('#customAlert').appendTo("body").modal({
            backdrop: 'static',
            keyboard: false
        })
        .on('click', '#customAlertOk', function(e) {
        });
        CHAT_UI.dismissLoadingIndicator();

554
        if (message == "Room not found") {
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
            CHAT.saveRoomInfo();
        }
    });

    // server's request : user info (retry join)
    socket.on("retryJoinProcess", () => {
        var ua = window.navigator.userAgent.toLowerCase();
        //if ((ua.indexOf('iphone') > 0 || ua.indexOf('ipad') > 0) && ua.indexOf("safari") == -1) {
        if (CHAT_UTIL.isIOS()) {
            // iosでの場合
            webkit.messageHandlers.loginInfoRequestMessageHandlerId.postMessage({});
        // } else if (ua.indexOf('android') > 0 && ua.indexOf('linux') == -1){
        } else if (CHAT_UTIL.isAndroid()) {
            // androidでの場合
            android.getLoginParameter();
        } else {
            CHAT_UI.htmlElementTextInitialize("ko")
            // webでのsocket connect
            socket.emit('join', params, function(err) {
                if (err) {
                    // #36174
                    $("#customAlertTitle").text(err);
                    $("#customAlertOk").text(getLocalizedString("yesTitle"));

                    $('#customAlert').appendTo("body").modal({
                        backdrop: 'static',
                        keyboard: false
                    })
                    .on('click', '#customAlertOk', function(e) {
                    });
                } else {
                    if (params.roomName != undefined) {
                        $('.titleRoomName').text(params.roomName).data('roomName', params.roomName);
                    } else {
                        let roomListTitle = getLocalizedString("roomListTitle")
                        $('.titleRoomName').text(roomListTitle)
                    }
                }
                // loadingIndicatorを表示しない
                CHAT_UI.dismissLoadingIndicator();
            });
        }
    })
}