From 9b21ea157946eea7e847b52ba8d047e85067ea49 Mon Sep 17 00:00:00 2001 From: BrockDW Date: Fri, 24 Mar 2023 10:02:39 -0700 Subject: [PATCH 1/2] local update --- src/index.html | 6 +++++- src/scripts/background.js | 37 ++++++++++++++++++++++++++++++++++++- src/scripts/webact.js | 10 +++++++++- 3 files changed, 50 insertions(+), 3 deletions(-) diff --git a/src/index.html b/src/index.html index fcfc431..90e1d94 100644 --- a/src/index.html +++ b/src/index.html @@ -32,6 +32,8 @@ All-time By days Settings + Send Data +

In Web Activity Time Tracker you can:

@@ -119,4 +121,6 @@ - \ No newline at end of file + + + diff --git a/src/scripts/background.js b/src/scripts/background.js index fcb61bc..a089c15 100644 --- a/src/scripts/background.js +++ b/src/scripts/background.js @@ -473,4 +473,39 @@ loadPermissions(); addListener(); loadAddDataFromStorage(); updateSummaryTime(); -updateStorage(); \ No newline at end of file +updateStorage(); + + +chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) { + console.log("chrome listener triggered in background.js") + if (request.action === "sendBrowserActivityData") { + console.log("triggering sendBrowserActivityData function"); + sendBrowserActivityData(); + } +}); + + +function sendBrowserActivityData() { + // const backendUrl = "https://your-backend-url.com/api/browser-activity"; + console.log(tabs) + + const browserActivityData = tabs.map(tab => { + return { + url: tab.url, + days: tab.days.map(day => { + return { + date: day.date, + summary: day.summary, + time: day.time + }; + }) + }; + }); + + console.log(browserActivityData); + + // axios.post(backendUrl, browserActivityData) + // .then(response => console.log("Data sent successfully:", response.data)) + // .catch(error => console.error("Error sending data:", error)); + } + \ No newline at end of file diff --git a/src/scripts/webact.js b/src/scripts/webact.js index 9082ed6..9f27087 100644 --- a/src/scripts/webact.js +++ b/src/scripts/webact.js @@ -122,6 +122,12 @@ document.addEventListener('DOMContentLoaded', function () { window.open(chrome.runtime.getURL('options.html')); } }); + + document.getElementById("btnSendData").addEventListener("click", function () { + console.log("button clicked here"); + chrome.runtime.sendMessage({ action: "sendBrowserActivityData" }); + }); + }); firstInitPage(); @@ -556,4 +562,6 @@ function fillValuesForBlockWithInActiveDay(prefix, dayValue, timeValue, flag) { document.getElementById(prefix).value = dayValue; document.getElementById(prefix + 'Time').value = timeValue; } -} \ No newline at end of file +} + + From bed7085b9d6d341a9e136436c9ec3c7c6d019c56 Mon Sep 17 00:00:00 2001 From: Brock Date: Tue, 18 Apr 2023 22:18:44 -0700 Subject: [PATCH 2/2] update --- src/index.html | 8 + src/manifest.json | 2 +- src/scripts/background.js | 861 ++++++++++++++++++++---------------- src/scripts/ui.js | 900 ++++++++++++++++++++++---------------- src/scripts/webact.js | 19 +- 5 files changed, 1032 insertions(+), 758 deletions(-) diff --git a/src/index.html b/src/index.html index 90e1d94..fe20f73 100644 --- a/src/index.html +++ b/src/index.html @@ -100,6 +100,14 @@
+ + + +
Common chart Time chart diff --git a/src/manifest.json b/src/manifest.json index 585195d..623f46c 100644 --- a/src/manifest.json +++ b/src/manifest.json @@ -3,7 +3,7 @@ "name": "Web Activity Time Tracker", "short_name": "Web Time Tracker", - "version": "1.7.2", + "version": "1.7.2.8", "minimum_chrome_version": "26", "description": "Track and limit time your activity in the browser every day.", diff --git a/src/scripts/background.js b/src/scripts/background.js index a089c15..8ac4131 100644 --- a/src/scripts/background.js +++ b/src/scripts/background.js @@ -1,4 +1,4 @@ -'use strict'; +"use strict"; var tabs; var timeIntervalList; @@ -23,489 +23,614 @@ var isHasPermissioForNetflix; var isHasPermissioForNotification; function updateSummaryTime() { - setInterval(backgroundCheck, SETTINGS_INTERVAL_CHECK_DEFAULT); + setInterval(backgroundCheck, SETTINGS_INTERVAL_CHECK_DEFAULT); } function updateStorage() { - setInterval(backgroundUpdateStorage, SETTINGS_INTERVAL_SAVE_STORAGE_DEFAULT); + setInterval(backgroundUpdateStorage, SETTINGS_INTERVAL_SAVE_STORAGE_DEFAULT); } function backgroundCheck() { - chrome.windows.getLastFocused({ populate: true }, function(currentWindow) { - if (currentWindow.focused) { - var activeTab = currentWindow.tabs.find(t => t.active === true); - if (activeTab !== undefined && activity.isValidPage(activeTab)) { - var activeUrl = extractHostname(activeTab.url); - var tab = activity.getTab(activeUrl); - if (tab === undefined) { - activity.addTab(activeTab); - } - - if (activity.isInBlackList(activeUrl)) { - chrome.browserAction.setBadgeBackgroundColor({ color: '#fdb8b8' }) - chrome.browserAction.setBadgeText({ - tabId: activeTab.id, - text: 'n/a' - }); - } else { - if (tab !== undefined) { - if (currentTab !== tab.url) { - activity.setCurrentActiveTab(tab.url); - } - chrome.idle.queryState(parseInt(setting_interval_inactivity), function(state) { - if (state === 'active') { - mainTRacker(activeUrl, tab, activeTab); - } else checkDOM(state, activeUrl, tab, activeTab); - }); - } - } + chrome.windows.getLastFocused({ populate: true }, function (currentWindow) { + if (currentWindow.focused) { + var activeTab = currentWindow.tabs.find((t) => t.active === true); + if (activeTab !== undefined && activity.isValidPage(activeTab)) { + var activeUrl = extractHostname(activeTab.url); + var tab = activity.getTab(activeUrl); + if (tab === undefined) { + activity.addTab(activeTab); + } + + if (activity.isInBlackList(activeUrl)) { + chrome.browserAction.setBadgeBackgroundColor({ color: "#fdb8b8" }); + chrome.browserAction.setBadgeText({ + tabId: activeTab.id, + text: "n/a", + }); + } else { + if (tab !== undefined) { + if (currentTab !== tab.url) { + activity.setCurrentActiveTab(tab.url); } - } else activity.closeIntervalForCurrentTab(); - }); + chrome.idle.queryState( + parseInt(setting_interval_inactivity), + function (state) { + if (state === "active") { + mainTRacker(activeUrl, tab, activeTab); + } else checkDOM(state, activeUrl, tab, activeTab); + } + ); + } + } + } + } else activity.closeIntervalForCurrentTab(); + }); } function mainTRacker(activeUrl, tab, activeTab) { - if (activity.isLimitExceeded(activeUrl, tab) && !activity.wasDeferred(activeUrl)) { - setBlockPageToCurrent(activeTab.url, tab.days.at(-1).summary, tab.days.at(-1).counter); - } - if (!activity.isInBlackList(activeUrl)) { - if (activity.isNeedNotifyView(activeUrl, tab)) { - if (isHasPermissioForNotification) { - showNotification(activeUrl, tab); - } else { - checkPermissionsForNotifications(showNotification, activeUrl, tab); - } - } - tab.incSummaryTime(); - } - if (setting_view_in_badge === true) { - chrome.browserAction.setBadgeBackgroundColor({ color: '#e7e7e7' }) - var summary = tab.days.find(s => s.date === todayLocalDate()).summary; - chrome.browserAction.setBadgeText({ - tabId: activeTab.id, - text: String(convertSummaryTimeToBadgeString(summary)) - }); - } else { - chrome.browserAction.setBadgeBackgroundColor({ color: [0, 0, 0, 0] }) - chrome.browserAction.setBadgeText({ - tabId: activeTab.id, - text: '' - }); + if ( + activity.isLimitExceeded(activeUrl, tab) && + !activity.wasDeferred(activeUrl) + ) { + setBlockPageToCurrent( + activeTab.url, + tab.days.at(-1).summary, + tab.days.at(-1).counter + ); + } + if (!activity.isInBlackList(activeUrl)) { + if (activity.isNeedNotifyView(activeUrl, tab)) { + if (isHasPermissioForNotification) { + showNotification(activeUrl, tab); + } else { + checkPermissionsForNotifications(showNotification, activeUrl, tab); + } } + tab.incSummaryTime(); + } + if (setting_view_in_badge === true) { + chrome.browserAction.setBadgeBackgroundColor({ color: "#e7e7e7" }); + var summary = tab.days.find((s) => s.date === todayLocalDate()).summary; + chrome.browserAction.setBadgeText({ + tabId: activeTab.id, + text: String(convertSummaryTimeToBadgeString(summary)), + }); + } else { + chrome.browserAction.setBadgeBackgroundColor({ color: [0, 0, 0, 0] }); + chrome.browserAction.setBadgeText({ + tabId: activeTab.id, + text: "", + }); + } } function showNotification(activeUrl, tab) { - chrome.notifications.clear('watt-site-notification', function(wasCleared) { - if (!wasCleared) { - console.log('!wasCleared'); - - chrome.notifications.create( - 'watt-site-notification', { - type: 'basic', - iconUrl: 'icons/128x128.png', - title: "Web Activity Time Tracker", - contextMessage: activeUrl + ' ' + convertShortSummaryTimeToString(tab.getTodayTime()), - message: setting_notification_message - }, - function(notificationId) { - console.log(notificationId); - chrome.notifications.clear('watt-site-notification', function(wasCleared) { - if (wasCleared) - notificationAction(activeUrl, tab); - }); - }); - } else { - notificationAction(activeUrl, tab); + chrome.notifications.clear("watt-site-notification", function (wasCleared) { + if (!wasCleared) { + console.log("!wasCleared"); + + chrome.notifications.create( + "watt-site-notification", + { + type: "basic", + iconUrl: "icons/128x128.png", + title: "Web Activity Time Tracker", + contextMessage: + activeUrl + + " " + + convertShortSummaryTimeToString(tab.getTodayTime()), + message: setting_notification_message, + }, + function (notificationId) { + console.log(notificationId); + chrome.notifications.clear( + "watt-site-notification", + function (wasCleared) { + if (wasCleared) notificationAction(activeUrl, tab); + } + ); } - }); + ); + } else { + notificationAction(activeUrl, tab); + } + }); } function notificationAction(activeUrl, tab) { - chrome.notifications.create( - 'watt-site-notification', { - type: 'basic', - iconUrl: 'icons/128x128.png', - title: "Web Activity Time Tracker", - contextMessage: activeUrl + ' ' + convertShortSummaryTimeToString(tab.getTodayTime()), - message: setting_notification_message - }); + chrome.notifications.create("watt-site-notification", { + type: "basic", + iconUrl: "icons/128x128.png", + title: "Web Activity Time Tracker", + contextMessage: + activeUrl + " " + convertShortSummaryTimeToString(tab.getTodayTime()), + message: setting_notification_message, + }); } function setBlockPageToCurrent(currentUrl, summaryTime, counter) { - var blockUrl = chrome.runtime.getURL("block.html") + '?url=' + currentUrl - + '&summaryTime=' + summaryTime - + '&counter=' + counter; - chrome.tabs.query({ currentWindow: true, active: true }, function(tab) { - chrome.tabs.update(tab.id, { url: blockUrl }); - }); + var blockUrl = + chrome.runtime.getURL("block.html") + + "?url=" + + currentUrl + + "&summaryTime=" + + summaryTime + + "&counter=" + + counter; + chrome.tabs.query({ currentWindow: true, active: true }, function (tab) { + chrome.tabs.update(tab.id, { url: blockUrl }); + }); } function isVideoPlayedOnPage() { - var videoElement = document.getElementsByTagName('video')[0]; - if (videoElement !== undefined && videoElement.currentTime > 0 && !videoElement.paused && !videoElement.ended && videoElement.readyState > 2) { - return true; - } else return false; + var videoElement = document.getElementsByTagName("video")[0]; + if ( + videoElement !== undefined && + videoElement.currentTime > 0 && + !videoElement.paused && + !videoElement.ended && + videoElement.readyState > 2 + ) { + return true; + } else return false; } function checkDOM(state, activeUrl, tab, activeTab) { - if (state === 'idle' && isDomainEquals(activeUrl, "youtube.com")) { - trackForYT(mainTRacker, activeUrl, tab, activeTab); - } else if (state === 'idle' && isDomainEquals(activeUrl, "netflix.com")) { - trackForNetflix(mainTRacker, activeUrl, tab, activeTab); - } else activity.closeIntervalForCurrentTab(); + if (state === "idle" && isDomainEquals(activeUrl, "youtube.com")) { + trackForYT(mainTRacker, activeUrl, tab, activeTab); + } else if (state === "idle" && isDomainEquals(activeUrl, "netflix.com")) { + trackForNetflix(mainTRacker, activeUrl, tab, activeTab); + } else activity.closeIntervalForCurrentTab(); } function trackForYT(callback, activeUrl, tab, activeTab) { - if (isHasPermissioForYouTube) { - executeScriptYoutube(callback, activeUrl, tab, activeTab); - } else { - checkPermissionsForYT(executeScriptYoutube, activity.closeIntervalForCurrentTab, callback, activeUrl, tab, activeTab); - } + if (isHasPermissioForYouTube) { + executeScriptYoutube(callback, activeUrl, tab, activeTab); + } else { + checkPermissionsForYT( + executeScriptYoutube, + activity.closeIntervalForCurrentTab, + callback, + activeUrl, + tab, + activeTab + ); + } } function trackForNetflix(callback, activeUrl, tab, activeTab) { - if (isHasPermissioForNetflix) { - executeScriptNetflix(callback, activeUrl, tab, activeTab); - } else { - checkPermissionsForNetflix(executeScriptNetflix, activity.closeIntervalForCurrentTab, callback, activeUrl, tab, activeTab); - } + if (isHasPermissioForNetflix) { + executeScriptNetflix(callback, activeUrl, tab, activeTab); + } else { + checkPermissionsForNetflix( + executeScriptNetflix, + activity.closeIntervalForCurrentTab, + callback, + activeUrl, + tab, + activeTab + ); + } } function executeScriptYoutube(callback, activeUrl, tab, activeTab) { - chrome.tabs.executeScript({ code: "var videoElement = document.getElementsByTagName('video')[0]; (videoElement !== undefined && videoElement.currentTime > 0 && !videoElement.paused && !videoElement.ended && videoElement.readyState > 2);" }, (results) => { - if (results !== undefined && results[0] !== undefined && results[0] === true) - callback(activeUrl, tab, activeTab); - else activity.closeIntervalForCurrentTab(); - }); + chrome.tabs.executeScript( + { + code: "var videoElement = document.getElementsByTagName('video')[0]; (videoElement !== undefined && videoElement.currentTime > 0 && !videoElement.paused && !videoElement.ended && videoElement.readyState > 2);", + }, + (results) => { + if ( + results !== undefined && + results[0] !== undefined && + results[0] === true + ) + callback(activeUrl, tab, activeTab); + else activity.closeIntervalForCurrentTab(); + } + ); } function executeScriptNetflix(callback, activeUrl, tab, activeTab) { - chrome.tabs.executeScript({ code: "var videoElement = document.getElementsByTagName('video')[0]; (videoElement !== undefined && videoElement.currentTime > 0 && !videoElement.paused && !videoElement.ended && videoElement.readyState > 2);" }, (results) => { - if (results !== undefined && results[0] !== undefined && results[0] === true) { - callback(activeUrl, tab, activeTab); - } else { - activity.closeIntervalForCurrentTab(); - } - }); + chrome.tabs.executeScript( + { + code: "var videoElement = document.getElementsByTagName('video')[0]; (videoElement !== undefined && videoElement.currentTime > 0 && !videoElement.paused && !videoElement.ended && videoElement.readyState > 2);", + }, + (results) => { + if ( + results !== undefined && + results[0] !== undefined && + results[0] === true + ) { + callback(activeUrl, tab, activeTab); + } else { + activity.closeIntervalForCurrentTab(); + } + } + ); } function backgroundUpdateStorage() { - if (tabs != undefined && tabs.length > 0) - storage.saveTabs(tabs); - if (timeIntervalList != undefined && timeIntervalList.length > 0) - storage.saveValue(STORAGE_TIMEINTERVAL_LIST, timeIntervalList); + if (tabs != undefined && tabs.length > 0) storage.saveTabs(tabs); + if (timeIntervalList != undefined && timeIntervalList.length > 0) + storage.saveValue(STORAGE_TIMEINTERVAL_LIST, timeIntervalList); } function setDefaultSettings() { - storage.saveValue(SETTINGS_INTERVAL_INACTIVITY, SETTINGS_INTERVAL_INACTIVITY_DEFAULT); - storage.saveValue(SETTINGS_INTERVAL_RANGE, SETTINGS_INTERVAL_RANGE_DEFAULT); - storage.saveValue(SETTINGS_VIEW_TIME_IN_BADGE, SETTINGS_VIEW_TIME_IN_BADGE_DEFAULT); - storage.saveValue(SETTINGS_BLOCK_DEFERRAL, SETTINGS_BLOCK_DEFERRAL_DEFAULT); - storage.saveValue(SETTINGS_DARK_MODE, SETTINGS_DARK_MODE_DEFAULT); - storage.saveValue(SETTINGS_INTERVAL_SAVE_STORAGE, SETTINGS_INTERVAL_SAVE_STORAGE_DEFAULT); - storage.saveValue(STORAGE_NOTIFICATION_MESSAGE, STORAGE_NOTIFICATION_MESSAGE_DEFAULT); + storage.saveValue( + SETTINGS_INTERVAL_INACTIVITY, + SETTINGS_INTERVAL_INACTIVITY_DEFAULT + ); + storage.saveValue(SETTINGS_INTERVAL_RANGE, SETTINGS_INTERVAL_RANGE_DEFAULT); + storage.saveValue( + SETTINGS_VIEW_TIME_IN_BADGE, + SETTINGS_VIEW_TIME_IN_BADGE_DEFAULT + ); + storage.saveValue(SETTINGS_BLOCK_DEFERRAL, SETTINGS_BLOCK_DEFERRAL_DEFAULT); + storage.saveValue(SETTINGS_DARK_MODE, SETTINGS_DARK_MODE_DEFAULT); + storage.saveValue( + SETTINGS_INTERVAL_SAVE_STORAGE, + SETTINGS_INTERVAL_SAVE_STORAGE_DEFAULT + ); + storage.saveValue( + STORAGE_NOTIFICATION_MESSAGE, + STORAGE_NOTIFICATION_MESSAGE_DEFAULT + ); } function checkSettingsImEmpty() { - chrome.storage.local.getBytesInUse(['inactivity_interval'], function(item) { - if (item == 0) { - setDefaultSettings(); - } - }); + chrome.storage.local.getBytesInUse(["inactivity_interval"], function (item) { + if (item == 0) { + setDefaultSettings(); + } + }); } function setDefaultValueForNewSettings() { - loadNotificationMessage(); + loadNotificationMessage(); } function addListener() { - chrome.tabs.onActivated.addListener(function(info) { - chrome.tabs.get(info.tabId, function(tab) { - activity.addTab(tab); - }); + chrome.tabs.onActivated.addListener(function (info) { + chrome.tabs.get(info.tabId, function (tab) { + activity.addTab(tab); }); + }); - chrome.webNavigation.onCompleted.addListener(function(details) { - chrome.tabs.get(details.tabId, function(tab) { - activity.updateFavicon(tab); - }); - }); - chrome.runtime.onInstalled.addListener(function(details) { - if (details.reason == 'install') { - storage.saveValue(SETTINGS_SHOW_HINT, SETTINGS_SHOW_HINT_DEFAULT); - setDefaultSettings(); - } - if (details.reason == 'update') { - storage.saveValue(SETTINGS_SHOW_HINT, SETTINGS_SHOW_HINT_DEFAULT); - checkSettingsImEmpty(); - setDefaultValueForNewSettings(); - isNeedDeleteTimeIntervalFromTabs = true; - } - }); - chrome.storage.onChanged.addListener(function(changes, namespace) { - for (var key in changes) { - if (key === STORAGE_BLACK_LIST) { - loadBlackList(); - } - if (key === STORAGE_RESTRICTION_LIST) { - loadRestrictionList(); - } - if (key === STORAGE_NOTIFICATION_LIST) { - loadNotificationList(); - } - if (key === STORAGE_NOTIFICATION_MESSAGE) { - loadNotificationMessage(); - } - if (key === SETTINGS_INTERVAL_INACTIVITY) { - storage.getValue(SETTINGS_INTERVAL_INACTIVITY, function(item) { setting_interval_inactivity = item; }); - } - if (key === SETTINGS_VIEW_TIME_IN_BADGE) { - storage.getValue(SETTINGS_VIEW_TIME_IN_BADGE, function(item) { setting_view_in_badge = item; }); - } - if (key === SETTINGS_BLOCK_DEFERRAL) { - storage.getValue(SETTINGS_BLOCK_DEFERRAL, function(item) { setting_block_deferral = item; }); - } - if (key === SETTINGS_DARK_MODE) { - storage.getValue(SETTINGS_DARK_MODE, function(item) { setting_dark_mode = item; }); - } - } + chrome.webNavigation.onCompleted.addListener(function (details) { + chrome.tabs.get(details.tabId, function (tab) { + activity.updateFavicon(tab); }); + }); + chrome.runtime.onInstalled.addListener(function (details) { + if (details.reason == "install") { + storage.saveValue(SETTINGS_SHOW_HINT, SETTINGS_SHOW_HINT_DEFAULT); + setDefaultSettings(); + } + if (details.reason == "update") { + storage.saveValue(SETTINGS_SHOW_HINT, SETTINGS_SHOW_HINT_DEFAULT); + checkSettingsImEmpty(); + setDefaultValueForNewSettings(); + isNeedDeleteTimeIntervalFromTabs = true; + } + }); + chrome.storage.onChanged.addListener(function (changes, namespace) { + for (var key in changes) { + if (key === STORAGE_BLACK_LIST) { + loadBlackList(); + } + if (key === STORAGE_RESTRICTION_LIST) { + loadRestrictionList(); + } + if (key === STORAGE_NOTIFICATION_LIST) { + loadNotificationList(); + } + if (key === STORAGE_NOTIFICATION_MESSAGE) { + loadNotificationMessage(); + } + if (key === SETTINGS_INTERVAL_INACTIVITY) { + storage.getValue(SETTINGS_INTERVAL_INACTIVITY, function (item) { + setting_interval_inactivity = item; + }); + } + if (key === SETTINGS_VIEW_TIME_IN_BADGE) { + storage.getValue(SETTINGS_VIEW_TIME_IN_BADGE, function (item) { + setting_view_in_badge = item; + }); + } + if (key === SETTINGS_BLOCK_DEFERRAL) { + storage.getValue(SETTINGS_BLOCK_DEFERRAL, function (item) { + setting_block_deferral = item; + }); + } + if (key === SETTINGS_DARK_MODE) { + storage.getValue(SETTINGS_DARK_MODE, function (item) { + setting_dark_mode = item; + }); + } + } + }); - chrome.runtime.setUninstallURL("https://docs.google.com/forms/d/e/1FAIpQLSdImHtvey6sg5mzsQwWfAQscgZOOV52blSf9HkywSXJhuQQHg/viewform"); + chrome.runtime.setUninstallURL( + "https://docs.google.com/forms/d/e/1FAIpQLSdImHtvey6sg5mzsQwWfAQscgZOOV52blSf9HkywSXJhuQQHg/viewform" + ); } function loadTabs() { - storage.loadTabs(STORAGE_TABS, function(items) { - tabs = []; - if (items != undefined) { - for (var i = 0; i < items.length; i++) { - tabs.push(new Tab(items[i].url, items[i].favicon, items[i].days, items[i].summaryTime, items[i].counter)); - } - if (isNeedDeleteTimeIntervalFromTabs) - deleteTimeIntervalFromTabs(); - } - }); + storage.loadTabs(STORAGE_TABS, function (items) { + tabs = []; + if (items != undefined) { + for (var i = 0; i < items.length; i++) { + tabs.push( + new Tab( + items[i].url, + items[i].favicon, + items[i].days, + items[i].summaryTime, + items[i].counter + ) + ); + } + if (isNeedDeleteTimeIntervalFromTabs) deleteTimeIntervalFromTabs(); + } + }); } function deleteTimeIntervalFromTabs() { - tabs.forEach(function(item) { - item.days.forEach(function(day) { - if (day.time != undefined) - day.time = []; - }) - }) + tabs.forEach(function (item) { + item.days.forEach(function (day) { + if (day.time != undefined) day.time = []; + }); + }); } function deleteYesterdayTimeInterval() { - timeIntervalList = timeIntervalList.filter(x => x.day == todayLocalDate()); + timeIntervalList = timeIntervalList.filter((x) => x.day == todayLocalDate()); } function loadBlackList() { - storage.getValue(STORAGE_BLACK_LIST, function(items) { - setting_black_list = items; - }) + storage.getValue(STORAGE_BLACK_LIST, function (items) { + setting_black_list = items; + }); } function loadTimeIntervals() { - storage.getValue(STORAGE_TIMEINTERVAL_LIST, function(items) { - timeIntervalList = []; - if (items != undefined) { - for (var i = 0; i < items.length; i++) { - timeIntervalList.push(new TimeInterval(items[i].day, items[i].domain, items[i].intervals)); - } - deleteYesterdayTimeInterval(); - } - }); + storage.getValue(STORAGE_TIMEINTERVAL_LIST, function (items) { + timeIntervalList = []; + if (items != undefined) { + for (var i = 0; i < items.length; i++) { + timeIntervalList.push( + new TimeInterval(items[i].day, items[i].domain, items[i].intervals) + ); + } + deleteYesterdayTimeInterval(); + } + }); } function loadRestrictionList() { - storage.getValue(STORAGE_RESTRICTION_LIST, function(items) { - setting_restriction_list = items; - }) + storage.getValue(STORAGE_RESTRICTION_LIST, function (items) { + setting_restriction_list = items; + }); } function loadNotificationList() { - storage.getValue(STORAGE_NOTIFICATION_LIST, function(items) { - setting_notification_list = items; - }); + storage.getValue(STORAGE_NOTIFICATION_LIST, function (items) { + setting_notification_list = items; + }); } function loadNotificationMessage() { - storage.getValue(STORAGE_NOTIFICATION_MESSAGE, function(item) { - setting_notification_message = item; - if (isEmpty(setting_notification_message)) { - storage.saveValue(STORAGE_NOTIFICATION_MESSAGE, STORAGE_NOTIFICATION_MESSAGE_DEFAULT); - setting_notification_message = STORAGE_NOTIFICATION_MESSAGE_DEFAULT; - } - }); + storage.getValue(STORAGE_NOTIFICATION_MESSAGE, function (item) { + setting_notification_message = item; + if (isEmpty(setting_notification_message)) { + storage.saveValue( + STORAGE_NOTIFICATION_MESSAGE, + STORAGE_NOTIFICATION_MESSAGE_DEFAULT + ); + setting_notification_message = STORAGE_NOTIFICATION_MESSAGE_DEFAULT; + } + }); } function loadSettings() { - storage.getValue(SETTINGS_INTERVAL_INACTIVITY, function(item) { setting_interval_inactivity = item; }); - storage.getValue(SETTINGS_VIEW_TIME_IN_BADGE, function(item) { setting_view_in_badge = item; }); - storage.getValue(SETTINGS_BLOCK_DEFERRAL, function(item) { setting_block_deferral = item; }); - storage.getValue(SETTINGS_DARK_MODE, function(item) { setting_dark_mode = item; }); + storage.getValue(SETTINGS_INTERVAL_INACTIVITY, function (item) { + setting_interval_inactivity = item; + }); + storage.getValue(SETTINGS_VIEW_TIME_IN_BADGE, function (item) { + setting_view_in_badge = item; + }); + storage.getValue(SETTINGS_BLOCK_DEFERRAL, function (item) { + setting_block_deferral = item; + }); + storage.getValue(SETTINGS_DARK_MODE, function (item) { + setting_dark_mode = item; + }); } function loadAddDataFromStorage() { - loadTabs(); - loadTimeIntervals(); - loadBlackList(); - loadRestrictionList(); - loadNotificationList(); - loadNotificationMessage(); - loadSettings(); + loadTabs(); + loadTimeIntervals(); + loadBlackList(); + loadRestrictionList(); + loadNotificationList(); + loadNotificationMessage(); + loadSettings(); } function loadPermissions() { - checkPermissionsForYT(); - checkPermissionsForNetflix(); - checkPermissionsForNotifications(); + checkPermissionsForYT(); + checkPermissionsForNetflix(); + checkPermissionsForNotifications(); } function checkPermissionsForYT(callbackIfTrue, callbackIfFalse, ...props) { - chrome.permissions.contains({ - permissions: ['tabs'], - origins: ["https://www.youtube.com/*"] - }, function(result) { - if (callbackIfTrue != undefined && result) - callbackIfTrue(...props); - if (callbackIfFalse != undefined && !result) - callbackIfFalse(); - isHasPermissioForYouTube = result; - }); + chrome.permissions.contains( + { + permissions: ["tabs"], + origins: ["https://www.youtube.com/*"], + }, + function (result) { + if (callbackIfTrue != undefined && result) callbackIfTrue(...props); + if (callbackIfFalse != undefined && !result) callbackIfFalse(); + isHasPermissioForYouTube = result; + } + ); } function checkPermissionsForNetflix(callbackIfTrue, callbackIfFalse, ...props) { - chrome.permissions.contains({ - permissions: ['tabs'], - origins: ["https://www.netflix.com/*"] - }, function(result) { - if (callbackIfTrue != undefined && result) - callbackIfTrue(...props); - if (callbackIfFalse != undefined && !result) - callbackIfFalse(); - isHasPermissioForNetflix = result; - }); + chrome.permissions.contains( + { + permissions: ["tabs"], + origins: ["https://www.netflix.com/*"], + }, + function (result) { + if (callbackIfTrue != undefined && result) callbackIfTrue(...props); + if (callbackIfFalse != undefined && !result) callbackIfFalse(); + isHasPermissioForNetflix = result; + } + ); } function checkPermissionsForNotifications(callback, ...props) { - chrome.permissions.contains({ - permissions: ["notifications"] - }, function(result) { - if (callback != undefined && result) - callback(...props); - isHasPermissioForNotification = result; - }); + chrome.permissions.contains( + { + permissions: ["notifications"], + }, + function (result) { + if (callback != undefined && result) callback(...props); + isHasPermissioForNotification = result; + } + ); } function createFile(data, type, fileName) { - var file = new Blob([data], { type: type }); - var downloadLink; - downloadLink = document.createElement("a"); - downloadLink.download = fileName; - downloadLink.href = window.URL.createObjectURL(file); - downloadLink.style.display = "none"; - document.body.appendChild(downloadLink); - downloadLink.click(); - } - - function toCsv(tabsData) { - var str = "domain,date,time(sec)\r\n"; - for (var i = 0; i < tabsData.length; i++) { - for (var y = 0; y < tabsData[i].days.length; y++) { - var line = - tabsData[i].url + - "," + - new Date(tabsData[i].days[y].date).toLocaleDateString() + - "," + - tabsData[i].days[y].summary; - str += line + "\r\n"; - } + var file = new Blob([data], { type: type }); + var downloadLink; + downloadLink = document.createElement("a"); + downloadLink.download = fileName; + downloadLink.href = window.URL.createObjectURL(file); + downloadLink.style.display = "none"; + document.body.appendChild(downloadLink); + downloadLink.click(); +} + +function toCsv(tabsData) { + var str = "domain,date,time(sec)\r\n"; + for (var i = 0; i < tabsData.length; i++) { + for (var y = 0; y < tabsData[i].days.length; y++) { + var line = + tabsData[i].url + + "," + + new Date(tabsData[i].days[y].date).toLocaleDateString() + + "," + + tabsData[i].days[y].summary; + str += line + "\r\n"; } - - createFile(str, "text/csv", "domains.csv"); - } - - function exportToCSV() { - storage.getValue(STORAGE_TABS, function (item) { - toCsv(item); - }); } - - storage.getValue("SETTINGS_PERIODIC_HOUR_DOWNLOAD", function (hour) { - storage.getValue("SETTINGS_PERIODIC_MINUTE_DOWNLOAD", function (minute) { - if (typeof hour !== "number" || typeof minute !== "number") { - return; - } else { - autoDownloadCsv(hour, minute); - } - }); + + createFile(str, "text/csv", "domains.csv"); +} + +function exportToCSV() { + storage.getValue(STORAGE_TABS, function (item) { + toCsv(item); }); - - function autoDownloadCsv(hour, minute) { - var now = new Date(); - var triggerTime = new Date( - now.getFullYear(), - now.getMonth(), - now.getDate(), - hour, - minute, - 0, - 0 - ); - - if (triggerTime < now) { - triggerTime.setDate(triggerTime.getDate() + 1); +} + +storage.getValue("SETTINGS_PERIODIC_HOUR_DOWNLOAD", function (hour) { + storage.getValue("SETTINGS_PERIODIC_MINUTE_DOWNLOAD", function (minute) { + if (typeof hour !== "number" || typeof minute !== "number") { + return; + } else { + autoDownloadCsv(hour, minute); } - chrome.alarms.create("periodic_Download", { - when: triggerTime.getTime(), - periodInMinutes: 1440, // 24 hours - }); - chrome.alarms.onAlarm.addListener(function (alarm) { - if (alarm.name === "periodic_Download") { - exportToCSV(); - } - }); + }); +}); + +function autoDownloadCsv(hour, minute) { + var now = new Date(); + var triggerTime = new Date( + now.getFullYear(), + now.getMonth(), + now.getDate(), + hour, + minute, + 0, + 0 + ); + + if (triggerTime < now) { + triggerTime.setDate(triggerTime.getDate() + 1); } - + chrome.alarms.create("periodic_Download", { + when: triggerTime.getTime(), + periodInMinutes: 1440, // 24 hours + }); + chrome.alarms.onAlarm.addListener(function (alarm) { + if (alarm.name === "periodic_Download") { + exportToCSV(); + } + }); +} + loadPermissions(); addListener(); loadAddDataFromStorage(); updateSummaryTime(); updateStorage(); - chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) { - console.log("chrome listener triggered in background.js") - if (request.action === "sendBrowserActivityData") { - console.log("triggering sendBrowserActivityData function"); - sendBrowserActivityData(); - } + console.log("chrome listener triggered in background.js"); + if (request.action === "sendBrowserActivityData") { + console.log("triggering sendBrowserActivityData function"); + sendBrowserActivityData(); + } }); +// background.js + +async function sendBrowserActivityData() { + // const tabsData = getTabsData(); + const currentDate = new Date().toLocaleDateString("en-US"); // Get the current date in mm/dd/yyyy format + const dailyActivities = []; + + // Iterate through the tabsData and create DailyActivity objects + for (const tabData of tabs) { + for (const day of tabData.days) { + console.log(day.date, currentDate); + if (day.date === currentDate) { + console.log("triggered"); + dailyActivities.push({ + url: tabData.url, + date: currentDate, + seconds: day.summary, + }); + } + } + } + + const baseUrl = 'http://3.92.212.148:8094/api/v1/dailyActivity/addActivities'; -function sendBrowserActivityData() { - // const backendUrl = "https://your-backend-url.com/api/browser-activity"; - console.log(tabs) - - const browserActivityData = tabs.map(tab => { - return { - url: tab.url, - days: tab.days.map(day => { - return { - date: day.date, - summary: day.summary, - time: day.time - }; - }) - }; - }); + const param1 = "computer1" - console.log(browserActivityData); - - // axios.post(backendUrl, browserActivityData) - // .then(response => console.log("Data sent successfully:", response.data)) - // .catch(error => console.error("Error sending data:", error)); - } - \ No newline at end of file + const urlWithParams = `${baseUrl}?computer=${encodeURIComponent(param1)}`; + + // Send the dailyActivities list to the backend + const response = await fetch(urlWithParams, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(dailyActivities), + }); + + // Parse the response as JSON + const responseData = await response.json(); + + console.log(responseData); + + // Send the message back to the content script + chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { + chrome.tabs.sendMessage(tabs[0].id, { action: 'updateBackendMessage', message: responseData.message }); + }); +} diff --git a/src/scripts/ui.js b/src/scripts/ui.js index 443c03d..623dffb 100644 --- a/src/scripts/ui.js +++ b/src/scripts/ui.js @@ -1,413 +1,541 @@ -'use strict'; +"use strict"; class UI { - getTableOfSite() { - return document.getElementById('resultTable'); + getTableOfSite() { + return document.getElementById("resultTable"); + } + + setUIForToday() { + document.getElementById("btnToday").classList.add("active"); + document.getElementById("btnAll").classList.remove("active"); + document.getElementById("btnByDays").classList.remove("active"); + document.getElementById("btnSendData").classList.remove("active"); + document.getElementById("blockForChartBtn").classList.remove("hide"); + document.getElementById("stats").classList.add("hide"); + document.getElementById("labelForTimeInterval").classList.add("hide"); + this.setUIForDonutChart(); + + this.clearUI(); + } + + setUIForAll() { + document.getElementById("btnAll").classList.add("active"); + document.getElementById("btnToday").classList.remove("active"); + document.getElementById("btnByDays").classList.remove("active"); + document.getElementById("btnSendData").classList.remove("active"); + document.getElementById("blockForChartBtn").classList.add("hide"); + document.getElementById("stats").classList.remove("hide"); + document.getElementById("labelForTimeInterval").classList.add("hide"); + + this.clearUI(); + } + + setUIForByDays(range) { + document.getElementById("btnByDays").classList.add("active"); + document.getElementById("btnAll").classList.remove("active"); + document.getElementById("btnToday").classList.remove("active"); + document.getElementById("btnSendData").classList.remove("active"); + document.getElementById("blockForChartBtn").classList.add("hide"); + document.getElementById("stats").classList.add("hide"); + document.getElementById("labelForTimeInterval").classList.add("hide"); + + this.clearUI(); + this.addBlockForCalendar(range); + } + + clearUI() { + document.getElementById("resultTable").innerHTML = null; + document.getElementById("chart").innerHTML = null; + document.getElementById("timeChart").innerHTML = null; + document.getElementById("byDays").innerHTML = null; + document.getElementById("sendDataPage").style.display = "none"; + } + + setUIForDonutChart() { + document.getElementById("donutChartBtn").classList.add("active"); + document.getElementById("heatMapChartBtn").classList.remove("active"); + document.getElementById("timeChart").innerHTML = null; + document.getElementById("labelForTimeInterval").classList.add("hide"); + } + + setUIForTimeChart() { + document.getElementById("donutChartBtn").classList.remove("active"); + document.getElementById("heatMapChartBtn").classList.add("active"); + document.getElementById("chart").innerHTML = null; + document.getElementById("labelForTimeInterval").classList.remove("hide"); + } + + setUIForSendData() { + document.getElementById('btnSendData').classList.add('active'); + + // Remove the 'active' class from the other buttons + document.getElementById('btnToday').classList.remove('active'); + document.getElementById('btnAll').classList.remove('active'); + document.getElementById('btnByDays').classList.remove('active'); + + // Hide the unnecessary elements + document.getElementById('blockForChartBtn').classList.add('hide'); + document.getElementById('stats').classList.add('hide'); + document.getElementById('labelForTimeInterval').classList.add('hide'); + + // Clear the UI + this.clearUI(); + + // Hide the main content and show the send data page + document.getElementById("sendDataPage").style.display = "block"; + } + + fillEmptyBlock(elementName) { + document.getElementById(elementName).innerHTML = + '

No data

'; + } + + fillEmptyBlockForDaysIfInvalid() { + document.getElementById("tableForDaysBlock").innerHTML = + '

Invalid date

'; + } + + fillEmptyBlockForDays() { + document.getElementById("tableForDaysBlock").innerHTML = + '

No data

'; + } + + addHrAfterChart() { + document.getElementById("chart").appendChild(document.createElement("hr")); + } + + setActiveTooltipe(currentTab) { + if (currentTab !== "") { + var element = document.getElementById(currentTab); + if (element !== null) { + var event = new Event("mouseenter"); + document.getElementById(currentTab).dispatchEvent(event); + } } - - setUIForToday() { - document.getElementById('btnToday').classList.add('active'); - document.getElementById('btnAll').classList.remove('active'); - document.getElementById('btnByDays').classList.remove('active'); - document.getElementById('blockForChartBtn').classList.remove('hide'); - document.getElementById('stats').classList.add('hide'); - document.getElementById('labelForTimeInterval').classList.add('hide'); - this.setUIForDonutChart(); - - this.clearUI(); - } - - setUIForAll() { - document.getElementById('btnAll').classList.add('active'); - document.getElementById('btnToday').classList.remove('active'); - document.getElementById('btnByDays').classList.remove('active'); - document.getElementById('blockForChartBtn').classList.add('hide'); - document.getElementById('stats').classList.remove('hide'); - document.getElementById('labelForTimeInterval').classList.add('hide'); - - this.clearUI(); - } - - setUIForByDays(range) { - document.getElementById('btnByDays').classList.add('active'); - document.getElementById('btnAll').classList.remove('active'); - document.getElementById('btnToday').classList.remove('active'); - document.getElementById('blockForChartBtn').classList.add('hide'); - document.getElementById('stats').classList.add('hide'); - document.getElementById('labelForTimeInterval').classList.add('hide'); - - this.clearUI(); - this.addBlockForCalendar(range); - } - - clearUI() { - document.getElementById('resultTable').innerHTML = null; - document.getElementById('chart').innerHTML = null; - document.getElementById('timeChart').innerHTML = null; - document.getElementById('byDays').innerHTML = null; - } - - setUIForDonutChart() { - document.getElementById('donutChartBtn').classList.add('active'); - document.getElementById('heatMapChartBtn').classList.remove('active'); - document.getElementById('timeChart').innerHTML = null; - document.getElementById('labelForTimeInterval').classList.add('hide'); - } - - setUIForTimeChart() { - document.getElementById('donutChartBtn').classList.remove('active'); - document.getElementById('heatMapChartBtn').classList.add('active'); - document.getElementById('chart').innerHTML = null; - document.getElementById('labelForTimeInterval').classList.remove('hide'); - } - - fillEmptyBlock(elementName) { - document.getElementById(elementName).innerHTML = '

No data

'; - } - - fillEmptyBlockForDaysIfInvalid() { - document.getElementById('tableForDaysBlock').innerHTML = '

Invalid date

'; - } - - fillEmptyBlockForDays() { - document.getElementById('tableForDaysBlock').innerHTML = '

No data

'; + } + + drawChart(tabs) { + var donut = donutChart() + .width(550) + .height(230) + .cornerRadius(5) // sets how rounded the corners are on each slice + .padAngle(0.02) // effectively dictates the gap between slices + .variable("percentage") + .category("url"); + + if (setting_dark_mode) donut.darkMode(true); + else donut.darkMode(false); + + d3.select("#chart") + .datum(tabs) // bind data to the div + .call(donut); // draw chart in div + } + + drawTimeChart(tabs) { + drawIntervalChart(tabs); + } + + drawBarChart(days) { + d3.select("#barChart").datum(days); + barChart(days, setting_dark_mode); + } + + addTableHeader(currentTypeOfList, counterOfSite, totalTime, totalDays) { + function fillSummaryTime(totalTime) { + let arrayTime = getArrayTime(totalTime); + let stringTime = ""; + if (arrayTime.days > 0) stringTime += arrayTime.days + " days "; + stringTime += arrayTime.hours + " hours "; + stringTime += arrayTime.mins + " minutes "; + return stringTime; } - addHrAfterChart() { - document.getElementById('chart').appendChild(document.createElement('hr')); + var p = document.createElement("p"); + p.classList.add("table-header"); + if (currentTypeOfList === TypeListEnum.ToDay) + p.innerHTML = `Today (${counterOfSite} sites)
${convertShortSummaryTimeToLongString( + totalTime + )}`; + if (currentTypeOfList === TypeListEnum.All && totalDays !== undefined) { + if (totalDays.countOfDays > 0) { + p.innerHTML = + "Aggregate data since " + + new Date(totalDays.minDate).toLocaleDateString() + + " (" + + totalDays.countOfDays + + " days) (" + + counterOfSite + + " sites)
" + + fillSummaryTime(totalTime) + + ""; + } else { + p.innerHTML = + "Aggregate data since " + + new Date().toLocaleDateString() + + " (" + + counterOfSite + + " sites)
" + + convertShortSummaryTimeToLongString(totalTime) + + ""; + } } - - setActiveTooltipe(currentTab) { - if (currentTab !== '') { - var element = document.getElementById(currentTab); - if (element !== null) { - var event = new Event("mouseenter"); - document.getElementById(currentTab).dispatchEvent(event); - } + this.getTableOfSite().appendChild(p); + } + + addLineToTableOfSite( + tab, + currentTab, + summaryTime, + typeOfList, + counter, + blockName + ) { + var div = document.createElement("div"); + var tabUrlString = tab.url; + div.addEventListener("mouseenter", function () { + if (document.getElementById("chart").innerHTML !== "") { + var item = document.getElementById(tab.url); + if (item !== null) { + item.dispatchEvent(new Event("mouseenter")); + item.classList.add("mouse-over"); + } else { + document + .getElementById("Others") + .dispatchEvent(new Event("mouseenter")); + document.getElementById("Others").classList.add("mouse-over"); } + } + }); + div.addEventListener("mouseout", function () { + if (document.getElementById("chart").innerHTML !== "") { + var item = document.getElementById(tab.url); + if (item !== null) { + item.classList.remove("mouse-over"); + } else document.getElementById("Others").classList.remove("mouse-over"); + } + }); + div.classList.add("inline-flex"); + + var divForImg = document.createElement("div"); + var img = document.createElement("img"); + img.setAttribute("height", 27); + if (tab.favicon !== undefined || tab.favicon == null) + img.setAttribute("src", tab.favicon); + else img.setAttribute("src", "/icons/empty.png"); + divForImg.classList.add("block-img"); + divForImg.appendChild(img); + + var divForPath = document.createElement("div"); + + var url = this.createElement("p", ["p-url"], tabUrlString); + url.setAttribute("href", "https://" + tabUrlString); + url.addEventListener("click", function (e) { + if (e.target.attributes.href.value != undefined) + chrome.tabs.create({ url: e.target.attributes.href.value }); + }); + + var visits = this.createElement( + "p", + ["p-visits"], + (function () { + if (counter == 0) return "0 visits"; + if (counter > 1) return `${counter} visits`; + if (counter == 1) return `${counter} visit`; + })() + ); + + divForPath.appendChild(url); + divForPath.appendChild(visits); + + if (tab.url == currentTab) { + var divForImage = document.createElement("div"); + div.classList.add("span-active-url"); + var imgCurrentDomain = document.createElement("img"); + imgCurrentDomain.setAttribute("src", "/icons/eye.png"); + imgCurrentDomain.setAttribute("height", 20); + imgCurrentDomain.classList.add("margin-left-5"); + divForImage.appendChild(imgCurrentDomain); + var currentDomainTooltip = this.createElement( + "span", + ["tooltiptext"], + "Current domain" + ); + divForImage.classList.add("tooltip", "current-url"); + divForImage.appendChild(currentDomainTooltip); + url.appendChild(divForImage); } - drawChart(tabs) { - var donut = donutChart() - .width(550) - .height(230) - .cornerRadius(5) // sets how rounded the corners are on each slice - .padAngle(0.020) // effectively dictates the gap between slices - .variable('percentage') - .category('url'); - - if (setting_dark_mode) - donut.darkMode(true); - else donut.darkMode(false); - - d3.select('#chart') - .datum(tabs) // bind data to the div - .call(donut); // draw chart in div - } - - drawTimeChart(tabs) { - drawIntervalChart(tabs); - } - - drawBarChart(days) { - d3.select('#barChart').datum(days); - barChart(days, setting_dark_mode); - } - - addTableHeader(currentTypeOfList, counterOfSite, totalTime, totalDays) { - function fillSummaryTime(totalTime){ - let arrayTime = getArrayTime(totalTime); - let stringTime = ''; - if (arrayTime.days > 0) stringTime += arrayTime.days + ' days '; - stringTime += arrayTime.hours + ' hours '; - stringTime += arrayTime.mins + ' minutes '; - return stringTime; - } - - var p = document.createElement('p'); - p.classList.add('table-header'); - if (currentTypeOfList === TypeListEnum.ToDay) - p.innerHTML = `Today (${counterOfSite} sites)
${convertShortSummaryTimeToLongString(totalTime)}`; - if (currentTypeOfList === TypeListEnum.All && totalDays !== undefined) { - if (totalDays.countOfDays > 0) { - p.innerHTML = 'Aggregate data since ' + new Date(totalDays.minDate).toLocaleDateString() + ' (' + totalDays.countOfDays + ' days) (' + counterOfSite + ' sites)
' + fillSummaryTime(totalTime) + ''; - } else { - p.innerHTML = 'Aggregate data since ' + new Date().toLocaleDateString() + ' (' + counterOfSite + ' sites)
' + convertShortSummaryTimeToLongString(totalTime) + ''; - } + if (typeOfList !== undefined && typeOfList === TypeListEnum.ToDay) { + if (restrictionList !== undefined && restrictionList.length > 0) { + var item = restrictionList.find((x) => + isDomainEquals(x.domain, tab.url) + ); + if (item !== undefined) { + var divLimit = this.createElement("div", ["tooltip", "inline-block"]); + var limitIcon = this.createElement("img", [ + "margin-left-5", + "tooltip", + ]); + limitIcon.height = 20; + limitIcon.src = "/icons/limit.png"; + var tooltip = this.createElement( + "span", + ["tooltiptext"], + "Daily limit is " + convertShortSummaryTimeToLongString(item.time) + ); + divLimit = this.appendChild(divLimit, [limitIcon, tooltip]); + url.appendChild(divLimit); } - - this.getTableOfSite().appendChild(p); + } } - addLineToTableOfSite(tab, currentTab, summaryTime, typeOfList, counter, blockName) { - var div = document.createElement('div'); - var tabUrlString = tab.url; - div.addEventListener('mouseenter', function() { - if (document.getElementById('chart').innerHTML !== '') { - var item = document.getElementById(tab.url); - if (item !== null) { - item.dispatchEvent(new Event('mouseenter')); - item.classList.add('mouse-over'); - } else { - document.getElementById('Others').dispatchEvent(new Event('mouseenter')); - document.getElementById('Others').classList.add('mouse-over'); - } - } - }); - div.addEventListener('mouseout', function() { - if (document.getElementById('chart').innerHTML !== '') { - var item = document.getElementById(tab.url); - if (item !== null) { - item.classList.remove('mouse-over'); - } else document.getElementById('Others').classList.remove('mouse-over'); - } - }); - div.classList.add('inline-flex'); - - var divForImg = document.createElement('div'); - var img = document.createElement('img'); - img.setAttribute('height', 27); - if (tab.favicon !== undefined || tab.favicon == null) - img.setAttribute('src', tab.favicon); - else img.setAttribute('src', '/icons/empty.png'); - divForImg.classList.add('block-img'); - divForImg.appendChild(img); - - var divForPath = document.createElement('div'); - - var url = this.createElement('p', ['p-url'], tabUrlString); - url.setAttribute('href', 'https://' + tabUrlString); - url.addEventListener('click', function(e){ - if (e.target.attributes.href.value != undefined) - chrome.tabs.create({ url: e.target.attributes.href.value }) - }) - - var visits = this.createElement('p', ['p-visits'], function() { - if (counter == 0) return '0 visits'; - if (counter > 1) return `${counter} visits`; - if (counter == 1) return `${counter} visit`; - }()); - - divForPath.appendChild(url); - divForPath.appendChild(visits); - - if (tab.url == currentTab) { - var divForImage = document.createElement('div'); - div.classList.add('span-active-url'); - var imgCurrentDomain = document.createElement('img'); - imgCurrentDomain.setAttribute('src', '/icons/eye.png'); - imgCurrentDomain.setAttribute('height', 20); - imgCurrentDomain.classList.add('margin-left-5'); - divForImage.appendChild(imgCurrentDomain); - var currentDomainTooltip = this.createElement('span', ['tooltiptext'], 'Current domain'); - divForImage.classList.add('tooltip', 'current-url'); - divForImage.appendChild(currentDomainTooltip); - url.appendChild(divForImage); - } - - if (typeOfList !== undefined && typeOfList === TypeListEnum.ToDay) { - if (restrictionList !== undefined && restrictionList.length > 0) { - var item = restrictionList.find(x => isDomainEquals(x.domain, tab.url)); - if (item !== undefined) { - var divLimit = this.createElement('div', ['tooltip', 'inline-block']); - var limitIcon = this.createElement('img', ['margin-left-5', 'tooltip']); - limitIcon.height = 20; - limitIcon.src = '/icons/limit.png'; - var tooltip = this.createElement('span', ['tooltiptext'], "Daily limit is " + convertShortSummaryTimeToLongString(item.time)); - divLimit = this.appendChild(divLimit, [limitIcon, tooltip]); - url.appendChild(divLimit); - } - } - } - - var spanPercentage = this.createElement('span', ['span-percentage'], getPercentage(summaryTime)); - var spanTime = this.createElement('span', ['span-time']); - this.createElementsForTotalTime(summaryTime, typeOfList, spanTime); - - div = this.appendChild(div, [divForImg, divForPath, spanPercentage, spanTime]); - if (blockName !== undefined) - document.getElementById(blockName).appendChild(div); - else - this.getTableOfSite().appendChild(div); + var spanPercentage = this.createElement( + "span", + ["span-percentage"], + getPercentage(summaryTime) + ); + var spanTime = this.createElement("span", ["span-time"]); + this.createElementsForTotalTime(summaryTime, typeOfList, spanTime); + + div = this.appendChild(div, [ + divForImg, + divForPath, + spanPercentage, + spanTime, + ]); + if (blockName !== undefined) + document.getElementById(blockName).appendChild(div); + else this.getTableOfSite().appendChild(div); + } + + createElementsForTotalTime(summaryTime, typeOfList, parentElement) { + var arr = getArrayTime(summaryTime); + var isNextPartActiv = false; + var getCssClass = function (item) { + if (item > 0) { + isNextPartActiv = true; + return ["span-active-time"]; + } else { + if (isNextPartActiv) return ["span-active-time"]; + return null; + } + }; + if (typeOfList === TypeListEnum.All) { + var spanForDays = this.createElement( + "span", + getCssClass(arr.days), + arr.days + "d " + ); + this.appendChild(parentElement, [spanForDays]); } - - createElementsForTotalTime(summaryTime, typeOfList, parentElement) { - var arr = getArrayTime(summaryTime); - var isNextPartActiv = false; - var getCssClass = function(item) { - if (item > 0) { - isNextPartActiv = true; - return ['span-active-time']; - } else { - if (isNextPartActiv) - return ['span-active-time']; - return null; - } - }; - if (typeOfList === TypeListEnum.All) { - var spanForDays = this.createElement('span', getCssClass(arr.days), arr.days + 'd '); - this.appendChild(parentElement, [spanForDays]); - } - var spanForHour = this.createElement('span', getCssClass(arr.hours), arr.hours + 'h '); - var spanForMin = this.createElement('span', getCssClass(arr.mins), arr.mins + 'm '); - var spanForSec = this.createElement('span', getCssClass(arr.seconds), arr.seconds + 's '); - this.appendChild(parentElement, [spanForHour, spanForMin, spanForSec]); + var spanForHour = this.createElement( + "span", + getCssClass(arr.hours), + arr.hours + "h " + ); + var spanForMin = this.createElement( + "span", + getCssClass(arr.mins), + arr.mins + "m " + ); + var spanForSec = this.createElement( + "span", + getCssClass(arr.seconds), + arr.seconds + "s " + ); + this.appendChild(parentElement, [spanForHour, spanForMin, spanForSec]); + } + + addExpander() { + if (document.getElementById("expander") === null) { + var div = this.createElement("div", ["expander"], "Show all"); + div.id = "expander"; + div.addEventListener("click", function () { + ui.expand(); + }); + this.getTableOfSite().appendChild(div); } - - addExpander() { - if (document.getElementById('expander') === null) { - var div = this.createElement('div', ['expander'], 'Show all'); - div.id = 'expander'; - div.addEventListener('click', function() { - ui.expand(); - }); - this.getTableOfSite().appendChild(div); - } - } - - expand() { - getTabsForExpander(); - this.getTableOfSite().removeChild(document.getElementById('expander')); + } + + expand() { + getTabsForExpander(); + this.getTableOfSite().removeChild(document.getElementById("expander")); + } + + addBlockForCalendar(range) { + var div = document.getElementById("byDays"); + var barChart = document.createElement("div"); + barChart.id = "barChart"; + + var from = this.createElement("span", null, "From"); + var to = this.createElement("span", null, "To"); + + var calendarFirst = document.createElement("input"); + calendarFirst.id = "dateFrom"; + calendarFirst.type = "date"; + var previousDate = new Date(); + previousDate.setDate(previousDate.getDate() - getDateFromRange(range)); + calendarFirst.valueAsDate = new Date( + Date.UTC( + previousDate.getFullYear(), + previousDate.getMonth(), + previousDate.getDate() + ) + ); + + var calendarTwo = document.createElement("input"); + calendarTwo.id = "dateTo"; + calendarTwo.type = "date"; + calendarTwo.valueAsDate = new Date( + Date.UTC( + new Date().getFullYear(), + new Date().getMonth(), + new Date().getDate() + ) + ); + + var tableForDaysBlock = document.createElement("div"); + tableForDaysBlock.id = "tableForDaysBlock"; + + div = this.appendChild(div, [ + barChart, + from, + calendarFirst, + to, + calendarTwo, + ]); + + div.append(tableForDaysBlock); + + document.getElementById("dateFrom").addEventListener("change", function () { + getTabsByDays(tabsFromStorage); + }); + + document.getElementById("dateTo").addEventListener("change", function () { + getTabsByDays(tabsFromStorage); + }); + } + + getDateRange() { + return { + from: new Date(document.getElementById("dateFrom").value), + to: new Date(document.getElementById("dateTo").value), + }; + } + + fillListOfDays(days, allDays) { + var parent = document.getElementById("tableForDaysBlock"); + parent.innerHTML = null; + document.getElementById("barChart").innerHTML = null; + if (days.length > 0) { + var daysForBarChart = this.fillDaysForBarChart(days, allDays); + this.drawBarChart(daysForBarChart); + + var header = this.createElement("div", ["table-header"]); + + var headerTitleDate = this.createElement( + "span", + ["header-title-day"], + "Day" + ); + var headerTitleTime = this.createElement( + "span", + ["header-title-time"], + "Summary time" + ); + + header = this.appendChild(header, [headerTitleDate, headerTitleTime]); + parent.appendChild(header); + + for (var i = 0; i < days.length; i++) { + var check = this.createElement("input", ["toggle"]); + check.type = "checkbox"; + check.id = days[i].date; + + var label = this.createElement("label", ["day-block", "lbl-toggle"]); + label.setAttribute("for", days[i].date); + var span = this.createElement( + "p", + ["day"], + new Date(days[i].date).toLocaleDateString() + ); + var spanTime = this.createElement("p", ["span-time"]); + this.createElementsForTotalTime( + days[i].total, + TypeListEnum.ByDays, + spanTime + ); + + label = this.appendChild(label, [span, spanTime]); + parent = this.appendChild(parent, [check, label]); + + var div = this.createElement( + "div", + ["collapsible-content"], + convertSummaryTimeToString(days[i].total) + ); + div.id = days[i].date + "_block"; + parent.appendChild(div); + + document + .getElementById(days[i].date) + .addEventListener("click", function () { + var element = document.getElementById(this.id + "_block"); + element.innerHTML = null; + getTabsFromStorageByDay(this.id, this.id + "_block"); + }); + } + } else { + this.fillEmptyBlock("tableForDaysBlock"); } - - addBlockForCalendar(range) { - var div = document.getElementById('byDays'); - var barChart = document.createElement('div'); - barChart.id = 'barChart'; - - var from = this.createElement('span', null, 'From'); - var to = this.createElement('span', null, 'To'); - - var calendarFirst = document.createElement('input'); - calendarFirst.id = 'dateFrom'; - calendarFirst.type = 'date'; - var previousDate = new Date(); - previousDate.setDate(previousDate.getDate() - getDateFromRange(range)); - calendarFirst.valueAsDate = new Date(Date.UTC(previousDate.getFullYear(), previousDate.getMonth(), previousDate.getDate())); - - var calendarTwo = document.createElement('input'); - calendarTwo.id = 'dateTo'; - calendarTwo.type = 'date'; - calendarTwo.valueAsDate = new Date(Date.UTC(new Date().getFullYear(), new Date().getMonth(), new Date().getDate())); - - var tableForDaysBlock = document.createElement('div'); - tableForDaysBlock.id = 'tableForDaysBlock'; - - div = this.appendChild(div, [barChart, from, calendarFirst, to, calendarTwo]); - - div.append(tableForDaysBlock); - - document.getElementById('dateFrom').addEventListener('change', function() { - getTabsByDays(tabsFromStorage); + } + + fillDaysForBarChart(days, allDays) { + var resultList = []; + allDays.forEach((element) => { + var day = days.find((x) => x.date == element); + if (day !== undefined) { + resultList.push({ + date: day.date, + total: day.total, }); - - document.getElementById('dateTo').addEventListener('change', function() { - getTabsByDays(tabsFromStorage); + } else + resultList.push({ + date: element, + total: 0, }); - } - - getDateRange() { - return { - 'from': new Date(document.getElementById('dateFrom').value), - 'to': new Date(document.getElementById('dateTo').value) - }; - } - - fillListOfDays(days, allDays) { - var parent = document.getElementById('tableForDaysBlock'); - parent.innerHTML = null; - document.getElementById('barChart').innerHTML = null; - if (days.length > 0) { - var daysForBarChart = this.fillDaysForBarChart(days, allDays); - this.drawBarChart(daysForBarChart); - - var header = this.createElement('div', ['table-header']); + }); - var headerTitleDate = this.createElement('span', ['header-title-day'], 'Day'); - var headerTitleTime = this.createElement('span', ['header-title-time'], 'Summary time'); + return resultList; + } - header = this.appendChild(header, [headerTitleDate, headerTitleTime]); - parent.appendChild(header); - - for (var i = 0; i < days.length; i++) { - var check = this.createElement('input', ['toggle']); - check.type = 'checkbox'; - check.id = days[i].date; - - var label = this.createElement('label', ['day-block', 'lbl-toggle']); - label.setAttribute('for', days[i].date); - var span = this.createElement('p', ['day'], new Date(days[i].date).toLocaleDateString()); - var spanTime = this.createElement('p', ['span-time']); - this.createElementsForTotalTime(days[i].total, TypeListEnum.ByDays, spanTime); - - label = this.appendChild(label, [span, spanTime]); - parent = this.appendChild(parent, [check, label]); - - var div = this.createElement('div', ['collapsible-content'], convertSummaryTimeToString(days[i].total)); - div.id = days[i].date + '_block'; - parent.appendChild(div); - - document.getElementById(days[i].date).addEventListener('click', function() { - var element = document.getElementById(this.id + '_block'); - element.innerHTML = null; - getTabsFromStorageByDay(this.id, this.id + '_block') - }); - } - - } else { - this.fillEmptyBlock('tableForDaysBlock'); - } + createElement(type, css, innerText) { + var element = document.createElement(type); + if (css !== undefined && css !== null) { + for (let i = 0; i < css.length; i++) element.classList.add(css[i]); } + if (innerText !== undefined) element.innerHTML = innerText; - fillDaysForBarChart(days, allDays) { - var resultList = []; - allDays.forEach(element => { - var day = days.find(x => x.date == element); - if (day !== undefined) { - resultList.push({ - 'date': day.date, - 'total': day.total - }); - } else resultList.push({ - 'date': element, - 'total': 0 - }); - }); + return element; + } - return resultList; - } + appendChild(element, children) { + for (let i = 0; i < children.length; i++) element.appendChild(children[i]); - createElement(type, css, innerText) { - var element = document.createElement(type); - if (css !== undefined && css !== null) { - for (let i = 0; i < css.length; i++) - element.classList.add(css[i]); - } - if (innerText !== undefined) - element.innerHTML = innerText; + return element; + } - return element; - } + setPreloader() { + document.getElementById("preloader").classList.add("preloader"); + } - appendChild(element, children) { - for (let i = 0; i < children.length; i++) - element.appendChild(children[i]); + setMode() { + if (setting_dark_mode) document.body.classList.add("dark-mode"); + } - return element; - } - - setPreloader() { - document.getElementById('preloader').classList.add('preloader'); - } - - setMode(){ - if (setting_dark_mode) - document.body.classList.add('dark-mode'); - } - - removePreloader() { - document.getElementById('preloader').classList.remove('preloader'); - document.getElementById('preloader').classList.add('hide'); - } -} \ No newline at end of file + removePreloader() { + document.getElementById("preloader").classList.remove("preloader"); + document.getElementById("preloader").classList.add("hide"); + } +} diff --git a/src/scripts/webact.js b/src/scripts/webact.js index 9f27087..36a8a3b 100644 --- a/src/scripts/webact.js +++ b/src/scripts/webact.js @@ -87,34 +87,42 @@ document.addEventListener('DOMContentLoaded', function () { ui.setUIForToday(); getDataFromStorage(); }); + document.getElementById('donutChartBtn').addEventListener('click', function () { ui.setUIForDonutChart(); getDataFromStorage(); }); + document.getElementById('heatMapChartBtn').addEventListener('click', function () { ui.setUIForTimeChart(); getTimeIntervalList(); }); + document.getElementById('btnAll').addEventListener('click', function () { currentTypeOfList = TypeListEnum.All; ui.setUIForAll(); getDataFromStorage(); }); + document.getElementById('btnByDays').addEventListener('click', function () { currentTypeOfList = TypeListEnum.ByDays; ui.setUIForByDays(setting_range_days); getDataFromStorageByDays(); }); + document.getElementById('statInActiveDayIcon').addEventListener('click', function () { fillBlockWithInActiveDay(); }); + document.getElementById('statActiveDayIcon').addEventListener('click', function () { fillBlockWithActiveDay(); }); + document.getElementById('closeHintBtn').addEventListener('click', function () { document.getElementById('hintForUsers').classList.add('hide'); storage.saveValue(SETTINGS_SHOW_HINT, false); }); + document.getElementById('settings').addEventListener('click', function () { if (chrome.runtime.openOptionsPage) { chrome.runtime.openOptionsPage(); @@ -123,11 +131,16 @@ document.addEventListener('DOMContentLoaded', function () { } }); - document.getElementById("btnSendData").addEventListener("click", function () { - console.log("button clicked here"); + document.getElementById('btnSendData').addEventListener('click', function () { + // Call a method from ui.js to handle the UI update + ui.setUIForSendData(); + }); + + document.getElementById('btnSendDataToBackend').addEventListener('click', function () { + // Call a method from ui.js to handle the UI update + chrome.runtime.sendMessage({ action: "sendBrowserActivityData" }); }); - }); firstInitPage();