menu_media.js 17.4 KB
1 2 3 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 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 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 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
const { ipcRenderer } = require("electron");
const log = require('electron-log')
const sqlite3 = require('sqlite3').verbose();
const offset = new Date().getTimezoneOffset() * 60000;
var exec = require('child_process').exec, child;
var mypiechart = null;

const videoanalysis = document.getElementById("temp_post");


document.addEventListener("DOMContentLoaded", function(){
    getMediaChart();
    getStorageStructure('photo');
    video_list();
  });

//Tap change
function openTap(tabName) {
    var i;
    var x = document.getElementsByClassName("menu");
    for (i = 0; i < x.length; i++) {
        x[i].style.display = "none"
    }
    document.getElementById(tabName).style.display = "block";
}

//Show video list for analysis
var video_list = function getVideolist(filetype){
    return new Promise(function(resolve, reject){
        setTimeout( function(){
            document.querySelector('#videotable > tbody').innerHTML = `<tr><th></th>
                                                                        <th>name</th>\
                                                                        <th>date_added</th>\
                                                                        <th>resolution</th>\
                                                                        <th>size</th>\
                                                                    </tr>`;
            const db = new sqlite3.Database('InnerDatabase.db');
            let sql = `select display_name as name, date_added, path, resolution, size
                        from video;`
            log.info("video_list Query start");
            db.all(sql, [], (err, rows) => {
                if (err) {
                  log.err(err);
                  reject(err);
                  throw err;
                }
                else{
                    log.info("video_list Query succesfully executed");
                    rows.forEach((row) => {
                        getByte(row.size).then(function(bytedata) {
                            document.querySelector('#videotable > tbody').innerHTML += `<tr><td><div class="form-check">
                            <input class="form-check-input position-static" type="checkbox" id="blankCheckbox" value="${row.path}">
                          </div></td>
                            <td>${row.name}</td><td>${new Date(row.date_added*1000-offset).toISOString().replace(/T/, ' ').replace(/\..+/, '')}</td><td>${row.resolution}</td><td>${bytedata}</td></tr>`
                        });
                    });
                    db.close();
                    resolve(true);
                }
              });             
        }, 1000)
    })
}

//Request video analysis when click button
videoanalysis.addEventListener("click", ()=>{
    Promise.all([check()]).then(function(value){
        ipcRenderer.send(
            "video-analysis",
            value[0]
          );
      });
});

//Find which video checked
var check = function checkboxcheck(){
    return new Promise(function(resolve, reject){
        setTimeout(function(){
            var checkedValue = []; 
            var inputElements = document.querySelectorAll('#blankCheckbox');
            for(var i=0; i < inputElements.length; i++){
                if(inputElements[i].checked){
                    checkedValue.push(inputElements[i].value);
                    log.info(inputElements[i].value);
                }
            }
            resolve(checkedValue);           
        }, 1000)
    })
}

//Get videodetail from main
ipcRenderer.on("getvideodetail", (e, arg) => {
    log.info(arg + " from main");
    Promise.all([popvideoanalysis(arg)]).then(function(value){
        log.info(value);
        value[0].forEach((pie) => {
            log.info("hello")
            var ctx = document.getElementById(pie[0]).getContext("2d");
            log.info("hello")
            new Chart(ctx, pie[1]);
            log.info(pie[0] +" dect pie chart create");
        })
      });
});

