Skip to content

Commit

Permalink
added swdc headers and removed ping calls
Browse files Browse the repository at this point in the history
  • Loading branch information
xavluiz committed Jun 7, 2020
1 parent 0e8e106 commit 575ceb7
Show file tree
Hide file tree
Showing 16 changed files with 195 additions and 148 deletions.
17 changes: 11 additions & 6 deletions Software.py
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,11 @@ def initializeUser():
serverAvailable = serverIsAvailable()
fileExists = softwareSessionFileExists()
jwt = getItem("jwt")
log("JWT VAL: %s" % jwt)

# print("INITALIZING CODE TIME")
# print("JWT: %s" % jwt)
# print("file exists: %s" % fileExists)

if (fileExists is False or jwt is None):
if (serverAvailable is False):
if (retry_counter == 0):
Expand All @@ -357,7 +361,7 @@ def initializeUser():
check_online_interval_sec, initializeUser)
initializeUserTimer.start()
else:
result = createAnonymousUser(serverAvailable)
result = createAnonymousUser()
if (result is None):
if (retry_counter == 0):
showOfflinePrompt()
Expand All @@ -371,8 +375,9 @@ def initializeUser():


def initializePlugin(initializedAnonUser, serverAvailable):
PACKAGE_NAME = __name__.split('.')[0]
log('Code Time: Loaded v%s of package name: %s' % (VERSION, PACKAGE_NAME))
name = getPluginName()
version = getVersion()
log('Code Time: Loaded v%s of package name: %s' % (version, name))
showStatus("Code Time")

setItem("sublime_lastUpdateTime", None)
Expand All @@ -382,7 +387,7 @@ def initializePlugin(initializedAnonUser, serverAvailable):

# fire off timer tasks (seconds, task)

setOnlineStatusTimer = Timer(2, setOnlineStatus)
setOnlineStatusTimer = Timer(5, setOnlineStatus)
setOnlineStatusTimer.start()

oneMin = 60
Expand Down Expand Up @@ -463,7 +468,7 @@ def setOnlineStatus():
# log("Code Time: Offline")

# run the check in another 1 minute
timer = Timer(60 * 1, setOnlineStatus)
timer = Timer(60 * 10, setOnlineStatus)
timer.start()


Expand Down
107 changes: 107 additions & 0 deletions lib/CommonUtil.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import time as timeModule
import platform
import json
import os

from .Constants import *
from datetime import *

def getUtcOffset():
timestamp = timeModule.time()
time_local = datetime.fromtimestamp(timestamp)
time_utc = datetime.utcfromtimestamp(timestamp)
offset_in_sec = round((time_local - time_utc).total_seconds())
return offset_in_sec

def getNowTimes():
nowInSec = round(timeModule.time())
offsetInSec = getUtcOffset()
localNowInSec = round(nowInSec + offsetInSec)
day = datetime.now().date().isoformat()
return {
'nowInSec': nowInSec,
'localNowInSec': localNowInSec,
'offsetInSec': offsetInSec,
'day': day
}

def getIsNewDay():
day = getNowTimes()['day']
currentDay = getItem('currentDay')
if (currentDay != day):
return True
else:
return False

def getOs():
system = platform.system()
return system

def getTimezone():
myTimezone = None
try:
myTimezone = datetime.now(timezone.utc).astimezone().tzname()
except Exception:
pass
return myTimezone

def getPluginId():
return PLUGIN_ID

def getVersion():
packageJson = os.path.join(os.path.dirname(__file__), '..', 'package.json')
version = "2.2.1"
try:
with open(packageJson) as jsonData:
loadedJsonData = json.load(jsonData)
version = loadedJsonData.get("version", "2.2.1")
except Exception as ex:
print("Error reading package info: %s" % ex)

return version

def getPluginName():
pluginName = __name__.split('.')[0]
return pluginName

# fetch a value from the .software/session.json file
def getItem(key):
jsonObj = getSoftwareSessionAsJson()

# return a default of None if key isn't found
val = jsonObj.get(key, None)

return val

# get an item from the session json file
def setItem(key, value):
jsonObj = getSoftwareSessionAsJson()
jsonObj[key] = value

content = json.dumps(jsonObj)

sessionFile = getSoftwareSessionFile()
with open(sessionFile, 'w') as f:
f.write(content)

