### Get User Stats via API (C#) Source: https://docs.ziit.app/api/stats Retrieves aggregated statistics for a specific user using their Bearer API key. This C# example demonstrates how to make the GET request, including setting the Authorization header and query parameters. ```csharp // C# example for fetching user stats // Replace 'YOUR_API_TOKEN' with your actual Bearer token using System; using System.Net.Http; using System.Threading.Tasks; public class UserStatsApiClient { public static async Task Main(string[] args) { string apiToken = "YOUR_API_TOKEN"; string timeRange = "today"; int midnightOffsetSeconds = 0; try { string stats = await GetUserStatsAsync(apiToken, timeRange, midnightOffsetSeconds); if (stats != null) { Console.WriteLine("User Stats: " + stats); } } catch (Exception ex) { Console.Error.WriteLine($"Error: {ex.Message}"); } } public static async Task GetUserStatsAsync(string token, string timeRange, int midnightOffsetSeconds) { using (var httpClient = new HttpClient()) { httpClient.Timeout = TimeSpan.FromSeconds(10); string requestUri = $"https://ziit.app/api/external/stats?timeRange={timeRange}&midnightOffsetSeconds={midnightOffsetSeconds}"; var request = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri(requestUri) }; request.Headers.Add("Authorization", $"Bearer {token}"); HttpResponseMessage response = await httpClient.SendAsync(request); if (!response.IsSuccessStatusCode) { Console.Error.WriteLine($"Request failed with status code: {response.StatusCode}"); string errorBody = await response.Content.ReadAsStringAsync(); Console.Error.WriteLine($"Response body: {errorBody}"); return null; } return await response.Content.ReadAsStringAsync(); } } } ``` -------------------------------- ### Example: Ziit Badge with Custom Style and Icon Source: https://docs.ziit.app/badges An example of a Ziit badge URL demonstrating customization using query parameters. This example sets the style to 'flat' and includes a custom icon URL. Replace ':userId' as needed. ```text https://ziit.app/api/public/badge/cm98il90n0000o52c3my0bf5p?style=flat&icon=https://example.com/icon.svg ``` -------------------------------- ### Get User Stats via API (Go) Source: https://docs.ziit.app/api/stats Retrieves aggregated statistics for a specific user using their Bearer API key. This Go example shows how to construct the request, including the Authorization header and query parameters. ```go // Go example for fetching user stats // Replace 'YOUR_API_TOKEN' with your actual Bearer token package main import ( "fmt" "io/ioutil" "net/http" "net/url" "time" ) func main() { apiToken := "YOUR_API_TOKEN" timeRange := "today" midnightOffsetSeconds := 0 params := url.Values{} params.Add("timeRange", timeRange) params.Add("midnightOffsetSeconds", fmt.Sprintf("%d", midnightOffsetSeconds)) url := "https://ziit.app/api/external/stats?" + params.Encode() client := &http.Client{Timeout: 10 * time.Second} req, err := http.NewRequest("GET", url, nil) if err != nil { fmt.Printf("Error creating request: %s\n", err) return } req.Header.Add("Authorization", "Bearer "+apiToken) resp, err := client.Do(req) if err != nil { fmt.Printf("Error making request: %s\n", err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Printf("Error reading response body: %s\n", err) return } if resp.StatusCode != http.StatusOK { fmt.Printf("Request failed with status code: %d\nBody: %s\n", resp.StatusCode, string(body)) return } fmt.Printf("User Stats: %s\n", string(body)) } ``` -------------------------------- ### Git Integration Example (TypeScript) Source: https://docs.ziit.app/extension-spec-sheet An example demonstrating how to integrate with the IDE's Git extension to retrieve repository information and extract the project name from the remote URL. This is a common pattern for project detection. ```typescript // Example git integration (adapt to your IDE's git API) const gitExtension = ide.extensions.getExtension("git"); const git = gitExtension.getAPI(); const repository = git.getRepository(fileUri); const projectName = extractNameFromRemoteUrl(repository.remotes[0].fetchUrl); ``` -------------------------------- ### Get User Stats via API (Java) Source: https://docs.ziit.app/api/stats Retrieves aggregated statistics for a specific user using their Bearer API key. This Java example illustrates how to perform the GET request, including setting the Authorization header and query parameters. ```java // Java example for fetching user stats // Replace 'YOUR_API_TOKEN' with your actual Bearer token import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; public class UserStatsClient { public static void main(String[] args) { String apiToken = "YOUR_API_TOKEN"; String timeRange = "today"; int midnightOffsetSeconds = 0; try { String responseBody = getUserStats(apiToken, timeRange, midnightOffsetSeconds); if (responseBody != null) { System.out.println("User Stats: " + responseBody); } } catch (IOException | InterruptedException e) { e.printStackTrace(); } } public static String getUserStats(String token, String timeRange, int midnightOffsetSeconds) throws IOException, InterruptedException { HttpClient client = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_2) .connectTimeout(Duration.ofSeconds(10)) .build(); String queryParams = String.format("timeRange=%s&midnightOffsetSeconds=%d", timeRange, midnightOffsetSeconds); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://ziit.app/api/external/stats?" + queryParams)) .header("Authorization", "Bearer " + token) .timeout(Duration.ofSeconds(10)) .GET() .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() != 200) { System.err.println("Request failed with status code: " + response.statusCode()); System.err.println("Response body: " + response.body()); return null; } return response.body(); } } ``` -------------------------------- ### Get User Stats via API (Python) Source: https://docs.ziit.app/api/stats Retrieves aggregated statistics for a specific user using their Bearer API key. This Python example demonstrates making the GET request with the required Authorization header and query parameters. ```python # Python example for fetching user stats # Replace 'YOUR_API_TOKEN' with your actual Bearer token import requests def get_user_stats(token, time_range="today", midnight_offset_seconds=0): url = "https://ziit.app/api/external/stats" headers = { "Authorization": f"Bearer {token}" } params = { "timeRange": time_range, "midnightOffsetSeconds": midnight_offset_seconds } try: response = requests.get(url, headers=headers, params=params) response.raise_for_status() # Raise an exception for bad status codes return response.json() except requests.exceptions.RequestException as e: print(f"Error fetching user stats: {e}") return None # Example usage: # api_token = 'YOUR_API_TOKEN' # stats = get_user_stats(api_token) # if stats: # print("User Stats:", stats) ``` -------------------------------- ### Example: Project-Specific Ziit Badge Source: https://docs.ziit.app/badges An example of a Ziit badge URL to display coding time for a specific project. Replace ':userId' and ':project' with your actual Ziit user ID and project name. ```text https://ziit.app/api/public/badge/cm98il90n0000o52c3my0bf5p/ziit ``` -------------------------------- ### Get User Stats via API (JavaScript) Source: https://docs.ziit.app/api/stats Retrieves aggregated statistics for a specific user using their Bearer API key. This JavaScript example demonstrates how to make the GET request with the necessary Authorization header and query parameters. ```javascript // JavaScript example for fetching user stats // Replace 'YOUR_API_TOKEN' with your actual Bearer token async function getUserStats(token, timeRange = 'today', midnightOffsetSeconds = 0) { const url = `https://ziit.app/api/external/stats?timeRange=${timeRange}&midnightOffsetSeconds=${midnightOffsetSeconds}`; try { const response = await fetch(url, { method: 'GET', headers: { 'Authorization': `Bearer ${token}` } }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); return data; } catch (error) { console.error('Error fetching user stats:', error); return null; } } // Example usage: // const apiToken = 'YOUR_API_TOKEN'; // getUserStats(apiToken).then(stats => { // if (stats) { // console.log('User Stats:', stats); // } // }); ``` -------------------------------- ### Example: Basic Ziit Badge Source: https://docs.ziit.app/badges An example of a basic Ziit badge URL that shows the user's total coding time across all projects. Replace ':userId' with your actual Ziit user ID. ```text https://ziit.app/api/public/badge/cm98il90n0000o52c3my0bf5p ``` -------------------------------- ### Registering Ziit Commands (TypeScript Example) Source: https://docs.ziit.app/extension-spec-sheet Extensions should register commands to enable user interaction for configuring the API key, setting the base URL, opening the dashboard, and viewing logs. This example demonstrates command registration, likely within an IDE extension framework. ```typescript // Example command registration (specific IDE API may vary) context.subscriptions.push( vscode.commands.registerCommand('ziit.setApiKey', async () => { const apiKey = await vscode.window.showInputBox({ prompt: 'Enter your Ziit API Key', password: true }); if (apiKey) { // Save apiKey to configuration } }) ); context.subscriptions.push( vscode.commands.registerCommand('ziit.setBaseUrl', async () => { const baseUrl = await vscode.window.showInputBox({ prompt: 'Enter your Ziit server URL', value: 'https://api.ziit.com' }); if (baseUrl) { // Save baseUrl to configuration } }) ); context.subscriptions.push( vscode.commands.registerCommand('ziit.openDashboard', () => { // Open Ziit web dashboard in a browser vscode.env.openExternal(vscode.Uri.parse('https://app.ziit.com')); }) ); context.subscriptions.push( vscode.commands.registerCommand('ziit.showOutput', () => { // Show extension output channel const outputChannel = vscode.window.createOutputChannel('Ziit'); outputChannel.show(); }) ); ``` -------------------------------- ### Start Docker Compose Containers Source: https://docs.ziit.app/deploy/docker-compose This command starts the Docker containers defined in the `docker-compose.yml` file in detached mode (`-d`). This allows the application to run in the background. The application will be accessible at `http://localhost:3000` by default. ```bash docker compose up -d ``` -------------------------------- ### Example: Ziit Badge with Custom Time Range (Today) Source: https://docs.ziit.app/badges An example of a Ziit badge URL to display coding time for a specific time period, in this case, 'today'. Replace ':userId' and ':project' as needed. ```text https://ziit.app/api/public/badge/cm98il90n0000o52c3my0bf5p/all/today ``` -------------------------------- ### User GET Source: https://docs.ziit.app/extension-spec-sheet Returns public user data for the account identified by the Bearer API key. ```APIDOC ## GET /user ### Description Returns public user data for the account identified by the Bearer API key. ### Method GET ### Endpoint `/user` ### Response #### Success Response (200) (The specific structure of the user data is not detailed in the provided text.) ``` -------------------------------- ### Example: Ziit Badge with Custom Color and Label Source: https://docs.ziit.app/badges An example of a Ziit badge URL showing custom color and label text. This badge displays 'Coding Time' in green. Replace ':userId' and ':project' as needed. ```text https://ziit.app/api/public/badge/cm98il90n0000o52c3my0bf5p/all/all-time/green/Coding Time ``` -------------------------------- ### Get Public Leaderboard Data (C#) Source: https://docs.ziit.app/api/leaderboard Retrieves public leaderboard data showing top users using C#. This endpoint is accessible via a GET request. ```C# using System; using System.Net.Http; public class LeaderboardClient { public static async Task GetLeaderboardAsync() { using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync("https://ziit.app/api/public/leaderboard"); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } } ``` -------------------------------- ### Get Public Leaderboard Data (Java) Source: https://docs.ziit.app/api/leaderboard Retrieves public leaderboard data showing top users using Java. This endpoint is accessible via a GET request. ```Java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class LeaderboardClient { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://ziit.app/api/public/leaderboard")) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); } } ``` -------------------------------- ### Download Docker Compose File using cURL Source: https://docs.ziit.app/deploy/docker-compose This snippet shows how to download the `docker-compose.yml` file from the GitHub repository using the `curl` command-line tool. Ensure `curl` is installed on your system. ```bash curl -o docker-compose.yml https://raw.githubusercontent.com/0PandaDEV/Ziit/refs/heads/main/docker-compose.yml ``` -------------------------------- ### Get Public Leaderboard Data (Go) Source: https://docs.ziit.app/api/leaderboard Retrieves public leaderboard data showing top users using Go. This endpoint is accessible via a GET request. ```Go package main import ( "fmt" "net/http" ) func main() { resp, err := http.Get("https://ziit.app/api/public/leaderboard") if err != nil { fmt.Println("Error making request: ", err) return } defer resp.Body.Close() // Process the response body here fmt.Println("Status Code:", resp.StatusCode) } ``` -------------------------------- ### Get Public Leaderboard Data (Python) Source: https://docs.ziit.app/api/leaderboard Retrieves public leaderboard data showing top users using Python. This endpoint is accessible via a GET request. ```Python import requests response = requests.get('https://ziit.app/api/public/leaderboard') print(response.json()) ``` -------------------------------- ### GET /api/public/leaderboard Source: https://docs.ziit.app/api/leaderboard Returns public leaderboard data showing top users. ```APIDOC ## GET /api/public/leaderboard ### Description Returns public leaderboard data showing top users. ### Method GET ### Endpoint /api/public/leaderboard ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```bash curl -X GET "https://ziit.app/api/public/leaderboard" ``` ### Response #### Success Response (200) Empty #### Response Example (No example provided in the source text) ``` -------------------------------- ### Badge GET Source: https://docs.ziit.app/api/batch Returns an SVG badge representing time spent. ```APIDOC ## GET /badge ### Description Returns an SVG badge representing time spent. URL path segments define badge parameters. ### Method GET ### Endpoint https://ziit.app/badge ### Parameters #### Path Parameters (Details for path parameters are not provided in the input text, but would typically be defined here, e.g., project name, time range) #### Query Parameters None #### Request Body None ### Request Example (No specific request example provided for the badge endpoint) ### Response #### Success Response (200) - (SVG content representing the badge) #### Response Example (No specific response example provided for the badge endpoint, but it would be an SVG string) ``` -------------------------------- ### Get Public Leaderboard Data (JavaScript) Source: https://docs.ziit.app/api/leaderboard Retrieves public leaderboard data showing top users using JavaScript. This endpoint is accessible via a GET request. ```JavaScript fetch('https://ziit.app/api/public/leaderboard') .then(response => response.json()) .then(data => console.log(data)); ``` -------------------------------- ### GET /api/public/{badge} Source: https://docs.ziit.app/api/badge Returns an SVG badge representing time spent. URL path segments define badge parameters. ```APIDOC ## GET /api/public/{badge} ### Description Returns an SVG badge representing time spent. URL path segments define badge parameters. ### Method GET ### Endpoint /api/public/{badge} ### Parameters #### Path Parameters - **badge** (string) - Required - Path segments for badge configuration (userId/project/timeRange/color/labelText) #### Query Parameters - **style** (string) - Optional - Badge style. Default: "flat". Allowed values: "classic" | "flat" - **icon** (string) - Optional - Icon to display on badge ### Request Example ```curl curl -X GET "https://ziit.app/api/public/string?style=classic&icon=string" ``` ### Response #### Success Response (200) - **image/svg+xml** - The generated SVG badge. #### Error Response (400) - **string** - An error message. #### Response Example ```json "string" ``` ``` -------------------------------- ### GET /api/external/stats Source: https://docs.ziit.app/extension-spec-sheet Retrieve daily summary statistics for tracked time, including total time, projects, languages, editors, and operating systems. ```APIDOC ## GET /api/external/stats ### Description Retrieve daily summary statistics for tracked time, including total time, projects, languages, editors, and operating systems. ### Method GET ### Endpoint `/api/external/stats` ### Query Parameters - **timeRange** (string) - Required - The time range for the statistics (e.g., `today`). - **midnightOffsetSeconds** (integer) - Required - The timezone offset in seconds from UTC to midnight. ### Response #### Success Response (200) - **summaries** (array) - An array of summary objects. - **date** (string) - The date of the summary. - **totalSeconds** (integer) - The total seconds tracked for the day. - **projects** (object) - An object mapping project names to seconds tracked. - **languages** (object) - An object mapping language names to seconds tracked. - **editors** (object) - An object mapping editor names to seconds tracked. - **os** (object) - An object mapping OS names to seconds tracked. #### Response Example ```json { "summaries": [{ "date": "2024-01-15", "totalSeconds": 28800, "projects": { "my-project": 28800 }, "languages": { "typescript": 20000, "javascript": 8800 }, "editors": { "Your IDE Name": 28800 }, "os": { "macOS": 28800 } }] } ``` ``` -------------------------------- ### Send Batch Heartbeats via C# Source: https://docs.ziit.app/api/batch C# code example for sending batch heartbeat data to the Ziit App API using `HttpClient`. This snippet demonstrates how to construct the POST request with the authorization header and JSON payload. Ensure you handle the `HttpClient` lifecycle appropriately in a real application. ```csharp using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; public class ZiitBatchSender { public static async Task SendBatchHeartbeats(string token, List> heartbeats) { using (var client = new HttpClient()) { var url = "https://ziit.app/api/external/batch"; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var jsonPayload = JsonConvert.SerializeObject(heartbeats); var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync(url, content); response.EnsureSuccessStatusCode(); // Throws an exception if the response status code is an error string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine($"Response: {responseBody}"); } catch (HttpRequestException e) { Console.WriteLine($"Error sending batch heartbeats: {e.Message}"); } } } // Example Usage: // public static async Task Main(string[] args) // { // string myToken = "YOUR_API_TOKEN"; // var myHeartbeats = new List> // { // new Dictionary // { // { "timestamp", "2023-10-15T14:30:00Z" }, // { "project", "my-awesome-project" }, // { "language", "javascript" }, // { "editor", "vscode" }, // { "os", "macos" }, // { "file", "App.js" } // } // }; // await SendBatchHeartbeats(myToken, myHeartbeats); // } } ``` -------------------------------- ### GET /api/external/user Source: https://docs.ziit.app/api/user Retrieves public user data for the account identified by the Bearer API key. ```APIDOC ## GET /api/external/user ### Description Returns public user data for the account identified by the Bearer API key. ### Method GET ### Endpoint /api/external/user ### Parameters #### Header Parameters - **Authorization** (string) - Required - Bearer token for authentication. Format: `Bearer ` ### Request Example ```json { "example": "curl -X GET \"https://ziit.app/api/external/user\" \ -H \"Authorization: Bearer \"" } ``` ### Response #### Success Response (200) - **id** (string) - The user's unique identifier. - **email** (string) - The user's email address. - **githubId** (string) - The user's GitHub ID. - **githubUsername** (string) - The user's GitHub username. - **apiKey** (string) - The user's API key. - **keystrokeTimeout** (integer) - The user's keystroke timeout setting. #### Response Example ```json { "id": "string", "email": "user@example.com", "githubId": "string", "githubUsername": "string", "apiKey": "43845a17-01cb-476b-8c02-27c26965e86a", "keystrokeTimeout": 0 } ``` #### Error Responses - **401** - Unauthorized - **404** - Not Found - **500** - Internal Server Error ``` -------------------------------- ### Send Batch Heartbeats via Java Source: https://docs.ziit.app/api/batch Java code example for sending batch heartbeat data to the Ziit App API. This snippet uses Apache HttpClient to construct and execute the POST request. You'll need to include the Apache HttpClient library in your project's dependencies. ```java import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.List; import java.util.Map; import java.util.HashMap; public class ZiitBatchSender { public static void sendBatchHeartbeats(String token, List> heartbeats) throws Exception { String url = "https://ziit.app/api/external/batch"; CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); ObjectMapper mapper = new ObjectMapper(); String jsonPayload = mapper.writeValueAsString(heartbeats); StringEntity entity = new StringEntity(jsonPayload); httpPost.setEntity(entity); httpPost.setHeader("Authorization", "Bearer " + token); httpPost.setHeader("Content-Type", "application/json"); try (CloseableHttpResponse response = client.execute(httpPost)) { System.out.println("Status Code: " + response.getStatusLine().getStatusCode()); HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { String responseString = EntityUtils.toString(responseEntity); System.out.println("Response Body: " + responseString); } } finally { client.close(); } } public static void main(String[] args) { // Example Usage: // String myToken = "YOUR_API_TOKEN"; // List> myHeartbeats = new java.util.ArrayList<>(); // Map heartbeat = new HashMap<>(); // heartbeat.put("timestamp", "2023-10-15T14:30:00Z"); // heartbeat.put("project", "my-awesome-project"); // heartbeat.put("language", "javascript"); // heartbeat.put("editor", "vscode"); // heartbeat.put("os", "macos"); // heartbeat.put("file", "App.js"); // myHeartbeats.add(heartbeat); // try { // sendBatchHeartbeats(myToken, myHeartbeats); // } catch (Exception e) { // e.printStackTrace(); // } } } ``` -------------------------------- ### Send Batch Heartbeats via Python Source: https://docs.ziit.app/api/batch Python script to submit a batch of heartbeat data to the Ziit App API. It uses the `requests` library to perform a POST request, including the authorization token and JSON payload. Remember to install the `requests` library if you haven't already (`pip install requests`). ```python import requests import json def send_batch_heartbeats(token, heartbeats): url = "https://ziit.app/api/external/batch" headers = { "Authorization": f"Bearer {token}", "Content-Type": "application/json" } try: response = requests.post(url, headers=headers, data=json.dumps(heartbeats)) response.raise_for_status() # Raise an exception for bad status codes data = response.json() print(f"Batch sent successfully: {data}") return data except requests.exceptions.RequestException as e: print(f"Error sending batch heartbeats: {e}") # Example usage: # my_token = "YOUR_API_TOKEN" # my_heartbeats = [ # { # "timestamp": "2023-10-15T14:30:00Z", # "project": "my-awesome-project", # "language": "javascript", # "editor": "vscode", # "os": "macos", # "file": "App.js" # } # ] # send_batch_heartbeats(my_token, my_heartbeats) ``` -------------------------------- ### Get Public User Data (API) Source: https://docs.ziit.app/api/user Retrieves public user data for an account using a Bearer API key. The request is made via a GET request to the /api/external/user endpoint. Requires an 'Authorization' header with a Bearer token. Returns a JSON object with user details on success, or error codes for unauthorized, not found, or server errors. ```cURL curl -X GET "https://ziit.app/api/external/user" \ -H "Authorization: Bearer " ``` ```JavaScript fetch("https://ziit.app/api/external/user", { method: "GET", headers: { "Authorization": "Bearer YOUR_API_KEY" } }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ``` ```Go package main import ( "fmt" "net/http" "io/ioutil" ) func main() { client := &http.Client{} req, err := http.NewRequest("GET", "https://ziit.app/api/external/user", nil) if err != nil { fmt.Println("Error creating request:", err) return } req.Header.Add("Authorization", "Bearer YOUR_API_KEY") resp, err := client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("Error reading response body:", err) return } fmt.Println("Status Code:", resp.StatusCode) fmt.Println("Response Body:", string(body)) } ``` ```Python import requests url = "https://ziit.app/api/external/user" headers = { "Authorization": "Bearer YOUR_API_KEY" } response = requests.get(url, headers=headers) print(f"Status Code: {response.status_code}") print(f"Response Body: {response.json()}") ``` ```Java import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.io.IOException; public class GetUser { public static void main(String[] args) throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(java.net.URI.create("https://ziit.app/api/external/user")) .header("Authorization", "Bearer YOUR_API_KEY") .GET() .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("Status Code: " + response.statusCode()); System.out.println("Response Body: " + response.body()); } } ``` ```C# using System; using System.Net.Http; using System.Threading.Tasks; public class GetUserAsync { public static async Task Main(string[] args) { using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "YOUR_API_KEY"); HttpResponseMessage response = await client.GetAsync("https://ziit.app/api/external/user"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine($"Status Code: {response.StatusCode}"); Console.WriteLine($"Response Body: {responseBody}"); } } } ``` -------------------------------- ### Send Batch Heartbeats via cURL Source: https://docs.ziit.app/api/batch Example cURL command to send a batch of heartbeat data to the Ziit App API. It includes the endpoint URL, authorization header, content type, and a JSON payload representing heartbeat entries. Ensure the Bearer token is correctly provided. ```bash curl -X POST "https://ziit.app/api/external/batch" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d \ '[ { "timestamp": "2023-10-15T14:30:00Z", "project": "my-awesome-project", "language": "javascript", "editor": "vscode", "os": "macos", "file": "App.js" } ]' ``` -------------------------------- ### Send Batch Heartbeats via JavaScript Source: https://docs.ziit.app/api/batch JavaScript code snippet demonstrating how to send a batch of heartbeat data to the Ziit App API using the fetch API. It constructs the request with the appropriate headers and JSON body. This example assumes you have a valid Bearer token. ```javascript async function sendBatchHeartbeats(token, heartbeats) { const url = "https://ziit.app/api/external/batch"; const headers = { "Authorization": `Bearer ${token}`, "Content-Type": "application/json" }; try { const response = await fetch(url, { method: "POST", headers: headers, body: JSON.stringify(heartbeats) }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); console.log("Batch sent successfully:", data); return data; } catch (error) { console.error("Error sending batch heartbeats:", error); } } // Example usage: // const myToken = "YOUR_API_TOKEN"; // const myHeartbeats = [ // { // "timestamp": "2023-10-15T14:30:00Z", // "project": "my-awesome-project", // "language": "javascript", // "editor": "vscode", // "os": "macos", // "file": "App.js" // } // ]; // sendBatchHeartbeats(myToken, myHeartbeats); ``` -------------------------------- ### Get User Stats via API (cURL) Source: https://docs.ziit.app/api/stats Retrieves aggregated statistics for a specific user using their Bearer API key. Requires an Authorization header and accepts 'timeRange' and 'midnightOffsetSeconds' as query parameters. ```cURL curl -X GET "https://ziit.app/api/external/stats?timeRange=today&midnightOffsetSeconds=0" \ -H "Authorization: Bearer " ``` -------------------------------- ### GET /api/public/badge/:userId/:project/:timeRange/:color/:labelText Source: https://docs.ziit.app/badges Generates a customizable SVG badge displaying coding statistics for a specific user, project, and time range. Various parameters can be adjusted to customize the badge's appearance and content. ```APIDOC ## GET /api/public/badge/:userId/:project/:timeRange/:color/:labelText ### Description Generates a customizable SVG badge displaying coding statistics for a specific user, project, and time range. Various parameters can be adjusted to customize the badge's appearance and content. ### Method GET ### Endpoint `/api/public/badge/:userId/:project/:timeRange/:color/:labelText` ### Parameters #### Path Parameters - **userId** (string) - Required - Your Ziit user ID - **project** (string) - Optional - Project name or "all" for all projects (default: "all") - **timeRange** (string) - Optional - Time period to display stats for (default: "all-time") - **color** (string) - Optional - Badge color (default: "blue") - **labelText** (string) - Optional - Text for the badge label (default: "Ziit") #### Query Parameters - **style** (string) - Optional - Badge style ("classic" (default), "flat") - **icon** (string) - Optional - Direct URL to an image (e.g. SVG, PNG, JPG) ### Request Example ``` https://ziit.app/api/public/badge/cm98il90n0000o52c3my0bf5p/all/all-time/green/Coding Time?style=flat&icon=https://example.com/icon.svg ``` ### Response #### Success Response (200) - **SVG Badge** (string) - The generated SVG image representing the coding statistics badge. #### Response Example (SVG content would be returned here, not a JSON object) ``` -------------------------------- ### Extension Entry Point (TypeScript) Source: https://docs.ziit.app/extension-spec-sheet The main extension file acts as the activation point for the Ziit IDE extension. It initializes configuration, instantiates core managers like the status bar and heartbeat managers, and registers commands and event listeners. ```typescript // Main activation function export async function activate(context: ExtensionContext) { await initializeAndSyncConfig(); const statusBarManager = new StatusBarManager(); const heartbeatManager = new HeartbeatManager(context, statusBarManager); // Register commands and event listeners } ``` -------------------------------- ### Get Public Leaderboard Data (cURL) Source: https://docs.ziit.app/api/leaderboard Retrieves public leaderboard data showing top users. This endpoint is accessible via a GET request. ```cURL curl -X GET "https://ziit.app/api/public/leaderboard" ``` -------------------------------- ### Authentication Source: https://docs.ziit.app/extension-spec-sheet All API requests must include an 'Authorization' header with a Bearer token. ```APIDOC ## Authentication All API requests must include an `Authorization` header with a Bearer token. ``` Authorization: Bearer {apiKey} ``` ``` -------------------------------- ### POST /api/external/heartbeat Source: https://docs.ziit.app/extension-spec-sheet Send a single heartbeat to track current activity, including project, language, editor, and OS details. ```APIDOC ## POST /api/external/heartbeat ### Description Send a single heartbeat to track current activity, including project, language, editor, and OS details. ### Method POST ### Endpoint `/api/external/heartbeat` ### Request Body - **timestamp** (string) - Required - The timestamp of the heartbeat event. - **project** (string) - Required - The name of the project being worked on. - **language** (string) - Required - The programming language of the current file. - **file** (string) - Required - The name of the current file. - **branch** (string) - Optional - The git branch name. - **editor** (string) - Required - The name of the IDE being used. - **os** (string) - Required - The operating system. ### Request Example ```json { "timestamp": "2024-01-15T10:30:00.000Z", "project": "my-project", "language": "typescript", "file": "extension.ts", "branch": "main", "editor": "Your IDE Name", "os": "macOS" } ``` ### Response #### Success Response (200) (No specific response body defined, typically an empty success response or a confirmation message.) ``` -------------------------------- ### Daily Summary API Request and Response (JSON) Source: https://docs.ziit.app/extension-spec-sheet The 'Daily Summary' endpoint retrieves aggregated activity data for a specified time range. The response is a JSON object containing summaries broken down by date, total seconds, projects, languages, editors, and operating systems. ```json GET /api/external/stats?timeRange=today&midnightOffsetSeconds={timezoneOffset} Response: { "summaries": [{ "date": "2024-01-15", "totalSeconds": 28800, "projects": { "my-project": 28800 }, "languages": { "typescript": 20000, "javascript": 8800 }, "editors": { "Your IDE Name": 28800 }, "os": { "macOS": 28800 } }] } ``` -------------------------------- ### Get Aggregated User Stats (API) Source: https://docs.ziit.app/api/user Retrieves aggregated statistics for the user identified by the Bearer API key. This endpoint is accessed via a GET request. Authentication is handled through the 'Authorization' header using a Bearer token. The response will contain the aggregated stats for the authenticated user. ```cURL curl -X GET "https://ziit.app/api/external/stats" \ -H "Authorization: Bearer " ``` -------------------------------- ### POST /api/external/batch Source: https://docs.ziit.app/extension-spec-sheet Send a batch of heartbeats, typically used for syncing offline tracked time. ```APIDOC ## POST /api/external/batch ### Description Send a batch of heartbeats, typically used for syncing offline tracked time. The maximum number of heartbeats per request is 1000. ### Method POST ### Endpoint `/api/external/batch` ### Request Body An array of heartbeat objects. Each object should conform to the structure defined for the `/api/external/heartbeat` endpoint. ```json [ { /* heartbeat 1 */ }, { /* heartbeat 2 */ }, // ... up to 1000 heartbeats ] ``` ### Response #### Success Response (200) (No specific response body defined, typically an empty success response or a confirmation message.) ``` -------------------------------- ### Generate Basic Ziit Badge URL Source: https://docs.ziit.app/badges Constructs a basic Ziit badge URL to display total coding time across all projects. Requires userId. Defaults to 'all' for project and timeRange, and 'blue' for color. ```text https://ziit.app/api/public/badge/:userId/:project/:timeRange/:color/:labelText? ``` -------------------------------- ### Batch Sync API Request (JSON Array) Source: https://docs.ziit.app/extension-spec-sheet The 'Batch Sync' endpoint allows for the offline transmission of multiple heartbeats in a single request. This is crucial for maintaining data integrity when the extension is operating in offline mode, supporting up to 1000 heartbeats per request. ```json [ { /* heartbeat 1 */ }, { /* heartbeat 2 */ }, // ... up to 1000 heartbeats ] ``` -------------------------------- ### GET /api/public/stats Source: https://docs.ziit.app/api/public-stats Retrieves aggregate statistics across the Ziit platform. This endpoint provides insights into the overall usage and activity on the platform. ```APIDOC ## GET /api/public/stats ### Description Returns aggregate statistics across the platform. This endpoint provides insights into the overall usage and activity on the platform. ### Method GET ### Endpoint /api/public/stats ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **totalUsers** (integer) - The total number of users on the platform. - **totalHeartbeats** (integer) - The total number of heartbeats recorded. - **totalHours** (integer) - The total number of hours recorded. - **topEditor** (string) - The most used code editor. - **topLanguage** (string) - The most used programming language. - **topOS** (string) - The most used operating system. - **lastUpdated** (string) - The timestamp of the last data update (ISO 8601 format). - **source** (string) - The source of the data (e.g., "mixed"). #### Response Example ```json { "totalUsers": 1500, "totalHeartbeats": 5000000, "totalHours": 25000, "topEditor": "vscode", "topLanguage": "javascript", "topOS": "macos", "lastUpdated": "2019-08-24T14:15:22Z", "source": "mixed" } ``` ``` -------------------------------- ### Send Heartbeat POST Request (Go) Source: https://docs.ziit.app/api/heartbeat This snippet demonstrates sending a single heartbeat payload to the Ziit App API using Go. It requires an API key for authentication and sets the Content-Type to application/json. The request body includes project, language, editor, OS, and optional branch and file information. ```go package main import ( "bytes" "encoding/json" "fmt" "net/http" "time" ) type HeartbeatPayload struct { Timestamp string `json:"timestamp"` Project string `json:"project"` Language string `json:"language"` Editor string `json:"editor"` OS string `json:"os"` Branch *string `json:"branch,omitempty"` File *string `json:"file,omitempty"` } func sendHeartbeat(token string) (map[string]interface{}, error) { payload := HeartbeatPayload{ Timestamp: time.Now().UTC().Format(time.RFC3339), Project: "my-awesome-project", Language: "go", Editor: "vs code", OS: "linux", } payloadBytes, err := json.Marshal(payload) if err != nil { return nil, fmt.Errorf("failed to marshal payload: %w", err) } req, err := http.NewRequest("POST", "https://ziit.app/api/external/heartbeat", bytes.NewBuffer(payloadBytes)) if err != nil { return nil, fmt.Errorf("failed to create request: %w", err) } req.Header.Set("Authorization", "Bearer "+token) req.Header.Set("Content-Type", "application/json") client := &http.Client{} res, err := client.Do(req) if err != nil { return nil, fmt.Errorf("failed to send request: %w", err) } defer res.Body.Close() var result map[string]interface{} err = json.NewDecoder(res.Body).Decode(&result) if err != nil { return nil, fmt.Errorf("failed to decode response: %w", err) } if res.StatusCode != http.StatusOK { return nil, fmt.Errorf("unexpected status code: %d", res.StatusCode) } return result, nil } ``` -------------------------------- ### Send Batch Heartbeats via Go Source: https://docs.ziit.app/api/batch Go program to send a batch of heartbeat data to the Ziit App API. It utilizes the `net/http` package to construct and send a POST request with the necessary headers and JSON payload. Ensure you replace placeholder values with your actual token and data. ```go package main import ( "bytes" "encoding/json" "fmt" "net/http" ) func main() { url := "https://ziit.app/api/external/batch" token := "YOUR_API_TOKEN" heartbeats := []map[string]string{ { "timestamp": "2023-10-15T14:30:00Z", "project": "my-awesome-project", "language": "javascript", "editor": "vscode", "os": "macos", "file": "App.js" } } payload, err := json.Marshal(heartbeats) if err != nil { fmt.Println("Error marshalling JSON:", err) return } req, err := http.NewRequest("POST", url, bytes.NewBuffer(payload)) if err != nil { fmt.Println("Error creating request:", err) return } req.Header.Set("Authorization", "Bearer "+token) req.Header.Set("Content-Type", "application/json") client := &http.Client{} res, err := client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer res.Body.Close() var result map[string]interface{} err = json.NewDecoder(res.Body).Decode(&result) if err != nil { fmt.Println("Error decoding response:", err) return } fmt.Printf("Response: %+v\n", result) } ```