chat.js 10 KB
Newer Older
Kim Peace committed
1 2
// 名前空間
var CHAT = {};
Kim Peace committed
3
// test comment
Kim Peace committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 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 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 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 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
//招待するメンバーを保存する変数
CHAT.globalSelectedUserList = new Array();
CHAT.globalIsInvite = false;

//ログイン中の部屋情報を保存する変数
CHAT.globalLoginParameter;

CHAT.saveRoomInfo = function(roomId, roomName) {
    CHAT.globalLoginParameter.roomId = roomId;
    CHAT.globalLoginParameter.roomName = roomName;
    if (CHAT_UTIL.isIOS()) {
        webkit.messageHandlers.roomInfosaveMessageHandlerId.postMessage({"roomId":roomId, "roomName":roomName});
    } else if (CHAT_UTIL.isAndroid()) {
        if (roomId == undefined && roomName == undefined) {
            android.saveVisitRoomInfo('', '');
        } else {
            android.saveVisitRoomInfo(roomId, roomName);
        }
    }
}

// #36170 画像パスが存在しない場合はデフォルトの画像を返す
// 存在する場合はプロフィール画像取得用APIのURLを生成して返す
CHAT.getProfileImgUrl = function(path) {
    if (path == undefined || path == "") {
        return ASSET_PATH + 'images/user-profile.png';
    } else {
        var userInfo = path.split("/").reverse();
        return CMS_SERVER_URL + '/file/getProfileImage?profileFileName=' + userInfo[0] + '&profileGetLoginId=' + userInfo[1];
    }
}

// Video のサムネイルファイル生成する
CHAT.createVideoThumbnailAndUpload = function(sourceImage, callback) {
    var fileReader = new FileReader();

    fileReader.onload = function() {
        var blob = new Blob([fileReader.result], {type: sourceImage.type});
        var url = URL.createObjectURL(blob);
        var video = document.createElement('video');
        var timeupdate = function() {
            if (snapImage()) {
                video.removeEventListener('timeupdate', timeupdate);
                video.pause();
            }
        };
        video.addEventListener('loadeddata', function() {
            if (snapImage()) {
                video.removeEventListener('timeupdate', timeupdate);
            }
        });
        var snapImage = function() {
            var canvas = document.createElement('canvas');
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);

            fetch(canvas.toDataURL("image/jpeg"))
                .then(function(res) {
                    return res.arrayBuffer();
                })
                .then(function(buf) {
                    // 回転された画像をFormDataに保存
                    const newFile = new File([buf], sourceImage.name, {type:"image/jpeg"});
                    callback(newFile, true);
                    // ajax End
                }).catch((error) => { // fetch Error catch Block
                        if (error) {
                            console.log(error)
                        }
                });
            return true;
        };
        video.addEventListener('timeupdate', timeupdate);
        video.preload = 'metadata';
        video.src = url;
        // Load video in Safari / IE11
        video.muted = true;
        video.playsInline = true;
        video.play();
    };
    fileReader.readAsArrayBuffer(sourceImage);
}

// Ajaxでイメージをアップロードする
CHAT.uploadImage = function(formData) {
    formData.append('roomId', CHAT.globalLoginParameter.roomId);
    jQuery.ajax({
        async: true,
        url:    CMS_SERVER_URL+"/file/upload",
        type: "post",
        data: formData,
        contentType: false,
        processData: false
    }).done(function(res) {
        // 8
        var imgPath = CMS_SERVER_URL + '/file/getImage?fileName=' + res.fileName + '&roomId=' + CHAT.globalLoginParameter.roomId;
        var imageName = res.fileName

        // uploadFileの判断
        var extension = imageName.substr(imageName.lastIndexOf('.') + 1).toLowerCase();

        // 画像の処理
        if (res.fileType == "jpeg" || res.fileType == "jpg" || res.fileType == "png") {
            if (res.thumbnailPath && res.thumbnailPath.length > 0) {
                imgPath = CMS_SERVER_URL + '/file/getImage?fileName=' + res.thumbImageFileName + '&roomId=' + CHAT.globalLoginParameter.roomId;
                imageName = res.thumbImageFileName;
            }

            let downloadPath = CMS_SERVER_URL + '/file/download?fileName=' + imageName + '&roomId=' + CHAT.globalLoginParameter.roomId;
            // アップロードが終了した後ローディング画面から離れてメッセージをメッセージを転送する
            const lightbox = $('<a/>',{href:imgPath, 'data-lightbox':'attachedImages','data-title':imageName});
            const image = $('<img/>',{src:imgPath, width:'auto',style:'max-width:100%'});
            const downloadIcon = $('<a/>',{href:downloadPath, class:'fa fa-download', download:res.fileName});

            lightbox.append(image);
            lightbox.append(downloadIcon);
            let text = lightbox.prop('outerHTML')
            let encodedText
            try {
                encodedText = encodeURIComponent(text)
            } catch(e) {
                encodedText = text;
            }

            socket.emit('createMessage', {
                text: encodedText
            }, 1);

        } else {    // 動画の処理
            if (res.thumbnailPath && res.thumbnailPath.length > 0) {
                imgPath = CMS_SERVER_URL + '/file/getImage?fileName=' + res.thumbImageFileName + '&roomId=' + CHAT.globalLoginParameter.roomId;
            }

            let downloadPath = CMS_SERVER_URL + '/file/download?fileName=' + imageName + '&roomId=' + CHAT.globalLoginParameter.roomId;
            const aTag = $('<a/>', {id:"attachedImages"})
            const image = $('<img/>',{src:imgPath, width:'auto',style:'max-width:100%'});
            const downloadIcon = $('<a/>',{href:downloadPath, class:'fa fa-download', download:res.fileName});

            aTag.append(image);
            aTag.append(downloadIcon);

            let text = aTag.prop('outerHTML');
            let encodedText
            try {
                encodedText = encodeURIComponent(text)
            } catch(e) {
                encodedText = text;
            }

            socket.emit('createMessage', {
                text: encodedText
            }, 1);
        }

        $('.overlay').removeClass('active undismissable');
        $('.loader').removeClass('active');
        CHAT_UI.dismissLoadingIndicator();
    })
}