def getSoftwareSessionAsJson():
try:
with open(getSoftwareSessionFile()) as sessionFile:
loadedSessionFile = json.load(sessionFile)
return loadedSessionFile
except Exception:
return {}

def getSoftwareSessionFile():
file = getSoftwareDir(True)
return os.path.join(file, 'session.json')

def getSoftwareDir(autoCreate):
softwareDataDir = os.path.expanduser('~')
softwareDataDir = os.path.join(softwareDataDir, '.software')
if (autoCreate is True):
os.makedirs(softwareDataDir, exist_ok=True)
return softwareDataDir



3 changes: 2 additions & 1 deletion lib/KpmManager.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from .SoftwareUtil import *
from .TimeSummaryData import *
from .Constants import *
from .CommonUtil import *

DEFAULT_DURATION = 60

Expand Down Expand Up @@ -53,7 +54,7 @@ def __init__(self, project):
self.keystrokes = 0
self.project = project
self.pluginId = PLUGIN_ID
self.version = VERSION
self.version = getVersion()
self.timezone = getTimezone()
self.os = getOs()
self.cumulative_editor_seconds = 0
Expand Down
41 changes: 20 additions & 21 deletions lib/SoftwareDashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from .SoftwareFileChangeInfoSummaryData import *
from .SoftwarePayload import *
from .TimeSummaryData import *
from .CommonUtil import *

DAY_CHECK_TIMER_INTERVAL = 60

Expand Down Expand Up @@ -50,32 +51,30 @@ def launchCodeTimeMetrics():


def fetchCodeTimeMetricsDashboard():
serverOnline = serverIsAvailable()
summaryInfoFile = getSummaryInfoFile()

if serverOnline:
# fetch the backend data
islinux = "true"
if isWindows() is True or isMac() is True:
islinux = "false"
# fetch the backend data
islinux = "true"
if isWindows() is True or isMac() is True:
islinux = "false"

# TODO: find sublime setting for showGitMEtrics and replace true with it
showGitMetrics = True
api = '/dashboard?showGit=' + 'true' + '&linux=' + islinux + '&showToday=false'
response = requestIt("GET", api, None, getItem("jwt"))
# TODO: find sublime setting for showGitMEtrics and replace true with it
showGitMetrics = True
api = '/dashboard?showGit=' + 'true' + '&linux=' + islinux + '&showToday=false'
response = requestIt("GET", api, None, getItem("jwt"))

summaryContent = ""
try:
summaryContent = response.read().decode('utf-8')
except Exception as ex:
summaryContent = SERVICE_NOT_AVAIL
log("Code Time: Unable to read response data: %s" % ex)
summaryContent = ""
try:
summaryContent = response.read().decode('utf-8')
except Exception as ex:
summaryContent = SERVICE_NOT_AVAIL
log("Code Time: Unable to read response data: %s" % ex)

try:
with open(summaryInfoFile, 'w', encoding='utf-8') as f:
f.write(summaryContent)
except Exception as ex:
log("Code Time: Unable to write dashboard summary content: %s" % ex)
try:
with open(summaryInfoFile, 'w', encoding='utf-8') as f:
f.write(summaryContent)
except Exception as ex:
log("Code Time: Unable to write dashboard summary content: %s" % ex)

# concat summary info with the dashboard file
dashboardFile = getDashboardFile()
Expand Down
20 changes: 16 additions & 4 deletions lib/SoftwareHttp.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import json
import sublime_plugin, sublime
from .SoftwareSettings import *
from .CommonUtil import *

USER_AGENT = 'Code Time Sublime Plugin'
lastMsg = None
Expand Down Expand Up @@ -40,6 +41,9 @@ def showStatus(msg):
msg = "⏱"
else:
lastMsg = msg

if (msg is None):
msg = "Code Time"

if (active_window is not None):
for view in active_window.views():
Expand Down Expand Up @@ -70,19 +74,19 @@ def requestIt(method, api, payload, jwt):

# try to update kpm data.
try:
headers = {'Content-Type': 'application/json', 'User-Agent': USER_AGENT}
connection = None
# create the connection
if ('localhost' in api_endpoint):
connection = http.client.HTTPConnection(api_endpoint)
else:
# httpLog("Creating HTTPS Connection")
connection = http.client.HTTPSConnection(api_endpoint)