//Show video analysis result
var popvideoanalysis = function popVideoAnalysis(arg){
    return new Promise(function(resolve, reject){
        setTimeout( function(){
            log.info("start popVideoAnalysis");
            document.querySelector('#va_list').innerHTML = '';
            var mydectpiechart = [];
            var x = document.getElementsByClassName("menu");
            for (i = 0; i < x.length; i++) {
                x[i].style.display = "none"
            }
            document.getElementById('Analysis-Detail').style.display = "block";
            for(var k =0; k < arg[0].length; k++)
            {
                var lb_dict = arg[0][k];
                var dt_dict = arg[1][k];
        
                var html_taglist = ``;
                var i,j;
                for(i=0; i < lb_dict['labels'].length; i++){
                    var label_name = lb_dict['labels'][i];
                    html_taglist += `<div class="font-nanum pb-1 pt-1" style="font-size: 14px;"><a style="font-weight: bold;">${label_name}<a><br>`;
                    for(j=0; j<lb_dict[label_name].length; j++){
                        var label_detail = lb_dict[label_name][j];
                        html_taglist += `<p style="text-align: right;"><a class="pb-1s">${label_detail[0]}s ~ ${label_detail[1]} for ${label_detail[2].toFixed(2)} confidence</a><p>`;
                    }
                    html_taglist += '</div>'
                }
                var likelihood_index = {'UNKNOWN': 0,'VERY_UNLIKELY': 1,'UNLIKELY': 2,'POSSIBLE': 3,'LIKELY': 4,'VERY_LIKELY': 5};
                var det_dataset = [0,0,0,0,0,0]
                
                var html_detlist = ``;
                var i,j;
                for(i=0; i < dt_dict['likelihood'].length; i++){
                    html_detlist += `<div class="font-nanum pb-2 pt-2" style="font-size: 14px; text-align: right;"><a>~ ${dt_dict['likelihood'][i][0]}s , ${dt_dict['likelihood'][i][1]}</a><div>`;
                    det_dataset[likelihood_index[dt_dict['likelihood'][i][1]]] +=1;
                }
        
                log.info(det_dataset);
                var html = `<div class="bg-white rounded shadow-sm">
                <h6 class="border-bottom border-gray pl-2 pb-2 mb-0">${lb_dict['video']}</h6>
                <div class="row">
                    <div class="col">
                        <div class="my-3 p-3  bg-white rounded shadow-sm">
                            <h6 class="border-bottom border-gray pb-2 mb-0">Tag</h6>
                            <div id="taglist_${lb_dict['video']}" class="pt-2">
                            ${html_taglist}
                            </div>
                        </div>
                    </div>
                    <div class="col">
                        <div class="my-3 p-3  bg-white rounded shadow-sm">
                            <h6 class="border-bottom border-gray pb-2 mb-0">Content Detection</h6>
                            <div>
                                <canvas id="det_piechart_${lb_dict['video']}"></canvas>
                            </div>
                            <div id="detectionlist_${lb_dict['video']}" class="pt-2">
                                ${html_detlist}
                            </div>
                        </div>
                    </div>
                </div>
            </div>`;
                document.querySelector('#va_list').innerHTML += html;
                var config = {
                            type: 'pie',
                            data: {
                                labels: ["UNKNOWN","VERY_UNLIKELY", "UNLIKELY","POSSIBLE", "LIKELY","VERY_LIKELY"],
                                datasets: [{
                                data: det_dataset,
                                backgroundColor: ["#D3D3D3", "#C0C0C0", "#A9A9A9", "#FF3333","#FF0000","#CC0000"],
                                hoverBackgroundColor: ["#D3D3D3", "#C0C0C0", "#A9A9A9", "#FF3333","#FF0000","#CC0000"]
                                }]
                            },
                            options: {
                                responsive: true,
                            },
                        }
                mydectpiechart.push(['det_piechart_'+lb_dict['video'],config]);
                }
          resolve(mydectpiechart);
        }, 1000)
    })

}

//Draw piechart for Media type
function getMediaChart(){
    Promise.all([drawpiechart()]).then(function(value){
        log.info("getMediaChart finished")
      });
}

