-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
555 lines (462 loc) · 18.6 KB
/
Program.cs
File metadata and controls
555 lines (462 loc) · 18.6 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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
using System.IO.Compression;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
internal static class Program
{
private const string DefaultBaseUrl = "http://127.0.0.1:7071";
private const string DefaultRoutePrefix = "api";
private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
public static async Task<int> Main(string[] args)
{
try
{
var parsed = CliArgs.Parse(args);
var command = parsed.Command ?? "execute";
return command switch
{
"execute" => await ExecuteAsync(parsed),
"get-title-token" => await GetTitleTokenAsync(parsed),
"login-custom-id" => await LoginCustomIdAsync(parsed),
"help" or "--help" or "-h" => PrintHelpAndReturn(),
_ => ExitWithError($"Unknown command: {command}")
};
}
catch (Exception ex)
{
Console.Error.WriteLine($"[playfab-mini-client] {ex.Message}");
return 1;
}
}
private static int PrintHelpAndReturn()
{
Console.WriteLine("""
PlayFabMiniClient
Commands:
execute Executes local CloudScript/ExecuteFunction endpoint.
get-title-token Gets a title entity token using --title-id and --dev-secret-key.
login-custom-id Logs into PlayFab Client API and returns entity token + entity key.
Common Execute Options:
--function <name> Function name to invoke. Required.
--parameter-json <json> FunctionParameter JSON. Default: {}
--base-url <url> Local host base URL. Default: http://127.0.0.1:7071
--route-prefix <prefix> Route prefix used by local functions host. Default: api
--title-id <id> PlayFab title ID (required for PlayFab API calls)
--dev-secret-key <key> PlayFab secret key (required for get-title-token and --auth title)
--cloud-name <name> PlayFab cloud segment for host (<title>.<cloud>.playfabapi.com)
--entity-token <token> X-EntityToken header value
--entity-id <id> ExecuteFunctionRequest.Entity.Id
--entity-type <type> ExecuteFunctionRequest.Entity.Type
--auth <none|title|player-custom-id> Auth mode. Default: none
--custom-id <id> Required when --auth player-custom-id
--create-account <true|false> LoginWithCustomID CreateAccount. Default: true
--gzip-body Gzip request body and set Content-Encoding: gzip
--accept-gzip <true|false> Send Accept-Encoding: gzip header. Default: true
--expect-http-status <code> Assert HTTP status code. Default: 200
--expect-function-result-json <json> Assert data.FunctionResult exact JSON equality
--output <path> Write raw response body to file
Required args for PlayFab auth/API calls:
--title-id
--dev-secret-key (title token only)
""");
return 0;
}
private static async Task<int> ExecuteAsync(CliArgs args)
{
var functionName = args.Get("function");
if (string.IsNullOrWhiteSpace(functionName))
{
return ExitWithError("Missing --function");
}
var baseUrl = args.Get("base-url") ?? DefaultBaseUrl;
var routePrefix = args.Get("route-prefix") ?? DefaultRoutePrefix;
var parameterJson = args.Get("parameter-json") ?? "{}";
var authMode = (args.Get("auth") ?? "none").Trim().ToLowerInvariant();
var expectHttpStatus = args.GetInt("expect-http-status") ?? 200;
var expectResultJson = args.Get("expect-function-result-json");
var outputPath = args.Get("output");
var titleId = args.Get("title-id");
var devSecretKey = args.Get("dev-secret-key");
var cloudName = args.Get("cloud-name");
var acceptGzip = args.GetBool("accept-gzip", defaultValue: true);
var gzipBody = args.HasFlag("gzip-body");
var entityToken = args.Get("entity-token");
var entityId = args.Get("entity-id");
var entityType = args.Get("entity-type");
using var http = CreateHttpClient();
if (authMode == "title")
{
titleId = RequireOption(titleId, "title-id", "--auth title");
devSecretKey = RequireOption(devSecretKey, "dev-secret-key", "--auth title");
entityToken = await FetchTitleEntityTokenAsync(http, titleId, devSecretKey, cloudName);
}
else if (authMode == "player-custom-id")
{
var customId = args.Get("custom-id");
if (string.IsNullOrWhiteSpace(customId))
{
return ExitWithError("--custom-id is required when --auth player-custom-id");
}
titleId = RequireOption(titleId, "title-id", "--auth player-custom-id");
var createAccount = args.GetBool("create-account", defaultValue: true);
var login = await LoginWithCustomIdInternalAsync(http, titleId, cloudName, customId, createAccount);
entityToken = login.EntityToken;
entityId = login.Entity?.Id;
entityType = login.Entity?.Type;
}
else if (authMode != "none")
{
return ExitWithError("--auth must be one of: none, title, player-custom-id");
}
var executePayload = new ExecuteFunctionRequest
{
FunctionName = functionName,
FunctionParameter = ParseJsonToElement(parameterJson),
Entity = string.IsNullOrWhiteSpace(entityId) || string.IsNullOrWhiteSpace(entityType)
? null
: new EntityKey { Id = entityId, Type = entityType }
};
var endpoint = BuildLocalExecuteFunctionEndpoint(baseUrl, routePrefix);
var payloadBytes = JsonSerializer.SerializeToUtf8Bytes(executePayload, JsonOptions);
using var request = new HttpRequestMessage(HttpMethod.Post, endpoint);
if (acceptGzip)
{
request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
}
if (!string.IsNullOrWhiteSpace(entityToken))
{
request.Headers.TryAddWithoutValidation("X-EntityToken", entityToken);
}
if (gzipBody)
{
payloadBytes = Gzip(payloadBytes);
request.Content = new ByteArrayContent(payloadBytes);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content.Headers.ContentEncoding.Add("gzip");
}
else
{
request.Content = new ByteArrayContent(payloadBytes);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
}
using var response = await http.SendAsync(request);
var rawBody = await response.Content.ReadAsStringAsync();
if (!string.IsNullOrWhiteSpace(outputPath))
{
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(outputPath))!);
await File.WriteAllTextAsync(outputPath, rawBody, Encoding.UTF8);
}
if ((int)response.StatusCode != expectHttpStatus)
{
Console.Error.WriteLine(rawBody);
return ExitWithError($"HTTP status assertion failed. Expected {expectHttpStatus}, got {(int)response.StatusCode}");
}
Console.WriteLine(rawBody);
if (!string.IsNullOrWhiteSpace(expectResultJson))
{
var expectedNode = JsonNode.Parse(expectResultJson);
var envelope = JsonSerializer.Deserialize<PlayFabEnvelope<ExecuteFunctionResult>>(rawBody, JsonOptions)
?? throw new InvalidOperationException("Failed to deserialize ExecuteFunction response envelope.");
var actualNode = envelope.Data?.FunctionResult is null
? null
: JsonNode.Parse(envelope.Data.FunctionResult.Value.GetRawText());
if (!JsonNode.DeepEquals(expectedNode, actualNode))
{
return ExitWithError("FunctionResult assertion failed (JSON not equal).");
}
}
return 0;
}
private static async Task<int> GetTitleTokenAsync(CliArgs args)
{
var titleId = RequireOption(args.Get("title-id"), "title-id", "get-title-token");
var devSecretKey = RequireOption(args.Get("dev-secret-key"), "dev-secret-key", "get-title-token");
var cloudName = args.Get("cloud-name");
using var http = CreateHttpClient();
var token = await FetchTitleEntityTokenAsync(http, titleId, devSecretKey, cloudName);
var asJson = args.GetBool("json", defaultValue: false);
if (asJson)
{
Console.WriteLine(JsonSerializer.Serialize(new { entityToken = token }, JsonOptions));
}
else
{
Console.WriteLine(token);
}
return 0;
}
private static async Task<int> LoginCustomIdAsync(CliArgs args)
{
var titleId = RequireOption(args.Get("title-id"), "title-id", "login-custom-id");
var cloudName = args.Get("cloud-name");
var customId = args.Get("custom-id");
if (string.IsNullOrWhiteSpace(customId))
{
return ExitWithError("Missing --custom-id");
}
var createAccount = args.GetBool("create-account", defaultValue: true);
using var http = CreateHttpClient();
var login = await LoginWithCustomIdInternalAsync(http, titleId, cloudName, customId, createAccount);
Console.WriteLine(JsonSerializer.Serialize(login, JsonOptions));
return 0;
}
private static HttpClient CreateHttpClient()
{
var handler = new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
return new HttpClient(handler)
{
Timeout = TimeSpan.FromSeconds(60)
};
}
private static string BuildLocalExecuteFunctionEndpoint(string baseUrl, string routePrefix)
{
var trimmedBase = baseUrl.TrimEnd('/');
var trimmedPrefix = routePrefix.Trim('/');
return string.IsNullOrWhiteSpace(trimmedPrefix)
? $"{trimmedBase}/CloudScript/ExecuteFunction"
: $"{trimmedBase}/{trimmedPrefix}/CloudScript/ExecuteFunction";
}
private static JsonElement ParseJsonToElement(string json)
{
using var doc = JsonDocument.Parse(json);
return doc.RootElement.Clone();
}
private static byte[] Gzip(byte[] bytes)
{
using var output = new MemoryStream();
using (var gzip = new GZipStream(output, CompressionLevel.Fastest, leaveOpen: true))
{
gzip.Write(bytes, 0, bytes.Length);
}
return output.ToArray();
}
private static async Task<string> FetchTitleEntityTokenAsync(HttpClient http, string titleId, string devSecretKey, string? cloudName)
{
var endpoint = BuildPlayFabEndpoint(titleId, cloudName, "/Authentication/GetEntityToken");
var body = "{}";
using var request = new HttpRequestMessage(HttpMethod.Post, endpoint)
{
Content = new StringContent(body, Encoding.UTF8, "application/json")
};
request.Headers.TryAddWithoutValidation("X-SecretKey", devSecretKey);
using var response = await http.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
var envelope = JsonSerializer.Deserialize<PlayFabEnvelope<GetEntityTokenData>>(content, JsonOptions)
?? throw new InvalidOperationException("Could not deserialize GetEntityToken response.");
if (envelope.Data?.EntityToken is null)
{
throw new InvalidOperationException($"GetEntityToken failed. Status={envelope.Status}, Code={envelope.Code}, Body={content}");
}
return envelope.Data.EntityToken;
}
private static async Task<LoginCustomIdResult> LoginWithCustomIdInternalAsync(HttpClient http, string titleId, string? cloudName, string customId, bool createAccount)
{
var endpoint = BuildPlayFabEndpoint(titleId, cloudName, "/Client/LoginWithCustomID");
var loginRequest = new
{
TitleId = titleId,
CustomId = customId,
CreateAccount = createAccount,
InfoRequestParameters = new { GetPlayerProfile = true }
};
using var request = new HttpRequestMessage(HttpMethod.Post, endpoint)
{
Content = new StringContent(JsonSerializer.Serialize(loginRequest, JsonOptions), Encoding.UTF8, "application/json")
};
using var response = await http.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
var envelope = JsonSerializer.Deserialize<PlayFabEnvelope<LoginWithCustomIdData>>(content, JsonOptions)
?? throw new InvalidOperationException("Could not deserialize LoginWithCustomID response.");
if (envelope.Data?.EntityToken?.EntityToken is null)
{
throw new InvalidOperationException($"LoginWithCustomID failed. Status={envelope.Status}, Code={envelope.Code}, Body={content}");
}
return new LoginCustomIdResult
{
PlayFabId = envelope.Data.PlayFabId,
SessionTicket = envelope.Data.SessionTicket,
EntityToken = envelope.Data.EntityToken.EntityToken,
Entity = envelope.Data.EntityToken.Entity
};
}
private static string BuildPlayFabEndpoint(string titleId, string? cloudName, string endpoint)
{
var hostBuilder = new StringBuilder();
hostBuilder.Append(titleId).Append('.');
if (!string.IsNullOrWhiteSpace(cloudName))
{
hostBuilder.Append(cloudName).Append('.');
}
hostBuilder.Append("playfabapi.com");
return $"https://{hostBuilder}{endpoint}";
}
private static int ExitWithError(string message)
{
Console.Error.WriteLine($"[playfab-mini-client] {message}");
return 1;
}
private static string RequireOption(string? value, string optionName, string context)
{
if (string.IsNullOrWhiteSpace(value))
{
throw new InvalidOperationException($"Missing --{optionName} for {context}.");
}
return value;
}
}
internal sealed class CliArgs
{
private readonly Dictionary<string, string?> _options;
public string? Command { get; }
private CliArgs(string? command, Dictionary<string, string?> options)
{
Command = command;
_options = options;
}
public static CliArgs Parse(string[] args)
{
string? command = null;
var options = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
for (var i = 0; i < args.Length; i++)
{
var token = args[i];
if (!token.StartsWith("--", StringComparison.Ordinal))
{
if (command is null)
{
command = token;
}
else
{
throw new InvalidOperationException($"Unexpected positional argument: {token}");
}
continue;
}
var withoutPrefix = token[2..];
var eqIndex = withoutPrefix.IndexOf('=');
if (eqIndex >= 0)
{
var key = withoutPrefix[..eqIndex];
var value = withoutPrefix[(eqIndex + 1)..];
options[key] = value;
continue;
}
if (i + 1 < args.Length && !args[i + 1].StartsWith("--", StringComparison.Ordinal))
{
options[withoutPrefix] = args[i + 1];
i++;
}
else
{
options[withoutPrefix] = "true";
}
}
return new CliArgs(command, options);
}
public string? Get(string key)
{
return _options.TryGetValue(key, out var value) ? value : null;
}
public bool HasFlag(string key)
{
return GetBool(key, defaultValue: false);
}
public bool GetBool(string key, bool defaultValue)
{
var value = Get(key);
if (value is null)
{
return defaultValue;
}
if (bool.TryParse(value, out var parsed))
{
return parsed;
}
if (value == "1")
{
return true;
}
if (value == "0")
{
return false;
}
throw new InvalidOperationException($"Option --{key} must be a boolean (true/false).");
}
public int? GetInt(string key)
{
var value = Get(key);
if (value is null)
{
return null;
}
if (int.TryParse(value, out var parsed))
{
return parsed;
}
throw new InvalidOperationException($"Option --{key} must be an integer.");
}
}
internal sealed class EntityKey
{
public string? Id { get; set; }
public string? Type { get; set; }
}
internal sealed class ExecuteFunctionRequest
{
public EntityKey? Entity { get; set; }
public string? FunctionName { get; set; }
public JsonElement FunctionParameter { get; set; }
public bool? GeneratePlayStreamEvent { get; set; }
}
internal sealed class ExecuteFunctionResult
{
public int ExecutionTimeMilliseconds { get; set; }
public string? FunctionName { get; set; }
public JsonElement? FunctionResult { get; set; }
public bool? FunctionResultTooLarge { get; set; }
}
internal sealed class PlayFabEnvelope<T>
{
[JsonPropertyName("code")]
public int Code { get; set; }
[JsonPropertyName("status")]
public string? Status { get; set; }
[JsonPropertyName("data")]
public T? Data { get; set; }
[JsonPropertyName("error")]
public string? Error { get; set; }
[JsonPropertyName("errorMessage")]
public string? ErrorMessage { get; set; }
}
internal sealed class GetEntityTokenData
{
public string? EntityToken { get; set; }
}
internal sealed class LoginWithCustomIdData
{
public string? PlayFabId { get; set; }
public string? SessionTicket { get; set; }
public EntityTokenResult? EntityToken { get; set; }
}
internal sealed class EntityTokenResult
{
public string? EntityToken { get; set; }
public EntityKey? Entity { get; set; }
}
internal sealed class LoginCustomIdResult
{
public string? PlayFabId { get; set; }
public string? SessionTicket { get; set; }
public string? EntityToken { get; set; }
public EntityKey? Entity { get; set; }
}