-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
213 lines (184 loc) · 8.11 KB
/
Copy pathProgram.cs
File metadata and controls
213 lines (184 loc) · 8.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
/// <summary>
/// QuickSheet Rust Crate Lookup Extension — crate info and search via crates.io API.
/// Prefix: "crates". Usage:
/// "crates: tokio" → detail view for a specific crate
/// "crates: search async" → top 5 crates matching search query
/// No API key required. Responses cached 30 min (crate detail) / 10 min (search).
/// </summary>
class Program
{
private static readonly HttpClient Http = new()
{
Timeout = TimeSpan.FromSeconds(12),
DefaultRequestHeaders = { { "User-Agent", "quicksheet-crates/1.0 (github.com/Deskworks/quicksheet-crates)" } }
};
// Caches: key → (result, fetchedAt)
private static readonly Dictionary<string, (string result, DateTime fetchedAt)> CrateCache = new(StringComparer.OrdinalIgnoreCase);
private static readonly Dictionary<string, (string result, DateTime fetchedAt)> SearchCache = new(StringComparer.OrdinalIgnoreCase);
private static readonly TimeSpan CrateCacheTtl = TimeSpan.FromMinutes(30);
private static readonly TimeSpan SearchCacheTtl = TimeSpan.FromMinutes(10);
static void Main()
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
string? line;
while ((line = Console.ReadLine()) != null)
{
if (string.IsNullOrWhiteSpace(line)) continue;
try
{
using var doc = JsonDocument.Parse(line);
string? type = doc.RootElement.TryGetProperty("type", out var tp) ? tp.GetString() : null;
switch (type)
{
case "init":
HandleInit();
break;
case "activate":
HandleActivate(doc.RootElement);
break;
case "deactivate":
HandleDeactivate();
break;
}
}
catch (Exception ex)
{
SendResult($"[crates] error: {ex.Message}");
}
}
}
static void HandleInit()
{
var response = new
{
type = "init_response",
prefix = "crates",
name = "Rust Crate Lookup",
description = "Look up Rust crates on crates.io. Usage: crates: <name> or crates: search <query>"
};
Console.WriteLine(JsonSerializer.Serialize(response));
}
static void HandleDeactivate()
{
var response = new { type = "deactivate_response" };
Console.WriteLine(JsonSerializer.Serialize(response));
}
static void HandleActivate(JsonElement root)
{
string? cellValue = root.TryGetProperty("value", out var v) ? v.GetString() : null;
string? id = root.TryGetProperty("id", out var i) ? i.GetString() : null;
if (string.IsNullOrWhiteSpace(cellValue))
{
SendResult("Usage: crates: <name> or crates: search <query>", id);
return;
}
string query = cellValue.Trim();
string result;
if (query.StartsWith("search ", StringComparison.OrdinalIgnoreCase))
{
string searchTerm = query["search ".Length..].Trim();
result = FetchSearch(searchTerm);
}
else
{
result = FetchCrate(query);
}
SendResult(result, id);
}
static string FetchCrate(string name)
{
if (CrateCache.TryGetValue(name, out var cached) && DateTime.UtcNow - cached.fetchedAt < CrateCacheTtl)
return cached.result;
try
{
string url = $"https://crates.io/api/v1/crates/{Uri.EscapeDataString(name)}";
string json = Http.GetStringAsync(url).GetAwaiter().GetResult();
using var doc = JsonDocument.Parse(json);
if (!doc.RootElement.TryGetProperty("crate", out var crate))
return $"[crates] '{name}' not found on crates.io";
string crateName = crate.TryGetProperty("name", out var n) ? n.GetString() ?? name : name;
string version = crate.TryGetProperty("max_version", out var mv) ? mv.GetString() ?? "?" : "?";
long downloads = crate.TryGetProperty("downloads", out var dl) ? dl.GetInt64() : 0;
long recentDl = crate.TryGetProperty("recent_downloads", out var rd) ? rd.GetInt64() : 0;
string desc = crate.TryGetProperty("description", out var ds) ? ds.GetString() ?? "" : "";
string? homepage = crate.TryGetProperty("homepage", out var hp) ? hp.GetString() : null;
string? repository = crate.TryGetProperty("repository", out var rp) ? rp.GetString() : null;
string dlStr = FormatCount(downloads);
string recentStr = FormatCount(recentDl);
string link = homepage ?? repository ?? $"https://crates.io/crates/{crateName}";
string lines = $"{crateName} v{version} | ↓{dlStr} total (↓{recentStr}/mo)\n{desc.Trim()}\n{link}";
// keywords
if (crate.TryGetProperty("keywords", out var kw) && kw.ValueKind == JsonValueKind.Array)
{
var tags = new List<string>();
foreach (var k in kw.EnumerateArray())
if (k.GetString() is string s) tags.Add(s);
if (tags.Count > 0)
lines += $"\nkeywords: {string.Join(", ", tags)}";
}
CrateCache[name] = (lines, DateTime.UtcNow);
return lines;
}
catch (HttpRequestException)
{
return $"[crates] network error fetching '{name}'";
}
catch (Exception ex)
{
return $"[crates] error: {ex.Message}";
}
}
static string FetchSearch(string query)
{
if (SearchCache.TryGetValue(query, out var cached) && DateTime.UtcNow - cached.fetchedAt < SearchCacheTtl)
return cached.result;
try
{
string url = $"https://crates.io/api/v1/crates?q={Uri.EscapeDataString(query)}&per_page=5";
string json = Http.GetStringAsync(url).GetAwaiter().GetResult();
using var doc = JsonDocument.Parse(json);
if (!doc.RootElement.TryGetProperty("crates", out var crates) || crates.ValueKind != JsonValueKind.Array)
return $"[crates] no results for '{query}'";
var lines = new List<string>();
int idx = 1;
foreach (var c in crates.EnumerateArray())
{
string nm = c.TryGetProperty("name", out var n) ? n.GetString() ?? "?" : "?";
string ver = c.TryGetProperty("max_version", out var mv) ? mv.GetString() ?? "?" : "?";
long dl = c.TryGetProperty("downloads", out var d) ? d.GetInt64() : 0;
string desc = c.TryGetProperty("description", out var ds) ? ds.GetString() ?? "" : "";
string shortDesc = desc.Length > 60 ? desc[..57] + "..." : desc;
lines.Add($"{idx}. {nm} v{ver} ↓{FormatCount(dl)} | {shortDesc}");
idx++;
}
string result = lines.Count == 0
? $"[crates] no results for '{query}'"
: string.Join("\n", lines);
SearchCache[query] = (result, DateTime.UtcNow);
return result;
}
catch (HttpRequestException)
{
return $"[crates] network error searching '{query}'";
}
catch (Exception ex)
{
return $"[crates] error: {ex.Message}";
}
}
static string FormatCount(long n)
{
if (n >= 1_000_000_000) return $"{n / 1_000_000_000.0:F1}B";
if (n >= 1_000_000) return $"{n / 1_000_000.0:F1}M";
if (n >= 1_000) return $"{n / 1_000.0:F0}k";
return n.ToString();
}
static void SendResult(string text, string? id = null)
{
var response = new { type = "result", id, value = text };
Console.WriteLine(JsonSerializer.Serialize(response));
}
}