Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions plugins/leetcode-pulse/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 Manish

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
42 changes: 42 additions & 0 deletions plugins/leetcode-pulse/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# LeetCode Pulse

A desktop tile with your LeetCode solved counts, rank, difficulty split, streak, acceptance and 12-week activity map.

![LeetCode Pulse preview](assets/preview-widget.png)

## What it does

`bin/leetcode_pulse.py` fetches four public endpoints from [alfa-leetcode-api](https://github.com/alfaarghya/alfa-leetcode-api) in parallel and prints one compact JSON snapshot. The service polls every 10 minutes by default, keeps the last good snapshot when the API is unreachable, and the tile renders the numbers with the active Ryoku palette. Clicking the tile opens your LeetCode profile. There is no LeetCode login and no token.

## Install

Install from Ryoku Settings → Add-ons → Plugins → LeetCode Pulse. It is a community plugin (`official: false`); Ryoku does not review or maintain it.

## How it plugs in

The plugin registers as a `desktopWidget`. After adding it, move, scale and lock the tile under **Ryoku Settings → Add-ons → Plugins**, or place it with `ryoku-plugins-place`. The tile reports its own size and uses only `Ryoku.PluginKit.Singletons` for colour, type and radius.

| Setting | Type | Default | Effect |
| --- | --- | --- | --- |
| `username` | text | `MANISHX01` | LeetCode username shown in the tile — set it to your own handle |
| `pollSeconds` | int | `600` | Refresh interval in seconds (60–3600) |

The default is the contributor's public profile so the tile has something useful to show on first install; every installer can change `username` in the plugin settings.

## Security and privacy

- **Network:** reads public profile, solved, calendar and language data from `alfa-leetcode-api.onrender.com`. `leetcode.com` is opened only on an explicit click. Both hosts are declared in `capabilities.network`.
- **Files:** writes only `pulse.json` under `pluginApi.stateDir` (`$XDG_STATE_HOME/ryoku/plugins/leetcode-pulse`), and only to show cached stats during an API outage. No other paths are touched.
- **Commands:** Python 3 only, declared in `dependencies.commands`. No privilege, no shell string built from settings or network data, no secrets, no binaries.
- The username is URL-encoded and passed as a single path component; no credentials are sent.

## Develop tree

- `service/Main.qml`: settings, polling, timeout guard and cached snapshot state.
- `content/Widget.qml`: the themed tile, difficulty bar and 12-week activity grid.
- `bin/leetcode_pulse.py`: parallel read-only API fetch, dots and cache helper.
- `assets/preview-widget.png`: capture of the rendered tile.

## Credits and maintenance

Written by Manish (<159711477+mannish01@users.noreply.github.com>), MIT licensed, and maintained at <https://github.com/mannish01/LeetCode-Pulse>. Statistics come from the community [alfa-leetcode-api](https://github.com/alfaarghya/alfa-leetcode-api) service; Ryoku and LeetCode are not affiliated with this plugin.
Binary file added plugins/leetcode-pulse/assets/preview-widget.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
134 changes: 134 additions & 0 deletions plugins/leetcode-pulse/bin/leetcode_pulse.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
#!/usr/bin/env python3
"""Fetch MANISHX01's LeetCode stats for the Ryoku LeetCode Pulse widget.

Usage: leetcode_pulse.py <username> <state-dir>
Prints one compact JSON object on stdout. Never writes outside <state-dir>.
"""
import concurrent.futures
import datetime as dt
import json
import os
import sys
import urllib.parse
import urllib.request

BASE = "https://alfa-leetcode-api.onrender.com"
PATHS = ("/profile", "/solved", "/calendar", "/language")


def fetch(username, path):
req = urllib.request.Request(
BASE + "/" + urllib.parse.quote(username, safe="") + path,
headers={"User-Agent": "ryoku-leetcode-pulse/0.1", "Accept": "application/json"},
)
with urllib.request.urlopen(req, timeout=6) as response:
return json.load(response)


def bucket(rows, difficulty):
for row in rows or []:
if row.get("difficulty") == difficulty:
return row
return {}


def build_dots(raw_calendar):
try:
parsed = json.loads(raw_calendar) if isinstance(raw_calendar, str) else raw_calendar
except (TypeError, ValueError):
parsed = {}
counts = {}
for key, value in (parsed or {}).items():
try:
day = dt.datetime.fromtimestamp(int(key), dt.timezone.utc).date()
counts[day.isoformat()] = min(int(value), 5)
except (TypeError, ValueError, OSError, OverflowError):
continue
today = dt.datetime.now(dt.timezone.utc).date()
return [counts.get((today - dt.timedelta(days=i)).isoformat(), 0) for i in range(83, -1, -1)]


def main():
username = sys.argv[1] if len(sys.argv) > 1 else "MANISHX01"
state_dir = sys.argv[2] if len(sys.argv) > 2 else ""
cache_path = os.path.join(state_dir, "pulse.json") if state_dir else ""

with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
futures = [(path, pool.submit(fetch, username, path)) for path in PATHS]
results = {}
for path, future in futures:
try:
results[path] = future.result()
except Exception:
results[path] = None

def load_cached():
if not cache_path:
return None
try:
with open(cache_path, "r", encoding="utf-8") as handle:
cached = json.load(handle)
if isinstance(cached, dict) and cached.get("username") == username:
return cached
except (OSError, ValueError):
pass
return None

# Every endpoint must answer before a snapshot is called live: a partial
# outage must never overwrite a good cache with zeros.
live = all(value is not None for value in results.values())
cached = load_cached()
if not live and cached is not None:
snapshot = dict(cached)
snapshot["live"] = False
snapshot["error"] = "partial or offline API response - showing saved stats"
print(json.dumps(snapshot, separators=(",", ":")))
return

profile = results.get("/profile") or {}
solved = results.get("/solved") or {}
calendar = results.get("/calendar") or {}
languages = results.get("/language") or {}

total_attempts = bucket(solved.get("totalSubmissionNum"), "All").get("submissions", 0) or 0
total_accepted = bucket(solved.get("acSubmissionNum"), "All").get("submissions", 0) or 0
acceptance = round(total_accepted / total_attempts * 100) if total_attempts else 0

langs = [
{"name": row.get("languageName", ""), "count": row.get("problemsSolved", 0)}
for row in (languages.get("languageProblemCount") or [])
]
langs.sort(key=lambda row: row["count"], reverse=True)

data = {
"username": username,
"solved": solved.get("solvedProblem", profile.get("totalSolved", 0)) or 0,
"easy": solved.get("easySolved", profile.get("easySolved", 0)) or 0,
"medium": solved.get("mediumSolved", profile.get("mediumSolved", 0)) or 0,
"hard": solved.get("hardSolved", profile.get("hardSolved", 0)) or 0,
"total": profile.get("totalQuestions", 0) or 0,
"rank": profile.get("ranking", 0) or 0,
"streak": calendar.get("streak", 0) or 0,
"activeDays": calendar.get("totalActiveDays", 0) or 0,
"acceptance": acceptance,
"accepted": total_accepted,
"submissions": total_attempts,
"languages": langs[:3],
"dots": build_dots(calendar.get("submissionCalendar", "{}")),
"fetchedAt": int(dt.datetime.now(dt.timezone.utc).timestamp()),
"live": live,
"error": "" if live else "some endpoints were unavailable",
}

if live and cache_path:
try:
os.makedirs(state_dir, exist_ok=True)
with open(cache_path, "w", encoding="utf-8") as handle:
json.dump(data, handle)
except OSError:
pass
print(json.dumps(data, separators=(",", ":")))


if __name__ == "__main__":
main()
Loading