2019-05-01 20:48:28 +03:00
|
|
|
# -*- coding: utf-8 -*-
|
2013-07-08 05:38:01 +04:00
|
|
|
""" ==========================================================
|
2016-10-24 13:41:46 +03:00
|
|
|
File: WakaTime.py
|
2013-07-08 05:38:01 +04:00
|
|
|
Description: Automatic time tracking for Sublime Text 2 and 3.
|
2014-03-06 01:55:08 +04:00
|
|
|
Maintainer: WakaTime <support@wakatime.com>
|
2014-03-13 04:03:14 +04:00
|
|
|
License: BSD, see LICENSE for more details.
|
2014-03-15 00:36:20 +04:00
|
|
|
Website: https://wakatime.com/
|
2013-07-08 05:38:01 +04:00
|
|
|
==========================================================="""
|
2013-07-02 13:21:13 +04:00
|
|
|
|
2015-04-01 02:19:30 +03:00
|
|
|
|
2022-06-25 19:46:38 +03:00
|
|
|
__version__ = '11.0.7'
|
2013-07-02 13:21:13 +04:00
|
|
|
|
2015-04-01 02:19:30 +03:00
|
|
|
|
2013-07-23 23:09:58 +04:00
|
|
|
import sublime
|
|
|
|
import sublime_plugin
|
|
|
|
|
2016-04-29 01:18:38 +03:00
|
|
|
import json
|
2013-08-05 09:11:22 +04:00
|
|
|
import os
|
2013-07-23 23:09:58 +04:00
|
|
|
import platform
|
2015-10-02 01:07:55 +03:00
|
|
|
import re
|
2022-01-06 21:23:09 +03:00
|
|
|
import shutil
|
2020-12-29 05:42:00 +03:00
|
|
|
import ssl
|
2018-10-01 07:29:04 +03:00
|
|
|
import subprocess
|
2013-08-08 13:17:47 +04:00
|
|
|
import sys
|
2013-07-02 13:21:13 +04:00
|
|
|
import time
|
2013-08-08 13:17:47 +04:00
|
|
|
import threading
|
2016-11-11 13:29:51 +03:00
|
|
|
import traceback
|
2015-02-24 09:20:27 +03:00
|
|
|
import webbrowser
|
2018-10-01 07:29:04 +03:00
|
|
|
from subprocess import STDOUT, PIPE
|
2016-11-11 13:29:51 +03:00
|
|
|
from zipfile import ZipFile
|
2020-12-29 05:42:00 +03:00
|
|
|
|
2016-04-29 01:18:38 +03:00
|
|
|
try:
|
|
|
|
import Queue as queue # py2
|
|
|
|
except ImportError:
|
|
|
|
import queue # py3
|
2020-12-29 05:42:00 +03:00
|
|
|
|
2020-03-01 03:15:40 +03:00
|
|
|
try:
|
2021-11-16 20:43:20 +03:00
|
|
|
from ConfigParser import SafeConfigParser as ConfigParser
|
|
|
|
from ConfigParser import Error as ConfigParserError
|
2020-03-01 03:15:40 +03:00
|
|
|
except ImportError:
|
2021-11-16 20:43:20 +03:00
|
|
|
from configparser import ConfigParser, Error as ConfigParserError
|
2020-03-01 03:15:40 +03:00
|
|
|
try:
|
2022-04-29 21:14:55 +03:00
|
|
|
from urllib2 import Request, urlopen, HTTPError
|
2020-03-01 03:15:40 +03:00
|
|
|
except ImportError:
|
2022-04-29 21:14:55 +03:00
|
|
|
from urllib.request import Request, urlopen
|
2021-10-31 22:57:28 +03:00
|
|
|
from urllib.error import HTTPError
|
2015-04-01 02:19:30 +03:00
|
|
|
|
2013-07-02 13:21:13 +04:00
|
|
|
|
2020-12-29 05:42:00 +03:00
|
|
|
is_py2 = (sys.version_info[0] == 2)
|
|
|
|
is_py3 = (sys.version_info[0] == 3)
|
2018-10-01 07:29:04 +03:00
|
|
|
is_win = platform.system() == 'Windows'
|
|
|
|
|
2016-01-02 09:20:02 +03:00
|
|
|
|
2020-12-29 05:42:00 +03:00
|
|
|
if is_py2:
|
2021-10-31 22:57:28 +03:00
|
|
|
import codecs
|
|
|
|
open = codecs.open
|
|
|
|
|
2020-12-29 05:42:00 +03:00
|
|
|
def u(text):
|
|
|
|
if text is None:
|
|
|
|
return None
|
2021-10-31 21:41:21 +03:00
|
|
|
if isinstance(text, unicode): # noqa: F821
|
2020-12-29 05:42:00 +03:00
|
|
|
return text
|
|
|
|
try:
|
|
|
|
return text.decode('utf-8')
|
|
|
|
except:
|
|
|
|
try:
|
|
|
|
return text.decode(sys.getdefaultencoding())
|
|
|
|
except:
|
|
|
|
try:
|
2021-10-31 21:41:21 +03:00
|
|
|
return unicode(text) # noqa: F821
|
2020-12-29 05:42:00 +03:00
|
|
|
except:
|
|
|
|
try:
|
|
|
|
return text.decode('utf-8', 'replace')
|
|
|
|
except:
|
|
|
|
try:
|
2021-10-31 21:41:21 +03:00
|
|
|
return unicode(str(text)) # noqa: F821
|
2020-12-29 05:42:00 +03:00
|
|
|
except:
|
2021-10-31 21:41:21 +03:00
|
|
|
return unicode('') # noqa: F821
|
2020-12-29 05:42:00 +03:00
|
|
|
|
|
|
|
elif is_py3:
|
|
|
|
def u(text):
|
|
|
|
if text is None:
|
|
|
|
return None
|
|
|
|
if isinstance(text, bytes):
|
|
|
|
try:
|
|
|
|
return text.decode('utf-8')
|
|
|
|
except:
|
|
|
|
try:
|
|
|
|
return text.decode(sys.getdefaultencoding())
|
|
|
|
except:
|
|
|
|
pass
|
|
|
|
try:
|
|
|
|
return str(text)
|
|
|
|
except:
|
|
|
|
return text.decode('utf-8', 'replace')
|
|
|
|
|
2016-01-02 09:20:02 +03:00
|
|
|
else:
|
2020-12-29 05:42:00 +03:00
|
|
|
raise Exception('Unsupported Python version: {0}.{1}.{2}'.format(
|
|
|
|
sys.version_info[0],
|
|
|
|
sys.version_info[1],
|
|
|
|
sys.version_info[2],
|
|
|
|
))
|
2016-01-02 09:20:02 +03:00
|
|
|
|
|
|
|
|
2018-10-01 07:29:04 +03:00
|
|
|
class Popen(subprocess.Popen):
|
|
|
|
"""Patched Popen to prevent opening cmd window on Windows platform."""
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
2022-01-06 18:56:45 +03:00
|
|
|
if is_win:
|
|
|
|
startupinfo = kwargs.get('startupinfo')
|
2018-10-01 07:29:04 +03:00
|
|
|
try:
|
|
|
|
startupinfo = startupinfo or subprocess.STARTUPINFO()
|
|
|
|
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
2022-01-06 18:56:45 +03:00
|
|
|
kwargs['startupinfo'] = startupinfo
|
2018-10-01 07:29:04 +03:00
|
|
|
super(Popen, self).__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
|
2013-07-08 05:38:01 +04:00
|
|
|
# globals
|
2013-08-08 13:17:47 +04:00
|
|
|
ST_VERSION = int(sublime.version())
|
2021-10-31 22:57:28 +03:00
|
|
|
HOME_FOLDER = os.path.realpath(os.environ.get('WAKATIME_HOME') or os.path.expanduser('~'))
|
|
|
|
RESOURCES_FOLDER = os.path.join(HOME_FOLDER, '.wakatime')
|
|
|
|
CONFIG_FILE = os.path.join(HOME_FOLDER, '.wakatime.cfg')
|
|
|
|
INTERNAL_CONFIG_FILE = os.path.join(HOME_FOLDER, '.wakatime-internal.cfg')
|
2021-10-31 21:41:21 +03:00
|
|
|
GITHUB_RELEASES_STABLE_URL = 'https://api.github.com/repos/wakatime/wakatime-cli/releases/latest'
|
|
|
|
GITHUB_DOWNLOAD_PREFIX = 'https://github.com/wakatime/wakatime-cli/releases/download'
|
2013-08-08 13:17:47 +04:00
|
|
|
SETTINGS_FILE = 'WakaTime.sublime-settings'
|
|
|
|
SETTINGS = {}
|
2015-05-06 22:25:52 +03:00
|
|
|
LAST_HEARTBEAT = {
|
2013-11-28 15:16:43 +04:00
|
|
|
'time': 0,
|
|
|
|
'file': None,
|
|
|
|
'is_write': False,
|
|
|
|
}
|
2018-10-07 06:40:12 +03:00
|
|
|
LAST_HEARTBEAT_SENT_AT = 0
|
2019-05-01 20:48:28 +03:00
|
|
|
LAST_FETCH_TODAY_CODING_TIME = 0
|
|
|
|
FETCH_TODAY_DEBOUNCE_COUNTER = 0
|
|
|
|
FETCH_TODAY_DEBOUNCE_SECONDS = 60
|
2021-10-31 21:41:21 +03:00
|
|
|
LATEST_CLI_VERSION = None
|
|
|
|
WAKATIME_CLI_LOCATION = None
|
2016-04-29 01:18:38 +03:00
|
|
|
HEARTBEATS = queue.Queue()
|
2018-10-07 06:40:12 +03:00
|
|
|
HEARTBEAT_FREQUENCY = 2 # minutes between logging heartbeat when editing same file
|
|
|
|
SEND_BUFFER_SECONDS = 30 # seconds between sending buffered heartbeats to API
|
2013-07-08 05:38:01 +04:00
|
|
|
|
2014-12-24 21:01:56 +03:00
|
|
|
|
2015-10-02 22:09:37 +03:00
|
|
|
# Log Levels
|
|
|
|
DEBUG = 'DEBUG'
|
|
|
|
INFO = 'INFO'
|
|
|
|
WARNING = 'WARNING'
|
|
|
|
ERROR = 'ERROR'
|
|
|
|
|
|
|
|
|
2021-10-31 21:41:21 +03:00
|
|
|
def parseConfigFile(configFile):
|
|
|
|
"""Returns a configparser.SafeConfigParser instance with configs
|
|
|
|
read from the config file. Default location of the config file is
|
|
|
|
at ~/.wakatime.cfg.
|
|
|
|
"""
|
2020-03-01 03:15:40 +03:00
|
|
|
|
2021-11-16 20:43:20 +03:00
|
|
|
kwargs = {} if is_py2 else {'strict': False}
|
|
|
|
configs = ConfigParser(**kwargs)
|
2021-10-31 21:41:21 +03:00
|
|
|
try:
|
|
|
|
with open(configFile, 'r', encoding='utf-8') as fh:
|
|
|
|
try:
|
2021-11-16 20:43:20 +03:00
|
|
|
if is_py2:
|
|
|
|
configs.readfp(fh)
|
|
|
|
else:
|
|
|
|
configs.read_file(fh)
|
2021-10-31 21:41:21 +03:00
|
|
|
return configs
|
2021-11-16 20:43:20 +03:00
|
|
|
except ConfigParserError:
|
2021-10-31 21:41:21 +03:00
|
|
|
log(ERROR, traceback.format_exc())
|
|
|
|
return None
|
|
|
|
except IOError:
|
|
|
|
log(DEBUG, "Error: Could not read from config file {0}\n".format(configFile))
|
2021-10-31 22:57:28 +03:00
|
|
|
return configs
|
2020-03-01 03:15:40 +03:00
|
|
|
|
2020-12-29 05:42:00 +03:00
|
|
|
|
|
|
|
class ApiKey(object):
|
|
|
|
_key = None
|
|
|
|
|
2019-05-29 16:42:38 +03:00
|
|
|
def read(self):
|
|
|
|
if self._key:
|
|
|
|
return self._key
|
|
|
|
|
|
|
|
key = SETTINGS.get('api_key')
|
|
|
|
if key:
|
|
|
|
self._key = key
|
|
|
|
return self._key
|
|
|
|
|
|
|
|
try:
|
2021-10-31 21:41:21 +03:00
|
|
|
configs = parseConfigFile(CONFIG_FILE)
|
2019-05-29 16:42:38 +03:00
|
|
|
if configs:
|
|
|
|
if configs.has_option('settings', 'api_key'):
|
|
|
|
key = configs.get('settings', 'api_key')
|
|
|
|
if key:
|
|
|
|
self._key = key
|
|
|
|
return self._key
|
|
|
|
except:
|
|
|
|
pass
|
|
|
|
|
|
|
|
return self._key
|
|
|
|
|
|
|
|
def write(self, key):
|
|
|
|
global SETTINGS
|
|
|
|
self._key = key
|
|
|
|
SETTINGS.set('api_key', str(key))
|
|
|
|
sublime.save_settings(SETTINGS_FILE)
|
|
|
|
|
|
|
|
|
|
|
|
APIKEY = ApiKey()
|
|
|
|
|
|
|
|
|
2016-04-29 01:18:38 +03:00
|
|
|
def set_timeout(callback, seconds):
|
|
|
|
"""Runs the callback after the given seconds delay.
|
|
|
|
|
|
|
|
If this is Sublime Text 3, runs the callback on an alternate thread. If this
|
|
|
|
is Sublime Text 2, runs the callback in the main thread.
|
|
|
|
"""
|
|
|
|
|
|
|
|
milliseconds = int(seconds * 1000)
|
|
|
|
try:
|
|
|
|
sublime.set_timeout_async(callback, milliseconds)
|
|
|
|
except AttributeError:
|
|
|
|
sublime.set_timeout(callback, milliseconds)
|
|
|
|
|
|
|
|
|
2015-10-02 22:09:37 +03:00
|
|
|
def log(lvl, message, *args, **kwargs):
|
|
|
|
try:
|
|
|
|
if lvl == DEBUG and not SETTINGS.get('debug'):
|
|
|
|
return
|
|
|
|
msg = message
|
|
|
|
if len(args) > 0:
|
|
|
|
msg = message.format(*args)
|
|
|
|
elif len(kwargs) > 0:
|
|
|
|
msg = message.format(**kwargs)
|
2016-09-23 09:36:23 +03:00
|
|
|
try:
|
|
|
|
print('[WakaTime] [{lvl}] {msg}'.format(lvl=lvl, msg=msg))
|
|
|
|
except UnicodeDecodeError:
|
2020-12-29 05:42:00 +03:00
|
|
|
print(u('[WakaTime] [{lvl}] {msg}').format(lvl=lvl, msg=u(msg)))
|
2015-10-02 22:09:37 +03:00
|
|
|
except RuntimeError:
|
2016-04-29 01:18:38 +03:00
|
|
|
set_timeout(lambda: log(lvl, message, *args, **kwargs), 0)
|
|
|
|
|
|
|
|
|
2019-05-01 20:48:28 +03:00
|
|
|
def update_status_bar(status=None, debounced=False, msg=None):
|
2016-04-29 01:18:38 +03:00
|
|
|
"""Updates the status bar."""
|
2019-05-01 20:48:28 +03:00
|
|
|
global LAST_FETCH_TODAY_CODING_TIME, FETCH_TODAY_DEBOUNCE_COUNTER
|
2016-04-29 01:18:38 +03:00
|
|
|
|
|
|
|
try:
|
2019-05-01 20:48:28 +03:00
|
|
|
if not msg and SETTINGS.get('status_bar_message') is not False and SETTINGS.get('status_bar_enabled'):
|
|
|
|
if SETTINGS.get('status_bar_coding_activity') and status == 'OK':
|
|
|
|
if debounced:
|
|
|
|
FETCH_TODAY_DEBOUNCE_COUNTER -= 1
|
|
|
|
if debounced or not LAST_FETCH_TODAY_CODING_TIME:
|
|
|
|
now = int(time.time())
|
|
|
|
if LAST_FETCH_TODAY_CODING_TIME and (FETCH_TODAY_DEBOUNCE_COUNTER > 0 or LAST_FETCH_TODAY_CODING_TIME > now - FETCH_TODAY_DEBOUNCE_SECONDS):
|
|
|
|
return
|
|
|
|
LAST_FETCH_TODAY_CODING_TIME = now
|
|
|
|
FetchStatusBarCodingTime().start()
|
|
|
|
return
|
|
|
|
else:
|
|
|
|
FETCH_TODAY_DEBOUNCE_COUNTER += 1
|
|
|
|
set_timeout(lambda: update_status_bar(status, debounced=True), FETCH_TODAY_DEBOUNCE_SECONDS)
|
|
|
|
return
|
|
|
|
else:
|
2019-05-10 19:18:38 +03:00
|
|
|
msg = 'WakaTime: {status}'.format(status=status)
|
2016-04-29 01:18:38 +03:00
|
|
|
|
2019-05-01 20:48:28 +03:00
|
|
|
if msg:
|
2016-04-29 01:18:38 +03:00
|
|
|
active_window = sublime.active_window()
|
|
|
|
if active_window:
|
|
|
|
for view in active_window.views():
|
|
|
|
view.set_status('wakatime', msg)
|
2019-05-01 20:48:28 +03:00
|
|
|
|
2016-04-29 01:18:38 +03:00
|
|
|
except RuntimeError:
|
2019-05-01 20:48:28 +03:00
|
|
|
set_timeout(lambda: update_status_bar(status=status, debounced=debounced, msg=msg), 0)
|
|
|
|
|
|
|
|
|
|
|
|
class FetchStatusBarCodingTime(threading.Thread):
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
threading.Thread.__init__(self)
|
|
|
|
|
2019-05-10 19:43:30 +03:00
|
|
|
self.debug = SETTINGS.get('debug')
|
2019-05-29 16:42:38 +03:00
|
|
|
self.api_key = APIKEY.read() or ''
|
2020-03-01 21:01:52 +03:00
|
|
|
self.proxy = SETTINGS.get('proxy')
|
2019-05-01 20:48:28 +03:00
|
|
|
|
|
|
|
def run(self):
|
|
|
|
if not self.api_key:
|
|
|
|
log(DEBUG, 'Missing WakaTime API key.')
|
|
|
|
return
|
2020-03-01 21:01:52 +03:00
|
|
|
if not isCliInstalled():
|
|
|
|
return
|
2019-05-01 20:48:28 +03:00
|
|
|
|
2019-05-10 19:43:30 +03:00
|
|
|
ua = 'sublime/%d sublime-wakatime/%s' % (ST_VERSION, __version__)
|
2020-12-29 05:42:00 +03:00
|
|
|
|
2021-10-31 21:41:21 +03:00
|
|
|
cmd = [
|
|
|
|
getCliLocation(),
|
2019-05-10 19:43:30 +03:00
|
|
|
'--today',
|
|
|
|
'--key', str(bytes.decode(self.api_key.encode('utf8'))),
|
|
|
|
'--plugin', ua,
|
2021-10-31 21:41:21 +03:00
|
|
|
]
|
2019-05-10 19:43:30 +03:00
|
|
|
if self.debug:
|
|
|
|
cmd.append('--verbose')
|
|
|
|
if self.proxy:
|
|
|
|
cmd.extend(['--proxy', self.proxy])
|
|
|
|
|
|
|
|
log(DEBUG, ' '.join(obfuscate_apikey(cmd)))
|
2019-05-01 20:48:28 +03:00
|
|
|
try:
|
2019-05-10 19:43:30 +03:00
|
|
|
process = Popen(cmd, stdout=PIPE, stderr=STDOUT)
|
2020-12-29 05:42:00 +03:00
|
|
|
output, err = process.communicate()
|
|
|
|
output = u(output)
|
2021-10-31 01:18:26 +03:00
|
|
|
if output:
|
|
|
|
output = output.strip()
|
2019-05-10 19:43:30 +03:00
|
|
|
retcode = process.poll()
|
|
|
|
if not retcode and output:
|
2020-12-29 05:42:00 +03:00
|
|
|
msg = 'Today: {output}'.format(output=output)
|
2019-05-01 20:48:28 +03:00
|
|
|
update_status_bar(msg=msg)
|
2019-05-10 19:43:30 +03:00
|
|
|
else:
|
|
|
|
log(DEBUG, 'wakatime-core today exited with status: {0}'.format(retcode))
|
|
|
|
if output:
|
2020-12-29 05:42:00 +03:00
|
|
|
log(DEBUG, u('wakatime-core today output: {0}').format(output))
|
2019-05-01 20:48:28 +03:00
|
|
|
except:
|
|
|
|
pass
|
2015-10-02 22:09:37 +03:00
|
|
|
|
|
|
|
|
2013-08-14 13:36:17 +04:00
|
|
|
def prompt_api_key():
|
2019-05-29 16:42:38 +03:00
|
|
|
if APIKEY.read():
|
2017-03-16 18:36:17 +03:00
|
|
|
return True
|
2014-12-24 21:01:56 +03:00
|
|
|
|
2017-03-16 18:36:17 +03:00
|
|
|
window = sublime.active_window()
|
|
|
|
if window:
|
2013-08-05 09:11:22 +04:00
|
|
|
def got_key(text):
|
|
|
|
if text:
|
2019-05-29 16:42:38 +03:00
|
|
|
APIKEY.write(text)
|
2019-05-27 22:39:48 +03:00
|
|
|
window.show_input_panel('[WakaTime] Enter your wakatime.com api key:', '', got_key, None, None)
|
2017-03-16 18:36:17 +03:00
|
|
|
return True
|
|
|
|
else:
|
|
|
|
log(ERROR, 'Could not prompt for api key because no window found.')
|
|
|
|
return False
|
2013-07-10 11:14:44 +04:00
|
|
|
|
2013-08-09 05:52:45 +04:00
|
|
|
|
2015-04-03 01:04:05 +03:00
|
|
|
def obfuscate_apikey(command_list):
|
|
|
|
cmd = list(command_list)
|
2015-04-01 23:01:10 +03:00
|
|
|
apikey_index = None
|
|
|
|
for num in range(len(cmd)):
|
|
|
|
if cmd[num] == '--key':
|
|
|
|
apikey_index = num + 1
|
|
|
|
break
|
|
|
|
if apikey_index is not None and apikey_index < len(cmd):
|
2015-10-01 21:24:13 +03:00
|
|
|
cmd[apikey_index] = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX' + cmd[apikey_index][-4:]
|
2015-04-01 23:01:10 +03:00
|
|
|
return cmd
|
|
|
|
|
|
|
|
|
2016-04-29 01:18:38 +03:00
|
|
|
def enough_time_passed(now, is_write):
|
|
|
|
if now - LAST_HEARTBEAT['time'] > HEARTBEAT_FREQUENCY * 60:
|
2013-07-10 11:14:44 +04:00
|
|
|
return True
|
2016-04-29 01:18:38 +03:00
|
|
|
if is_write and now - LAST_HEARTBEAT['time'] > 2:
|
2015-05-06 22:22:42 +03:00
|
|
|
return True
|
2013-07-10 11:14:44 +04:00
|
|
|
return False
|
|
|
|
|
|
|
|
|
2015-04-03 02:41:55 +03:00
|
|
|
def find_folder_containing_file(folders, current_file):
|
|
|
|
"""Returns absolute path to folder containing the file.
|
|
|
|
"""
|
|
|
|
|
|
|
|
parent_folder = None
|
|
|
|
|
|
|
|
current_folder = current_file
|
|
|
|
while True:
|
2015-02-06 04:40:45 +03:00
|
|
|
for folder in folders:
|
2015-04-03 02:41:55 +03:00
|
|
|
if os.path.realpath(os.path.dirname(current_folder)) == os.path.realpath(folder):
|
|
|
|
parent_folder = folder
|
|
|
|
break
|
|
|
|
if parent_folder is not None:
|
|
|
|
break
|
|
|
|
if not current_folder or os.path.dirname(current_folder) == current_folder:
|
|
|
|
break
|
|
|
|
current_folder = os.path.dirname(current_folder)
|
|
|
|
|
|
|
|
return parent_folder
|
|
|
|
|
|
|
|
|
|
|
|
def find_project_from_folders(folders, current_file):
|
|
|
|
"""Find project name from open folders.
|
|
|
|
"""
|
|
|
|
|
|
|
|
folder = find_folder_containing_file(folders, current_file)
|
2015-04-08 00:20:21 +03:00
|
|
|
return os.path.basename(folder) if folder else None
|
2014-06-18 21:35:59 +04:00
|
|
|
|
|
|
|
|
2015-05-07 00:06:06 +03:00
|
|
|
def is_view_active(view):
|
|
|
|
if view:
|
|
|
|
active_window = sublime.active_window()
|
|
|
|
if active_window:
|
|
|
|
active_view = active_window.active_view()
|
|
|
|
if active_view:
|
|
|
|
return active_view.buffer_id() == view.buffer_id()
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
2016-04-30 01:01:25 +03:00
|
|
|
def handle_activity(view, is_write=False):
|
2015-03-25 21:08:27 +03:00
|
|
|
window = view.window()
|
|
|
|
if window is not None:
|
2016-04-29 01:18:38 +03:00
|
|
|
entity = view.file_name()
|
|
|
|
if entity:
|
|
|
|
timestamp = time.time()
|
|
|
|
last_file = LAST_HEARTBEAT['file']
|
|
|
|
if entity != last_file or enough_time_passed(timestamp, is_write):
|
|
|
|
project = window.project_data() if hasattr(window, 'project_data') else None
|
|
|
|
folders = window.folders()
|
|
|
|
append_heartbeat(entity, timestamp, is_write, view, project, folders)
|
|
|
|
|
|
|
|
|
|
|
|
def append_heartbeat(entity, timestamp, is_write, view, project, folders):
|
|
|
|
global LAST_HEARTBEAT
|
|
|
|
|
|
|
|
# add this heartbeat to queue
|
|
|
|
heartbeat = {
|
|
|
|
'entity': entity,
|
|
|
|
'timestamp': timestamp,
|
|
|
|
'is_write': is_write,
|
|
|
|
'project': project,
|
|
|
|
'folders': folders,
|
2022-01-07 05:37:52 +03:00
|
|
|
'lines_in_file': view.rowcol(view.size())[0] + 1,
|
2016-04-29 01:18:38 +03:00
|
|
|
}
|
2022-01-07 05:37:52 +03:00
|
|
|
selections = view.sel()
|
2022-08-23 16:13:44 +03:00
|
|
|
if selections and len(selections) > 0:
|
2022-01-07 05:37:52 +03:00
|
|
|
rowcol = view.rowcol(selections[0].begin())
|
|
|
|
row, col = rowcol[0] + 1, rowcol[1] + 1
|
|
|
|
heartbeat['lineno'] = row
|
|
|
|
heartbeat['cursorpos'] = col
|
2016-04-29 01:18:38 +03:00
|
|
|
HEARTBEATS.put_nowait(heartbeat)
|
|
|
|
|
|
|
|
# make this heartbeat the LAST_HEARTBEAT
|
|
|
|
LAST_HEARTBEAT = {
|
|
|
|
'file': entity,
|
|
|
|
'time': timestamp,
|
|
|
|
'is_write': is_write,
|
|
|
|
}
|
|
|
|
|
|
|
|
# process the queue of heartbeats in the future
|
2018-10-07 06:40:12 +03:00
|
|
|
set_timeout(lambda: process_queue(timestamp), SEND_BUFFER_SECONDS)
|
2016-04-29 01:18:38 +03:00
|
|
|
|
|
|
|
|
2018-10-07 06:40:12 +03:00
|
|
|
def process_queue(timestamp):
|
|
|
|
global LAST_HEARTBEAT_SENT_AT
|
|
|
|
|
2020-03-01 21:01:52 +03:00
|
|
|
if not isCliInstalled():
|
|
|
|
return
|
|
|
|
|
2018-10-07 06:40:12 +03:00
|
|
|
# Prevent sending heartbeats more often than SEND_BUFFER_SECONDS
|
|
|
|
now = int(time.time())
|
2020-03-01 21:01:52 +03:00
|
|
|
if timestamp != LAST_HEARTBEAT['time'] and LAST_HEARTBEAT_SENT_AT > now - SEND_BUFFER_SECONDS:
|
2018-10-07 06:40:12 +03:00
|
|
|
return
|
|
|
|
LAST_HEARTBEAT_SENT_AT = now
|
|
|
|
|
2016-04-29 01:18:38 +03:00
|
|
|
try:
|
|
|
|
heartbeat = HEARTBEATS.get_nowait()
|
|
|
|
except queue.Empty:
|
|
|
|
return
|
2013-08-08 13:17:47 +04:00
|
|
|
|
2016-04-29 01:18:38 +03:00
|
|
|
has_extra_heartbeats = False
|
|
|
|
extra_heartbeats = []
|
|
|
|
try:
|
|
|
|
while True:
|
|
|
|
extra_heartbeats.append(HEARTBEATS.get_nowait())
|
|
|
|
has_extra_heartbeats = True
|
|
|
|
except queue.Empty:
|
|
|
|
pass
|
|
|
|
|
|
|
|
thread = SendHeartbeatsThread(heartbeat)
|
|
|
|
if has_extra_heartbeats:
|
|
|
|
thread.add_extra_heartbeats(extra_heartbeats)
|
|
|
|
thread.start()
|
2013-08-08 13:17:47 +04:00
|
|
|
|
2016-04-29 01:18:38 +03:00
|
|
|
|
|
|
|
class SendHeartbeatsThread(threading.Thread):
|
2015-10-01 22:39:28 +03:00
|
|
|
"""Non-blocking thread for sending heartbeats to api.
|
|
|
|
"""
|
2013-08-08 13:17:47 +04:00
|
|
|
|
2016-04-29 01:18:38 +03:00
|
|
|
def __init__(self, heartbeat):
|
2013-08-08 13:17:47 +04:00
|
|
|
threading.Thread.__init__(self)
|
2016-04-29 01:18:38 +03:00
|
|
|
|
2013-08-14 12:49:08 +04:00
|
|
|
self.debug = SETTINGS.get('debug')
|
2019-05-29 16:42:38 +03:00
|
|
|
self.api_key = APIKEY.read() or ''
|
2013-10-28 08:30:10 +04:00
|
|
|
self.ignore = SETTINGS.get('ignore', [])
|
2017-09-14 17:39:28 +03:00
|
|
|
self.include = SETTINGS.get('include', [])
|
2017-03-04 19:21:21 +03:00
|
|
|
self.hidefilenames = SETTINGS.get('hidefilenames')
|
2017-03-10 19:11:40 +03:00
|
|
|
self.proxy = SETTINGS.get('proxy')
|
2016-04-29 01:18:38 +03:00
|
|
|
|
|
|
|
self.heartbeat = heartbeat
|
|
|
|
self.has_extra_heartbeats = False
|
|
|
|
|
|
|
|
def add_extra_heartbeats(self, extra_heartbeats):
|
|
|
|
self.has_extra_heartbeats = True
|
|
|
|
self.extra_heartbeats = extra_heartbeats
|
2013-08-08 13:17:47 +04:00
|
|
|
|
|
|
|
def run(self):
|
2016-04-29 01:18:38 +03:00
|
|
|
"""Running in background thread."""
|
|
|
|
|
|
|
|
self.send_heartbeats()
|
|
|
|
|
|
|
|
def build_heartbeat(self, entity=None, timestamp=None, is_write=None,
|
2022-01-07 05:37:52 +03:00
|
|
|
lineno=None, cursorpos=None, lines_in_file=None,
|
|
|
|
project=None, folders=None):
|
2016-04-29 01:18:38 +03:00
|
|
|
"""Returns a dict for passing to wakatime-cli as arguments."""
|
|
|
|
|
|
|
|
heartbeat = {
|
|
|
|
'entity': entity,
|
|
|
|
'timestamp': timestamp,
|
|
|
|
'is_write': is_write,
|
|
|
|
}
|
|
|
|
|
|
|
|
if project and project.get('name'):
|
|
|
|
heartbeat['alternate_project'] = project.get('name')
|
|
|
|
elif folders:
|
|
|
|
project_name = find_project_from_folders(folders, entity)
|
2014-06-18 21:35:59 +04:00
|
|
|
if project_name:
|
2016-04-29 01:18:38 +03:00
|
|
|
heartbeat['alternate_project'] = project_name
|
|
|
|
|
2022-01-07 05:37:52 +03:00
|
|
|
if lineno is not None:
|
|
|
|
heartbeat['lineno'] = lineno
|
2016-04-29 01:18:38 +03:00
|
|
|
if cursorpos is not None:
|
2021-11-18 00:52:49 +03:00
|
|
|
heartbeat['cursorpos'] = cursorpos
|
2022-01-07 05:37:52 +03:00
|
|
|
if lines_in_file is not None:
|
|
|
|
heartbeat['lines-in-file'] = lines_in_file
|
2016-04-29 01:18:38 +03:00
|
|
|
|
|
|
|
return heartbeat
|
|
|
|
|
|
|
|
def send_heartbeats(self):
|
2021-10-31 21:41:21 +03:00
|
|
|
heartbeat = self.build_heartbeat(**self.heartbeat)
|
|
|
|
ua = 'sublime/%d sublime-wakatime/%s' % (ST_VERSION, __version__)
|
|
|
|
cmd = [
|
|
|
|
getCliLocation(),
|
|
|
|
'--entity', heartbeat['entity'],
|
|
|
|
'--time', str('%f' % heartbeat['timestamp']),
|
|
|
|
'--plugin', ua,
|
|
|
|
]
|
|
|
|
if self.api_key:
|
|
|
|
cmd.extend(['--key', str(bytes.decode(self.api_key.encode('utf8')))])
|
|
|
|
if heartbeat['is_write']:
|
|
|
|
cmd.append('--write')
|
|
|
|
if heartbeat.get('alternate_project'):
|
|
|
|
cmd.extend(['--alternate-project', heartbeat['alternate_project']])
|
2022-01-07 05:37:52 +03:00
|
|
|
if heartbeat.get('lineno') is not None:
|
|
|
|
cmd.extend(['--lineno', '{0}'.format(heartbeat['lineno'])])
|
2021-10-31 21:41:21 +03:00
|
|
|
if heartbeat.get('cursorpos') is not None:
|
2021-11-18 00:52:49 +03:00
|
|
|
cmd.extend(['--cursorpos', '{0}'.format(heartbeat['cursorpos'])])
|
2022-01-07 05:37:52 +03:00
|
|
|
if heartbeat.get('lines_in_file') is not None:
|
|
|
|
cmd.extend(['--lines-in-file', '{0}'.format(heartbeat['lines_in_file'])])
|
2021-10-31 21:41:21 +03:00
|
|
|
for pattern in self.ignore:
|
|
|
|
cmd.extend(['--exclude', pattern])
|
|
|
|
for pattern in self.include:
|
|
|
|
cmd.extend(['--include', pattern])
|
|
|
|
if self.debug:
|
|
|
|
cmd.append('--verbose')
|
|
|
|
if self.hidefilenames:
|
|
|
|
cmd.append('--hidefilenames')
|
|
|
|
if self.proxy:
|
|
|
|
cmd.extend(['--proxy', self.proxy])
|
|
|
|
if self.has_extra_heartbeats:
|
|
|
|
cmd.append('--extra-heartbeats')
|
|
|
|
stdin = PIPE
|
|
|
|
extra_heartbeats = json.dumps([self.build_heartbeat(**x) for x in self.extra_heartbeats])
|
|
|
|
inp = "{0}\n".format(extra_heartbeats).encode('utf-8')
|
2020-03-01 03:15:40 +03:00
|
|
|
else:
|
2021-10-31 21:41:21 +03:00
|
|
|
extra_heartbeats = None
|
|
|
|
stdin = None
|
|
|
|
inp = None
|
2016-04-29 01:18:38 +03:00
|
|
|
|
2021-10-31 21:41:21 +03:00
|
|
|
log(DEBUG, ' '.join(obfuscate_apikey(cmd)))
|
|
|
|
try:
|
|
|
|
process = Popen(cmd, stdin=stdin, stdout=PIPE, stderr=STDOUT)
|
|
|
|
output, _err = process.communicate(input=inp)
|
|
|
|
retcode = process.poll()
|
|
|
|
if (not retcode or retcode == 102) and not output:
|
|
|
|
self.sent()
|
2020-03-01 03:15:40 +03:00
|
|
|
else:
|
2016-04-29 01:18:38 +03:00
|
|
|
update_status_bar('Error')
|
2021-10-31 21:41:21 +03:00
|
|
|
if retcode:
|
|
|
|
log(DEBUG if retcode == 102 else ERROR, 'wakatime-core exited with status: {0}'.format(retcode))
|
|
|
|
if output:
|
|
|
|
log(ERROR, u('wakatime-core output: {0}').format(output))
|
|
|
|
except:
|
|
|
|
log(ERROR, u(sys.exc_info()[1]))
|
|
|
|
update_status_bar('Error')
|
2013-08-08 13:17:47 +04:00
|
|
|
|
2015-03-20 11:14:53 +03:00
|
|
|
def sent(self):
|
2016-04-29 01:18:38 +03:00
|
|
|
update_status_bar('OK')
|
2015-03-20 11:14:53 +03:00
|
|
|
|
2016-04-29 01:18:38 +03:00
|
|
|
|
2013-08-08 13:17:47 +04:00
|
|
|
def plugin_loaded():
|
2013-10-28 08:30:10 +04:00
|
|
|
global SETTINGS
|
2015-10-02 22:09:37 +03:00
|
|
|
SETTINGS = sublime.load_settings(SETTINGS_FILE)
|
2014-10-14 22:02:52 +04:00
|
|
|
|
2016-04-29 01:18:38 +03:00
|
|
|
log(INFO, 'Initializing WakaTime plugin v%s' % __version__)
|
2019-05-01 20:48:28 +03:00
|
|
|
update_status_bar('Initializing...')
|
2016-04-29 01:18:38 +03:00
|
|
|
|
2022-06-25 19:45:29 +03:00
|
|
|
UpdateCLI().start()
|
2014-10-14 22:02:52 +04:00
|
|
|
|
2013-08-14 13:36:17 +04:00
|
|
|
after_loaded()
|
|
|
|
|
|
|
|
|
|
|
|
def after_loaded():
|
|
|
|
if not prompt_api_key():
|
2016-04-29 01:18:38 +03:00
|
|
|
set_timeout(after_loaded, 0.5)
|
2019-05-01 20:48:28 +03:00
|
|
|
update_status_bar('OK')
|
2013-08-08 13:17:47 +04:00
|
|
|
|
|
|
|
|
|
|
|
# need to call plugin_loaded because only ST3 will auto-call it
|
|
|
|
if ST_VERSION < 3000:
|
|
|
|
plugin_loaded()
|
2013-07-02 13:21:13 +04:00
|
|
|
|
|
|
|
|
|
|
|
class WakatimeListener(sublime_plugin.EventListener):
|
|
|
|
|
|
|
|
def on_post_save(self, view):
|
2016-04-30 01:01:25 +03:00
|
|
|
handle_activity(view, is_write=True)
|
2013-07-02 13:21:13 +04:00
|
|
|
|
2015-04-13 02:45:16 +03:00
|
|
|
def on_selection_modified(self, view):
|
2015-05-07 00:06:06 +03:00
|
|
|
if is_view_active(view):
|
2016-04-30 01:01:25 +03:00
|
|
|
handle_activity(view)
|
2013-07-08 05:38:01 +04:00
|
|
|
|
2013-07-16 15:02:30 +04:00
|
|
|
def on_modified(self, view):
|
2015-05-07 00:06:06 +03:00
|
|
|
if is_view_active(view):
|
2016-04-30 01:01:25 +03:00
|
|
|
handle_activity(view)
|
2015-02-24 01:59:10 +03:00
|
|
|
|
|
|
|
|
|
|
|
class WakatimeDashboardCommand(sublime_plugin.ApplicationCommand):
|
2015-02-24 09:20:27 +03:00
|
|
|
|
2015-02-24 01:59:10 +03:00
|
|
|
def run(self):
|
|
|
|
webbrowser.open_new_tab('https://wakatime.com/dashboard')
|
2020-03-01 03:15:40 +03:00
|
|
|
|
|
|
|
|
2022-06-25 19:45:29 +03:00
|
|
|
class UpdateCLI(threading.Thread):
|
2020-03-01 03:15:40 +03:00
|
|
|
"""Non-blocking thread for downloading latest wakatime-cli from GitHub.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def run(self):
|
2022-06-25 19:45:29 +03:00
|
|
|
if isCliLatest():
|
|
|
|
return
|
|
|
|
|
2020-03-01 03:15:40 +03:00
|
|
|
log(INFO, 'Downloading wakatime-cli...')
|
|
|
|
|
2022-02-22 07:08:48 +03:00
|
|
|
if os.path.isdir(os.path.join(RESOURCES_FOLDER, 'wakatime-cli')):
|
|
|
|
shutil.rmtree(os.path.join(RESOURCES_FOLDER, 'wakatime-cli'))
|
|
|
|
|
2020-12-29 05:42:00 +03:00
|
|
|
if not os.path.exists(RESOURCES_FOLDER):
|
|
|
|
os.makedirs(RESOURCES_FOLDER)
|
|
|
|
|
2020-03-01 03:15:40 +03:00
|
|
|
try:
|
2021-10-31 21:41:21 +03:00
|
|
|
url = cliDownloadUrl()
|
2021-10-31 22:57:28 +03:00
|
|
|
log(DEBUG, 'Downloading wakatime-cli from {url}'.format(url=url))
|
2020-03-01 03:15:40 +03:00
|
|
|
zip_file = os.path.join(RESOURCES_FOLDER, 'wakatime-cli.zip')
|
|
|
|
download(url, zip_file)
|
|
|
|
|
2022-01-01 03:42:11 +03:00
|
|
|
if isCliInstalled():
|
|
|
|
try:
|
|
|
|
os.remove(getCliLocation())
|
|
|
|
except:
|
|
|
|
log(DEBUG, traceback.format_exc())
|
|
|
|
|
2020-03-01 03:15:40 +03:00
|
|
|
log(INFO, 'Extracting wakatime-cli...')
|
|
|
|
with ZipFile(zip_file) as zf:
|
|
|
|
zf.extractall(RESOURCES_FOLDER)
|
|
|
|
|
2021-10-31 22:57:28 +03:00
|
|
|
if not is_win:
|
|
|
|
os.chmod(getCliLocation(), 509) # 755
|
|
|
|
|
2020-03-01 03:15:40 +03:00
|
|
|
try:
|
2021-10-31 22:57:28 +03:00
|
|
|
os.remove(os.path.join(RESOURCES_FOLDER, 'wakatime-cli.zip'))
|
2020-03-01 03:15:40 +03:00
|
|
|
except:
|
2021-10-31 22:57:28 +03:00
|
|
|
log(DEBUG, traceback.format_exc())
|
2020-03-01 03:15:40 +03:00
|
|
|
except:
|
|
|
|
log(DEBUG, traceback.format_exc())
|
|
|
|
|
2022-01-06 21:23:09 +03:00
|
|
|
createSymlink()
|
|
|
|
|
2020-03-01 03:15:40 +03:00
|
|
|
log(INFO, 'Finished extracting wakatime-cli.')
|
|
|
|
|
2021-10-31 21:41:21 +03:00
|
|
|
|
|
|
|
def getCliLocation():
|
|
|
|
global WAKATIME_CLI_LOCATION
|
|
|
|
|
|
|
|
if not WAKATIME_CLI_LOCATION:
|
|
|
|
binary = 'wakatime-cli-{osname}-{arch}{ext}'.format(
|
|
|
|
osname=platform.system().lower(),
|
|
|
|
arch=architecture(),
|
|
|
|
ext='.exe' if is_win else '',
|
2020-03-01 03:15:40 +03:00
|
|
|
)
|
2021-10-31 21:41:21 +03:00
|
|
|
WAKATIME_CLI_LOCATION = os.path.join(RESOURCES_FOLDER, binary)
|
|
|
|
|
|
|
|
return WAKATIME_CLI_LOCATION
|
|
|
|
|
|
|
|
|
|
|
|
def architecture():
|
|
|
|
arch = platform.machine() or platform.processor()
|
|
|
|
if arch == 'armv7l':
|
|
|
|
return 'arm'
|
|
|
|
if arch == 'aarch64':
|
|
|
|
return 'arm64'
|
|
|
|
if 'arm' in arch:
|
|
|
|
return 'arm64' if sys.maxsize > 2**32 else 'arm'
|
|
|
|
return 'amd64' if sys.maxsize > 2**32 else '386'
|
2020-03-01 03:15:40 +03:00
|
|
|
|
|
|
|
|
|
|
|
def isCliInstalled():
|
2021-10-31 21:41:21 +03:00
|
|
|
return os.path.exists(getCliLocation())
|
2020-03-01 03:15:40 +03:00
|
|
|
|
2020-03-01 21:01:52 +03:00
|
|
|
|
2020-03-01 03:15:40 +03:00
|
|
|
def isCliLatest():
|
|
|
|
if not isCliInstalled():
|
|
|
|
return False
|
2020-03-01 21:01:52 +03:00
|
|
|
|
2021-10-31 21:41:21 +03:00
|
|
|
args = [getCliLocation(), '--version']
|
2021-10-31 22:57:28 +03:00
|
|
|
try:
|
|
|
|
stdout, stderr = Popen(args, stdout=PIPE, stderr=PIPE).communicate()
|
|
|
|
except:
|
|
|
|
return False
|
2020-03-01 03:15:40 +03:00
|
|
|
stdout = (stdout or b'') + (stderr or b'')
|
|
|
|
localVer = extractVersion(stdout.decode('utf-8'))
|
|
|
|
if not localVer:
|
2021-10-31 22:57:28 +03:00
|
|
|
log(DEBUG, 'Local wakatime-cli version not found.')
|
2020-03-01 03:15:40 +03:00
|
|
|
return False
|
|
|
|
|
|
|
|
log(INFO, 'Current wakatime-cli version is %s' % localVer)
|
|
|
|
log(INFO, 'Checking for updates to wakatime-cli...')
|
|
|
|
|
2020-03-01 21:01:52 +03:00
|
|
|
remoteVer = getLatestCliVersion()
|
2020-03-01 03:15:40 +03:00
|
|
|
|
|
|
|
if not remoteVer:
|
|
|
|
return True
|
|
|
|
|
|
|
|
if remoteVer == localVer:
|
|
|
|
log(INFO, 'wakatime-cli is up to date.')
|
|
|
|
return True
|
|
|
|
|
2021-10-31 22:57:28 +03:00
|
|
|
log(INFO, 'Found an updated wakatime-cli %s' % remoteVer)
|
2020-03-01 03:15:40 +03:00
|
|
|
return False
|
|
|
|
|
2020-03-01 21:01:52 +03:00
|
|
|
|
2020-03-01 03:15:40 +03:00
|
|
|
def getLatestCliVersion():
|
2021-10-31 21:41:21 +03:00
|
|
|
global LATEST_CLI_VERSION
|
|
|
|
|
|
|
|
if LATEST_CLI_VERSION:
|
|
|
|
return LATEST_CLI_VERSION
|
|
|
|
|
2021-10-31 22:57:28 +03:00
|
|
|
configs, last_modified, last_version = None, None, None
|
2020-03-01 03:15:40 +03:00
|
|
|
try:
|
2021-10-31 21:41:21 +03:00
|
|
|
configs = parseConfigFile(INTERNAL_CONFIG_FILE)
|
|
|
|
if configs:
|
2022-01-05 15:15:10 +03:00
|
|
|
last_modified, last_version = lastModifiedAndVersion(configs)
|
2020-03-01 03:15:40 +03:00
|
|
|
except:
|
2021-10-31 22:57:28 +03:00
|
|
|
log(DEBUG, traceback.format_exc())
|
2020-03-01 03:15:40 +03:00
|
|
|
|
2021-10-31 21:41:21 +03:00
|
|
|
try:
|
2021-10-31 22:57:28 +03:00
|
|
|
headers, contents, code = request(GITHUB_RELEASES_STABLE_URL, last_modified=last_modified)
|
2020-03-01 21:01:52 +03:00
|
|
|
|
2021-10-31 21:41:21 +03:00
|
|
|
log(DEBUG, 'GitHub API Response {0}'.format(code))
|
|
|
|
|
|
|
|
if code == 304:
|
|
|
|
LATEST_CLI_VERSION = last_version
|
|
|
|
return last_version
|
|
|
|
|
2021-10-31 22:57:28 +03:00
|
|
|
data = json.loads(contents.decode('utf-8'))
|
2021-10-31 21:41:21 +03:00
|
|
|
|
|
|
|
ver = data['tag_name']
|
|
|
|
log(DEBUG, 'Latest wakatime-cli version from GitHub: {0}'.format(ver))
|
|
|
|
|
2021-10-31 22:57:28 +03:00
|
|
|
if configs:
|
|
|
|
last_modified = headers.get('Last-Modified')
|
|
|
|
if not configs.has_section('internal'):
|
|
|
|
configs.add_section('internal')
|
|
|
|
configs.set('internal', 'cli_version', ver)
|
|
|
|
configs.set('internal', 'cli_version_last_modified', last_modified)
|
|
|
|
with open(INTERNAL_CONFIG_FILE, 'w', encoding='utf-8') as fh:
|
|
|
|
configs.write(fh)
|
2021-10-31 21:41:21 +03:00
|
|
|
|
|
|
|
LATEST_CLI_VERSION = ver
|
|
|
|
return ver
|
|
|
|
except:
|
2021-10-31 22:57:28 +03:00
|
|
|
log(DEBUG, traceback.format_exc())
|
2021-10-31 21:41:21 +03:00
|
|
|
return None
|
2020-03-01 03:15:40 +03:00
|
|
|
|
2020-03-01 21:01:52 +03:00
|
|
|
|
2022-01-05 15:15:10 +03:00
|
|
|
def lastModifiedAndVersion(configs):
|
|
|
|
last_modified, last_version = None, None
|
|
|
|
if configs.has_option('internal', 'cli_version'):
|
|
|
|
last_version = configs.get('internal', 'cli_version')
|
|
|
|
if last_version and configs.has_option('internal', 'cli_version_last_modified'):
|
|
|
|
last_modified = configs.get('internal', 'cli_version_last_modified')
|
|
|
|
if last_modified and last_version and extractVersion(last_version):
|
|
|
|
return last_modified, last_version
|
|
|
|
return None, None
|
|
|
|
|
|
|
|
|
2020-03-01 03:15:40 +03:00
|
|
|
def extractVersion(text):
|
|
|
|
pattern = re.compile(r"([0-9]+\.[0-9]+\.[0-9]+)")
|
|
|
|
match = pattern.search(text)
|
|
|
|
if match:
|
2021-10-31 22:57:28 +03:00
|
|
|
return 'v{ver}'.format(ver=match.group(1))
|
2020-03-01 03:15:40 +03:00
|
|
|
return None
|
|
|
|
|
2020-03-01 21:01:52 +03:00
|
|
|
|
2021-10-31 21:41:21 +03:00
|
|
|
def cliDownloadUrl():
|
|
|
|
osname = platform.system().lower()
|
|
|
|
arch = architecture()
|
|
|
|
|
|
|
|
validCombinations = [
|
|
|
|
'darwin-amd64',
|
|
|
|
'darwin-arm64',
|
|
|
|
'freebsd-386',
|
|
|
|
'freebsd-amd64',
|
|
|
|
'freebsd-arm',
|
|
|
|
'linux-386',
|
|
|
|
'linux-amd64',
|
|
|
|
'linux-arm',
|
|
|
|
'linux-arm64',
|
|
|
|
'netbsd-386',
|
|
|
|
'netbsd-amd64',
|
|
|
|
'netbsd-arm',
|
|
|
|
'openbsd-386',
|
|
|
|
'openbsd-amd64',
|
|
|
|
'openbsd-arm',
|
|
|
|
'openbsd-arm64',
|
|
|
|
'windows-386',
|
|
|
|
'windows-amd64',
|
|
|
|
'windows-arm64',
|
|
|
|
]
|
|
|
|
check = '{osname}-{arch}'.format(osname=osname, arch=arch)
|
|
|
|
if check not in validCombinations:
|
|
|
|
reportMissingPlatformSupport(osname, arch)
|
|
|
|
|
|
|
|
version = getLatestCliVersion()
|
|
|
|
|
|
|
|
return '{prefix}/{version}/wakatime-cli-{osname}-{arch}.zip'.format(
|
|
|
|
prefix=GITHUB_DOWNLOAD_PREFIX,
|
|
|
|
version=version,
|
|
|
|
osname=osname,
|
|
|
|
arch=arch,
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
def reportMissingPlatformSupport(osname, arch):
|
|
|
|
url = 'https://api.wakatime.com/api/v1/cli-missing?osname={osname}&architecture={arch}&plugin=sublime'.format(
|
|
|
|
osname=osname,
|
|
|
|
arch=arch,
|
|
|
|
)
|
|
|
|
request(url)
|
|
|
|
|
|
|
|
|
|
|
|
def request(url, last_modified=None):
|
2022-04-29 21:14:55 +03:00
|
|
|
req = Request(url)
|
|
|
|
req.add_header('User-Agent', 'github.com/wakatime/sublime-wakatime')
|
|
|
|
|
2021-10-31 21:41:21 +03:00
|
|
|
proxy = SETTINGS.get('proxy')
|
|
|
|
if proxy:
|
2022-04-29 21:14:55 +03:00
|
|
|
req.set_proxy(proxy, 'https')
|
2021-10-31 21:41:21 +03:00
|
|
|
|
|
|
|
if last_modified:
|
2022-04-29 21:14:55 +03:00
|
|
|
req.add_header('If-Modified-Since', last_modified)
|
2021-10-31 21:41:21 +03:00
|
|
|
|
|
|
|
try:
|
2022-04-29 21:14:55 +03:00
|
|
|
resp = urlopen(req)
|
2021-10-31 22:57:28 +03:00
|
|
|
headers = dict(resp.getheaders()) if is_py2 else resp.headers
|
|
|
|
return headers, resp.read(), resp.getcode()
|
|
|
|
except HTTPError as err:
|
|
|
|
if err.code == 304:
|
|
|
|
return None, None, 304
|
2021-11-02 03:18:06 +03:00
|
|
|
if is_py2:
|
2022-04-29 21:14:55 +03:00
|
|
|
with SSLCertVerificationDisabled():
|
|
|
|
try:
|
|
|
|
resp = urlopen(req)
|
|
|
|
headers = dict(resp.getheaders()) if is_py2 else resp.headers
|
|
|
|
return headers, resp.read(), resp.getcode()
|
|
|
|
except HTTPError as err2:
|
|
|
|
if err2.code == 304:
|
|
|
|
return None, None, 304
|
|
|
|
log(DEBUG, err.read().decode())
|
|
|
|
log(DEBUG, err2.read().decode())
|
|
|
|
raise
|
|
|
|
except IOError:
|
|
|
|
raise
|
2021-11-02 03:27:12 +03:00
|
|
|
log(DEBUG, err.read().decode())
|
2021-10-31 22:57:28 +03:00
|
|
|
raise
|
2021-10-31 21:41:21 +03:00
|
|
|
except IOError:
|
2021-10-31 22:57:28 +03:00
|
|
|
if is_py2:
|
2022-04-29 21:14:55 +03:00
|
|
|
with SSLCertVerificationDisabled():
|
|
|
|
try:
|
|
|
|
resp = urlopen(url)
|
|
|
|
headers = dict(resp.getheaders()) if is_py2 else resp.headers
|
|
|
|
return headers, resp.read(), resp.getcode()
|
|
|
|
except HTTPError as err:
|
|
|
|
if err.code == 304:
|
|
|
|
return None, None, 304
|
|
|
|
log(DEBUG, err.read().decode())
|
|
|
|
raise
|
|
|
|
except IOError:
|
|
|
|
raise
|
2021-10-31 22:57:28 +03:00
|
|
|
raise
|
2021-10-31 21:41:21 +03:00
|
|
|
|
|
|
|
|
2020-03-01 03:15:40 +03:00
|
|
|
def download(url, filePath):
|
2022-04-29 21:14:55 +03:00
|
|
|
req = Request(url)
|
|
|
|
req.add_header('User-Agent', 'github.com/wakatime/sublime-wakatime')
|
|
|
|
|
2021-10-31 21:41:21 +03:00
|
|
|
proxy = SETTINGS.get('proxy')
|
|
|
|
if proxy:
|
2022-04-29 21:14:55 +03:00
|
|
|
req.set_proxy(proxy, 'https')
|
2021-10-31 21:41:21 +03:00
|
|
|
|
2022-04-29 21:14:55 +03:00
|
|
|
with open(filePath, 'wb') as fh:
|
|
|
|
try:
|
|
|
|
resp = urlopen(req)
|
|
|
|
fh.write(resp.read())
|
|
|
|
except HTTPError as err:
|
|
|
|
if err.code == 304:
|
|
|
|
return None, None, 304
|
|
|
|
if is_py2:
|
|
|
|
with SSLCertVerificationDisabled():
|
|
|
|
try:
|
|
|
|
resp = urlopen(req)
|
|
|
|
fh.write(resp.read())
|
|
|
|
return
|
|
|
|
except HTTPError as err2:
|
|
|
|
log(DEBUG, err.read().decode())
|
|
|
|
log(DEBUG, err2.read().decode())
|
|
|
|
raise
|
|
|
|
except IOError:
|
|
|
|
raise
|
|
|
|
log(DEBUG, err.read().decode())
|
|
|
|
raise
|
|
|
|
except IOError:
|
|
|
|
if is_py2:
|
|
|
|
with SSLCertVerificationDisabled():
|
|
|
|
try:
|
|
|
|
resp = urlopen(url)
|
|
|
|
fh.write(resp.read())
|
|
|
|
return
|
|
|
|
except HTTPError as err:
|
|
|
|
log(DEBUG, err.read().decode())
|
|
|
|
raise
|
|
|
|
except IOError:
|
|
|
|
raise
|
|
|
|
raise
|
2022-01-06 21:23:09 +03:00
|
|
|
|
|
|
|
|
2022-01-07 05:16:02 +03:00
|
|
|
def is_symlink(path):
|
|
|
|
try:
|
|
|
|
return os.is_symlink(path)
|
|
|
|
except:
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
2022-01-06 21:23:09 +03:00
|
|
|
def createSymlink():
|
2022-01-07 05:16:02 +03:00
|
|
|
link = os.path.join(RESOURCES_FOLDER, 'wakatime-cli')
|
2022-01-06 21:23:09 +03:00
|
|
|
if is_win:
|
2022-01-07 05:16:02 +03:00
|
|
|
link = link + '.exe'
|
|
|
|
elif os.path.exists(link) and is_symlink(link):
|
|
|
|
return # don't re-create symlink on Unix-like platforms
|
|
|
|
|
|
|
|
try:
|
|
|
|
os.symlink(getCliLocation(), link)
|
|
|
|
except:
|
2022-01-06 21:23:09 +03:00
|
|
|
try:
|
|
|
|
shutil.copy2(getCliLocation(), link)
|
2022-01-22 02:12:51 +03:00
|
|
|
if not is_win:
|
|
|
|
os.chmod(link, 509) # 755
|
2022-01-06 21:23:09 +03:00
|
|
|
except:
|
2022-06-08 14:43:01 +03:00
|
|
|
log(WARNING, traceback.format_exc())
|
2022-04-29 21:14:55 +03:00
|
|
|
|
|
|
|
|
|
|
|
class SSLCertVerificationDisabled(object):
|
|
|
|
|
|
|
|
def __enter__(self):
|
|
|
|
self.original_context = ssl._create_default_https_context
|
|
|
|
ssl._create_default_https_context = ssl._create_unverified_context
|
|
|
|
|
|
|
|
def __exit__(self, *args, **kwargs):
|
|
|
|
ssl._create_default_https_context = self.original_context
|