headers = {'Content-Type': 'application/json', 'User-Agent': USER_AGENT}

if (jwt is not None):
headers['Authorization'] = jwt
elif (method is 'POST' and jwt is None):
httpLog("Code Time: no auth token available to post kpm data: %s" % payload)
# httpLog("Code Time: no auth token available to post kpm data: %s" % payload)
return None

# make the request
Expand All @@ -93,6 +97,14 @@ def requestIt(method, api, payload, jwt):
pass
# httpLog("Code Time: Sending [" + method + ": " + api_endpoint + "" + api + ", headers: " + json.dumps(headers) + "] payload: %s" % payload)

headers['X-SWDC-Plugin-Id'] = getPluginId()
headers['X-SWDC-Plugin-Name'] = getPluginName()
headers['X-SWDC-Plugin-Version'] = getVersion()
headers['X-SWDC-Plugin-OS'] = getOs()
headers['X-SWDC-Plugin-TZ'] = getTimezone()
headers['X-SWDC-Plugin-Offset'] = int(float(getUtcOffset() / 60))

# httpLog("HEADERS: %s" % headers)

# send the request
connection.request(method, api, payload, headers)
Expand All @@ -101,6 +113,6 @@ def requestIt(method, api, payload, jwt):
# httpLog("Code Time: " + api_endpoint + "" + api + " Response (%d)" % response.status)
return response
except Exception as ex:
print("Code Time: " + api + " Network error: %s" % ex)
print("Code Time: Response Error for " + api + ": %s" % ex)
return None

2 changes: 2 additions & 0 deletions lib/SoftwareMusic.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import time
from .SoftwareHttp import *
from .SoftwareUtil import *
from .CommonUtil import *


currentTrackInfo = {}

Expand Down
1 change: 1 addition & 0 deletions lib/SoftwareOffline.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from .SoftwareFileChangeInfoSummaryData import *
from .TimeSummaryData import *
from .Constants import *
from .CommonUtil import *

# This file is called SessionSummaryDataManager.js in Atom

Expand Down
1 change: 1 addition & 0 deletions lib/SoftwarePayload.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from .SoftwareOffline import *
from .SoftwareHttp import *
from .TimeSummaryData import *
from .CommonUtil import *

# send the data that has been saved offline
def sendOfflineData(isNewDay=False):
Expand Down
1 change: 1 addition & 0 deletions lib/SoftwareRepo.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from .SoftwareHttp import *
from .SoftwareUtil import *
from .SoftwareSettings import *
from .CommonUtil import *

ONE_HOUR_IN_SEC = 60 * 60
ONE_DAY_SEC = ONE_HOUR_IN_SEC * 24
Expand Down
1 change: 1 addition & 0 deletions lib/SoftwareSessionApp.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from .SoftwareHttp import *
from .SoftwareWallClock import *
from .SoftwareOffline import *
from .CommonUtil import *

def updateSessionSummaryFromServer(isNewDay=False):
jwt = getItem('jwt')
Expand Down
1 change: 1 addition & 0 deletions lib/SoftwareTree.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from .SoftwareRepo import *
from .SoftwareUserStatus import *
from .TimeSummaryData import *
from .CommonUtil import *

icons = {
"bolt-grey": "data:image/png;base64,iVBORw0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original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,16 @@
from .SoftwareDashboard import *
from .SoftwareSettings import *
from .SoftwarePayload import *
from .CommonUtil import *

loggedInCacheState = False
LOGIN_LABEL = "Log in"

def isLoggedOn(serverAvailable):
def isLoggedOn():
jwt = getItem("jwt")
if (serverAvailable and jwt is not None):
if (jwt is not None):

user = getUser(serverAvailable)
user = getUser()
if (user is not None and validateEmail(user.get("email", None))):
setItem("name", user.get("email"))
setItem("jwt", user.get("plugin_jwt"))
Expand Down Expand Up @@ -52,10 +53,8 @@ def getUserStatus():

currentUserStatus = {}

serverAvailable = serverIsAvailable()

# check if they're logged in or not
loggedOn = isLoggedOn(serverAvailable)
loggedOn = isLoggedOn()

setValue("logged_on", loggedOn)

Expand Down
Loading

0 comments on commit 575ceb7

Please sign in to comment.