|
| 1 | +"""Codestats |
| 2 | +============ |
| 3 | +
|
| 4 | +Refer `code-stats-vim |
| 5 | +<https://gitlab.com/code-stats/code-stats-vim/-/blob/master/pythonx/codestats.py> |
| 6 | +`_. |
| 7 | +""" |
| 8 | +import json |
| 9 | +import logging |
| 10 | +import threading |
| 11 | +import time |
| 12 | +from datetime import datetime |
| 13 | +from http.client import HTTPException |
| 14 | +from socket import gethostname |
| 15 | +from ssl import CertificateError |
| 16 | +from typing import NoReturn |
| 17 | +from urllib.error import URLError |
| 18 | +from urllib.request import Request, urlopen |
| 19 | + |
| 20 | +logger = logging.getLogger(__name__) |
| 21 | +INTERVAL = 10 # interval at which stats are sent |
| 22 | +SLEEP_INTERVAL = 0.1 # sleep interval for timeslicing |
| 23 | +TIMEOUT = 2 # request timeout value (in seconds) |
| 24 | + |
| 25 | +codestats = None |
| 26 | + |
| 27 | + |
| 28 | +def codestats_hook( |
| 29 | + api_key: str = "", |
| 30 | + url: str = "https://codestats.net/api/my/pulses", |
| 31 | + language_type: str = "Terminal (python)", |
| 32 | + service_name: str = "codestats", |
| 33 | + user_name: str = gethostname(), |
| 34 | +) -> None: |
| 35 | + """Codestats hook. |
| 36 | +
|
| 37 | + :param api_key: |
| 38 | + :type api_key: str |
| 39 | + :param url: |
| 40 | + :type url: str |
| 41 | + :param language_type: |
| 42 | + :type language_type: str |
| 43 | + :param service_name: |
| 44 | + :type service_name: str |
| 45 | + :param user_name: |
| 46 | + :type user_name: str |
| 47 | + :rtype: None |
| 48 | + """ |
| 49 | + global codestats |
| 50 | + if codestats is None: |
| 51 | + if api_key == "": |
| 52 | + from ..utils.api import get_api_key |
| 53 | + |
| 54 | + api_key = get_api_key(service_name, user_name) |
| 55 | + codestats = CodeStats(api_key, url, language_type) |
| 56 | + codestats.add_xp() |
| 57 | + |
| 58 | + |
| 59 | +class CodeStats: |
| 60 | + """Codestats.""" |
| 61 | + |
| 62 | + def __init__( |
| 63 | + self, |
| 64 | + api_key: str, |
| 65 | + url: str = "https://codestats.net/api/my/pulses", |
| 66 | + language_type: str = "Terminal (python)", |
| 67 | + ) -> None: |
| 68 | + """Init. |
| 69 | +
|
| 70 | + :param api_key: |
| 71 | + :type api_key: str |
| 72 | + :param url: |
| 73 | + :type url: str |
| 74 | + :param language_type: |
| 75 | + :type language_type: str |
| 76 | + :rtype: None |
| 77 | + """ |
| 78 | + self.url = url |
| 79 | + self.api_key = api_key |
| 80 | + self.language_type = language_type |
| 81 | + self.xp_dict = {language_type: 0} |
| 82 | + |
| 83 | + self.sem = threading.Semaphore() |
| 84 | + |
| 85 | + self.cs_thread = threading.Thread(target=self.main_thread) |
| 86 | + self.cs_thread.daemon = True |
| 87 | + self.cs_thread.start() |
| 88 | + |
| 89 | + def add_xp(self, xp: int = 1) -> None: |
| 90 | + """Add xp. |
| 91 | +
|
| 92 | + Sem sections are super small so this should be quick if it blocks. |
| 93 | +
|
| 94 | + :param xp: |
| 95 | + :type xp: int |
| 96 | + :rtype: None |
| 97 | + """ |
| 98 | + self.sem.acquire() |
| 99 | + self.xp_dict[self.language_type] += xp |
| 100 | + self.sem.release() |
| 101 | + |
| 102 | + def send_xp(self) -> None: |
| 103 | + """Send xp. |
| 104 | +
|
| 105 | + Acquire the lock to get the list of xp to send. |
| 106 | +
|
| 107 | + :rtype: None |
| 108 | + """ |
| 109 | + if len(self.xp_dict) == 0: |
| 110 | + return |
| 111 | + |
| 112 | + self.sem.acquire() |
| 113 | + xp_list = [dict(language=ft, xp=xp) for ft, xp in self.xp_dict.items()] |
| 114 | + self.xp_dict = {self.language_type: 0} |
| 115 | + self.sem.release() |
| 116 | + |
| 117 | + headers = { |
| 118 | + "Content-Type": "application/json", |
| 119 | + "User-Agent": "code-stats-python/{0}".format(__version__), |
| 120 | + "X-API-Token": self.api_key, |
| 121 | + "Accept": "*/*", |
| 122 | + } |
| 123 | + |
| 124 | + # after lock is released we can send the payload |
| 125 | + utc_now = datetime.now().astimezone().isoformat() |
| 126 | + pulse_json = json.dumps( |
| 127 | + {"coded_at": "{0}".format(utc_now), "xps": xp_list} |
| 128 | + ).encode("utf-8") |
| 129 | + req = Request(url=self.url, data=pulse_json, headers=headers) |
| 130 | + error = "" |
| 131 | + try: |
| 132 | + response = urlopen(req, timeout=TIMEOUT) # nosec: B310 |
| 133 | + response.read() |
| 134 | + # connection might not be closed without .read() |
| 135 | + except URLError as e: |
| 136 | + try: |
| 137 | + # HTTP error |
| 138 | + error = "{0} {1}".format( |
| 139 | + e.code, # type: ignore |
| 140 | + e.read().decode("utf-8"), # type: ignore |
| 141 | + ) |
| 142 | + except AttributeError: |
| 143 | + # non-HTTP error, eg. no network |
| 144 | + error = e.reason |
| 145 | + except CertificateError as e: |
| 146 | + # SSL certificate error (eg. a public wifi redirects traffic) |
| 147 | + error = e |
| 148 | + except HTTPException as e: |
| 149 | + error = "HTTPException on send data. Msg: {0}\nDoc?:{1}".format( |
| 150 | + e.message, e.__doc__ # type: ignore |
| 151 | + ) |
| 152 | + if error: |
| 153 | + logger.error(error) |
| 154 | + |
| 155 | + def main_thread(self) -> NoReturn: |
| 156 | + """Run main thread. |
| 157 | +
|
| 158 | + Needs to be able to send XP at an interval. |
| 159 | + """ |
| 160 | + while True: |
| 161 | + cur_time = 0 |
| 162 | + while cur_time < INTERVAL: |
| 163 | + time.sleep(SLEEP_INTERVAL) |
| 164 | + cur_time += SLEEP_INTERVAL |
| 165 | + |
| 166 | + self.send_xp() |
0 commit comments