//Get Storage structure for specific media type
function getStorageStructure(filetype){
    document.querySelector('#mediafile_struct > div').innerHTML = '';
    document.querySelector('#filetable > tbody').innerHTML = '';
    document.getElementById('filelist_for_folder').style.display = "none";
    log.info("getStorageStructure start")
    Promise.all([file_struct(filetype)]).then(function(value){
        value[0].forEach((row) => {
            getByte(row.dirsize).then(function(bytedata) {
                document.querySelector('#mediafile_struct > div').innerHTML += `<div class="d-flex justify-content-between p-1"><a href="#" clase="folder_name" onclick="getFilelistinFolder('${row.dir}','${filetype}');" id="${row.dir}">${row.dir} </a><a></a>${bytedata}<br></div>`
            });
        });
      });
    var i;
    var x = document.getElementsByClassName("filetype");
    for (i = 0; i < x.length; i++) {
    x[i].style.fontWeight = "normal";
    }
    document.getElementById(filetype).style.fontWeight = "bold";
    switch(filetype){
        case 'photo':
            document.getElementById('struct_title').innerText = "Image";
            break;
        case 'video':
            document.getElementById('struct_title').innerText = "Video";
            break;
        case 'audio':
            document.getElementById('struct_title').innerText = "Audio";
            break;
        case 'documentinfo':
            document.getElementById('struct_title').innerText = "Document";
            break;
    }
}

//Get file list of specific filetype in folder
function getFilelistinFolder(foldername,filetype){
    log.info("getFilelistinFolder start")
    document.querySelector('#filetable > tbody').innerHTML = `<tr><th>name</th>\
                                                            <th>date_added</th>\
                                                            <th>size</th>\
                                                        </tr>`;

    Promise.all([fileinfolder(foldername, filetype)]).then(function(value){
        value[0].forEach((row) => {
            getByte(row.size).then(function(bytedata) {
                document.querySelector('#filetable > tbody').innerHTML += `<tr><td>${row.name}</td><td>${new Date(row.date_added*1000-offset).toISOString().replace(/T/, ' ').replace(/\..+/, '')}</td><td>${bytedata}</td></tr>`
            });
        });
      });
    document.getElementById('filelist_for_folder').style.display = "block";
}

//draw piechart for Media type
var drawpiechart = function drawPieChart(){
    return new Promise(function(resolve, reject){
        setTimeout( function(){
          var html = ''
          Promise.all([filetype_all_size('photo'),filetype_all_size('video'),filetype_all_size('audio'),filetype_all_size('documentinfo')]).then(function(value){
            var ctx = document.getElementById("pieChart").getContext('2d');
            var config = {
                        type: 'pie',
                        data: {
                            labels: ["Image", "Video", "Audio", "Documents"],
                            datasets: [{
                            data: [value[0], value[1], value[2], value[3]],
                            backgroundColor: ["#F7464A", "#46BFBD", "#FDB45C", "#949FB1"],
                            hoverBackgroundColor: ["#FF5A5E", "#5AD3D1", "#FFC870", "#A8B3C5"]
                            }]
                        },
                        options: {
                            responsive: true
                        }
                    }
            if (mypiechart == null) {
              mypiechart = new Chart(ctx, config);
              log.info("pie chart create")
            } else {
                mypiechart.config = config;
                mypiechart.update();
                log.info("pie chart update")
            }
            Promise.all([getByte(value[0]),getByte(value[1]),getByte(value[2]),getByte(value[3])]).then(function(b){
                var html = `<div class="d-flex justify-content-between pt-1 pb-1"><a style="font-weight: bold;">Image </a><a>${b[0]}</a></div>
                            <div class="d-flex justify-content-between pt-1 pb-1"><a style="font-weight: bold;">Video </a><a>${b[1]}</a></div>
                            <div class="d-flex justify-content-between pt-1 pb-1"><a style="font-weight: bold;">Audio </a><a>${b[2]}</a></div>
                            <div class="d-flex justify-content-between pt-1 pb-1"><a style="font-weight: bold;">Document </a><a>${b[3]}</a></div>`         
                document.querySelector('#pie_datalist').innerHTML = html;  
                });
            });
          resolve(true);
        }, 1000)
    })
}