// Thumbnailのファイルを生成する。
CHAT.createThumbnailAndUpload = function(sourceImage, callback) {
    const fileReader = new FileReader();
    const img = new Image();
    fileReader.onloadend = function() {
            img.src = fileReader.result
    }

    img.onload = function() {
        const elem = document.createElement('canvas');
        var rate
        var width = img.width
        var height = img.height
        if ((img.width <= 500) && (img.height <= 500))
        {
            callback(undefined, false)
            return
        }

        if (img.width > img.height)
        {
            rate = 500/img.width
        } else {
            rate = 500/img.height
        }
        elem.width = width * rate;
        elem.height = height * rate;

        const ctx = elem.getContext('2d')

        ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, elem.width, elem.height);
        // ctx.drawImage(img, 0, 0, width, height);

        fetch(elem.toDataURL("image/jpeg"))
        .then(function(res) {
            return res.arrayBuffer();
        })
        .then(function(buf) {
            const newFile = new File([buf], sourceImage.name, {type:"image/jpeg"});

            callback(newFile, true)

        }).catch((error) => { // fetch Error catch Block
                if (error) {
                    console.log(error)
                }
        });
    }

    fileReader.readAsDataURL(sourceImage);
}

// 該当チャットルームに参加するためログイン情報をサーバに渡す
getLoginParameter = function(sid, loginId, shopName, roomId = undefined, roomName = undefined, languageCode) {
    var loginParam = new Object()
    loginParam.sid = sid;
    loginParam.loginId = loginId;
    loginParam.shopName = shopName;
    loginParam.roomId = roomId;
    loginParam.roomName = roomName;

    CHAT.globalLoginParameter = loginParam;

    if (!languageCode) {
        languageCode = "en"
    }
    CHAT_UI.htmlElementTextInitialize(languageCode)

    if (IS_ONLINE == 'true') {
        socket.emit('join', loginParam, 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 {
                console.log('No error');
                if (loginParam.roomName != undefined && loginParam.roomName != "null") {
                    $('.titleRoomName').text(loginParam.roomName).data('roomName', loginParam.roomName);
                } else {
                    // 設定されていたroomNameがない場合
                    let roomListTitle = getLocalizedString("roomListTitle")
                    $('.titleRoomName').text(roomListTitle).data('roomName', roomListTitle);
                }
            }
            // loadingIndicatorを表示しない
            CHAT_UI.dismissLoadingIndicator();
        });
    } else {
        // loadingIndicatorを表示しない
        CHAT_UI.dismissLoadingIndicator();
    }

}

CHAT.leaveRoom = function() {
    socket.emit('leaveRoom', function() {
    });
Lee Munkyeong committed
270 271 272 273 274
}

CHAT.requestMyinfo = function() {
    jQuery.ajax({
            async: true,
Lee Munkyeong committed
275
            url: CMS_SERVER_URL + "/chatapi/user?sid=" + CHAT.globalLoginParameter.sid + "&cmd=" + userAPICmd.MYINFO,
Lee Munkyeong committed
276 277 278
            type: "get",
            processData: false,
            contentType: false
279
    }).done(function(res) {
Lee Munkyeong committed
280 281 282
            console.log(res);
            return res;
    })
Kim Peace committed
283
}