//Change byte to kb, mb, gb
var getByte = function getB(byte){
    return new Promise(function(resolve, reject){
        setTimeout( function(){
            if(byte > 1073741824){
                resolve((byte/1073741824).toFixed(2) + "GB");
            }
            else if(byte > 1048576){
                resolve((byte/1048576).toFixed(2) + "MB");
            }
            else if(byte > 1024){
                resolve((byte/1024).toFixed(2) + "KB");
            }          
        }, 1000)
    })
}

//Get all file size of specific media type
var filetype_all_size = function getAllMediaTypeSize(filetype){
    return new Promise(function(resolve, reject){
        setTimeout( function(){
            const db = new sqlite3.Database('InnerDatabase.db');
            let sql = `select SUM(size) as totalsize from ${filetype};`
            log.info("filetype_all_size Query start");
            db.get(sql, [], (err, row) => {
                if (err) {
                  log.err(err);
                  reject(err);
                  throw err;
                }
                else{
                    log.info("filetype_all_size Query succesfully executed");
                    db.close();
                    resolve(row.totalsize);
                }
              });            
        }, 1000)
    })
}

//Get folder names that specific filetype located
var file_struct = function getStruct(filetype){
    return new Promise(function(resolve, reject){
        setTimeout( function(){
            const db = new sqlite3.Database('InnerDatabase.db');
            let sql = `select replace(SUBSTR(rtrim(path, replace(path, '/', '')),1,LENGTH(rtrim(path, replace(path, '/', '')))-1), rtrim(SUBSTR(rtrim(path, replace(path, '/', '')),1,LENGTH(rtrim(path, replace(path, '/', '')))-1), replace(SUBSTR(rtrim(path, replace(path, '/', '')),1,LENGTH(rtrim(path, replace(path, '/', '')))-1), '/', '')), '') as dir, sum(size) as dirsize
                        from ${filetype}
                        group by dir;`
            log.info("file_struct Query start");
            db.all(sql, [], (err, rows) => {
                if (err) {
                  log.err(err);
                  reject(err);
                  throw err;
                }
                else{
                    log.info("file_struct Query succesfully executed");
                    db.close();
                    resolve(rows);
                }
              });             
        }, 1000)
    })
}

//Get files of specific filetype in folder
var fileinfolder = function getFileinFolder(foldername,filetype){
    return new Promise(function(resolve, reject){
        setTimeout( function(){
            const db = new sqlite3.Database('InnerDatabase.db');
            let sql = '';
            switch(filetype){
                case 'photo':
                    sql += `select display_name as name, date_added, path, size from ${filetype}
                        where path LIKE '%${foldername}%';`
                    document.querySelector('#infilelist').innerText = `Images in ${foldername}`;
                    break;
                case 'video':
                    sql += `select display_name as name, date_added, path, size from ${filetype}
                        where path LIKE '%${foldername}%';`
                    document.querySelector('#infilelist').innerText = `Videos in ${foldername}`;
                    break;
                case 'audio':
                    sql += `select title as name, date_added, path, size from ${filetype}
                        where path LIKE '%${foldername}%';`
                    document.querySelector('#infilelist').innerText = `Audios in ${foldername}`;
                    break;
                case 'documentinfo':
                    sql += `select name, date_added, path, size from ${filetype}
                        where path LIKE '%${foldername}%';`
                    document.querySelector('#infilelist').innerText = `Documents in ${foldername}`;
                    break;
            }
            log.info("fileinfolder Query start");
            db.all(sql, [], (err, rows) => {
                if (err) {
                  log.err(err);
                  reject(err);
                  throw err;
                }
                else{
                    log.info("fileinfolder Query succesfully executed");
                    db.close();
                    resolve(rows);
                }
              });             
        }, 1000)
    })
}