Survivalcraft API 1.8.2.3 v1.8.2.3
Survivalcraft 2.4
载入中...
搜索中...
未找到
SchubExternalContentProvider.cs
浏览该文件的文档.
1using System.Globalization;
2using System.Text;
3using System.Text.Json;
4using System.Text.Json.Nodes;
5using Engine;
7
8namespace Game {
10 public class LoginProcessData {
11 public bool IsTokenFlow;
12
13 public Action Success;
14
15 public Action<Exception> Failure;
16
18
19 public void Succeed(SchubExternalContentProvider provider) {
20 provider.m_loginProcessData = null;
21 Success?.Invoke();
22 }
23
24 public void Fail(SchubExternalContentProvider provider, Exception error) {
25 provider.m_loginProcessData = null;
26 Failure?.Invoke(error);
27 }
28 }
29
30 public const string m_appKey = "1uGA5aADX43p";
31
32 public const string m_appSecret = "9aux67wg5z";
33
35
36 public string DisplayName => "SC中文社区";
37
38 public string Description {
39 get {
40 if (!IsLoggedIn) {
41 return "未登录";
42 }
43 return "登录";
44 }
45 }
46
47 public bool SupportsListing => true;
48
49 public bool SupportsLinks => true;
50
51 public bool RequiresLogin => true;
52
53 public bool IsLoggedIn => !string.IsNullOrEmpty(SettingsManager.ScpboxAccessToken);
54
55 public bool IsLocalProvider => false;
56
61
66
67 public void Login(CancellableProgress progress, Action success, Action<Exception> failure) {
68 try {
69 if (m_loginProcessData != null) {
70 throw new InvalidOperationException("登录已经在进程中");
71 }
73 throw new InvalidOperationException("网络连接错误");
74 }
75 Logout();
76 progress.Cancelled += delegate {
77 if (m_loginProcessData != null) {
78 LoginProcessData loginProcessData = m_loginProcessData;
79 m_loginProcessData = null;
80 loginProcessData.Fail(this, null);
81 }
82 };
83 m_loginProcessData = new LoginProcessData { Progress = progress, Success = success, Failure = failure };
85 }
86 catch (Exception obj) {
87 failure(obj);
88 }
89 }
90
91 public void Logout() {
92 m_loginProcessData = null;
94 SettingsManager.ScpboxUserInfo = string.Empty;
95 }
96
97 public void List(string path, CancellableProgress progress, Action<ExternalContentEntry> success, Action<Exception> failure) {
98 try {
100 Dictionary<string, string> dictionary = new() {
101 { "Authorization", $"Bearer {SettingsManager.ScpboxAccessToken}" }, { "Content-Type", "application/json" }
102 };
103 JsonObject jsonObject = new() {
104 { "path", NormalizePath(path) },
105 { "recursive", false },
106 { "include_media_info", false },
107 { "include_deleted", false },
108 { "include_has_explicit_shared_members", false }
109 };
110 MemoryStream data = new(Encoding.UTF8.GetBytes(jsonObject.ToJsonString()));
112 $"{CommunityServerManager.CurrentChineseInfo.ApiUrl}/com/files/list_folder",
113 null,
114 dictionary,
115 data,
116 progress,
117 delegate(byte[] result) {
118 try {
119 success(JsonElementToEntry(JsonDocument.Parse(result, JsonDocumentReader.DefaultJsonOptions).RootElement));
120 }
121 catch (Exception obj2) {
122 failure(obj2);
123 }
124 },
125 failure
126 );
127 }
128 catch (Exception obj) {
129 failure(obj);
130 }
131 }
132
133 public void Download(string path, CancellableProgress progress, Action<Stream> success, Action<Exception> failure) {
134 try {
136 JsonObject jsonObject = new() { { "path", NormalizePath(path) } };
137 Dictionary<string, string> dictionary = new() {
138 { "Authorization", $"Bearer {SettingsManager.ScpboxAccessToken}" }, { "Dropbox-API-Arg", jsonObject.ToJsonString() }
139 };
141 $"{CommunityServerManager.CurrentChineseInfo.ApiUrl}/com/files/download",
142 null,
143 dictionary,
144 progress,
145 delegate(byte[] result) { success(new MemoryStream(result)); },
146 failure
147 );
148 }
149 catch (Exception obj) {
150 failure(obj);
151 }
152 }
153
154 public void Upload(string path, Stream stream, CancellableProgress progress, Action<string> success, Action<Exception> failure) {
155 try {
157 JsonObject jsonObject = new() { { "path", NormalizePath(path) }, { "mode", "add" }, { "autorename", true }, { "mute", false } };
158 Dictionary<string, string> dictionary = new() {
159 { "Authorization", $"Bearer {SettingsManager.ScpboxAccessToken}" },
160 { "Content-Type", "application/octet-stream" },
161 { "Dropbox-API-Arg", jsonObject.ToJsonString() }
162 };
164 $"{CommunityServerManager.CurrentChineseInfo.ApiUrl}/com/files/upload",
165 null,
166 dictionary,
167 stream,
168 progress,
169 delegate { success(null); },
170 failure
171 );
172 }
173 catch (Exception obj) {
174 failure(obj);
175 }
176 }
177
178 public void Link(string path, CancellableProgress progress, Action<string> success, Action<Exception> failure) {
179 try {
181 Dictionary<string, string> dictionary = new() {
182 { "Authorization", $"Bearer {SettingsManager.ScpboxAccessToken}" }, { "Content-Type", "application/json" }
183 };
184 JsonObject jsonObject = new() { { "path", NormalizePath(path) }, { "short_url", false } };
185 MemoryStream data = new(Encoding.UTF8.GetBytes(jsonObject.ToJsonString()));
187 $"{CommunityServerManager.CurrentChineseInfo.ApiUrl}/com/sharing/create_shared_link",
188 null,
189 dictionary,
190 data,
191 progress,
192 delegate(byte[] result) {
193 try {
194 success(JsonElementToLinkAddress(JsonDocument.Parse(result, JsonDocumentReader.DefaultJsonOptions).RootElement));
195 }
196 catch (Exception obj2) {
197 failure(obj2);
198 }
199 },
200 failure
201 );
202 }
203 catch (Exception obj) {
204 failure(obj);
205 }
206 }
207
208 public void LoginLaunchBrowser() {
209 try {
210 LoginDialog login = new();
211 login.succ = delegate(byte[] a) {
212 StreamReader streamReader = new(new MemoryStream(a));
213 JsonElement json = JsonDocument.Parse(streamReader.ReadToEnd(), JsonDocumentReader.DefaultJsonOptions).RootElement;
214 if (json.GetProperty("code").GetInt32() == 200) {
215 JsonElement data = json.GetProperty("data");
216 SettingsManager.ScpboxAccessToken = data.GetProperty("accessToken").GetString() ?? string.Empty;
217 SettingsManager.ScpboxUserInfo = string.Empty;
218 string nickName = data.GetProperty("nickName").GetString() ?? string.Empty;
219 SettingsManager.ScpboxUserInfo += $"昵称:{nickName}";
220 SettingsManager.ScpboxUserInfo += $"\n账号:{data.GetProperty("user").GetString()}";
221 SettingsManager.ScpboxUserInfo += $"\n登录时间:{TimeZoneInfo.ConvertTimeFromUtc(
222 new DateTime(
223 1970,
224 1,
225 1,
226 0,
227 0,
228 0,
229 DateTimeKind.Utc
230 ).AddSeconds(data.GetProperty("loginTime").GetInt64()),
231 TimeZoneInfo.Local
232 )}";
234 null,
235 new MessageDialog(
237 $"登录成功:{nickName}",
239 null,
240 delegate {
241 m_loginProcessData = null;
242 DialogsManager.HideAllDialogs();
243 }
244 )
245 );
246 }
247 else {
248 login.tip.Text = json.GetProperty("msg").GetString();
250 null,
251 new MessageDialog(
253 $"登录失败:{login.tip.Text}",
255 null,
256 delegate {
257 m_loginProcessData = null;
258 DialogsManager.HideAllDialogs();
259 }
260 )
261 );
262 }
263 };
264 login.fail = delegate(Exception e) {
265 login.tip.Text = e.ToString();
267 null,
268 new MessageDialog(
270 $"登录失败:{e.Message}",
272 null,
273 delegate {
274 m_loginProcessData = null;
275 DialogsManager.HideAllDialogs();
276 }
277 )
278 );
279 };
280 login.cancel = delegate {
281 m_loginProcessData = null;
283 };
284 DialogsManager.ShowDialog(null, login);
285 }
286 catch (Exception error) {
287 m_loginProcessData.Fail(this, error);
288 }
289 }
290
291 public void WindowActivated() {
292 //不需要token验证
293 /*
294 if (m_loginProcessData != null && !m_loginProcessData.IsTokenFlow)
295 {
296 LoginProcessData loginProcessData = m_loginProcessData;
297 m_loginProcessData = null;
298 var dialog = new TextBoxDialog("输入用户登录Token:", "", 256, delegate (string s)
299 {
300 if (s != null)
301 {
302 try
303 {
304 WebManager.Post(m_redirectUri + "/com/oauth2/token", new Dictionary<string, string>
305 {
306 {
307 "code",
308 s.Trim()
309 },
310 {
311 "client_id",
312 "1unnzwkb8igx70k"
313 },
314 {
315 "client_secret",
316 "3i5u3j3141php7u"
317 },
318 {
319 "grant_type",
320 "authorization_code"
321 }
322 }, null, new MemoryStream(), loginProcessData.Progress, delegate (byte[] result)
323 {
324 SettingsManager.ScpboxAccessToken = ((IDictionary<string, object>)WebManager.JsonFromBytes(result))["access_token"].ToString();
325 loginProcessData.Succeed(this);
326 }, delegate (Exception error)
327 {
328 loginProcessData.Fail(this, error);
329 });
330 }
331 catch (Exception error2)
332 {
333 loginProcessData.Fail(this, error2);
334 }
336 else
337 {
338 loginProcessData.Fail(this, null);
339 }
340 });
341 DialogsManager.ShowDialog(null, dialog);
342 }
343 */
344 }
345
346 public void HandleUri(Uri uri) {
347 if (m_loginProcessData == null) {
348 m_loginProcessData = new LoginProcessData { IsTokenFlow = true };
349 }
350 LoginProcessData loginProcessData = m_loginProcessData;
351 m_loginProcessData = null;
352 if (loginProcessData.IsTokenFlow) {
353 try {
354 if (!(uri != null)
355 || string.IsNullOrEmpty(uri.Fragment)) {
356 throw new Exception("不能接收来自Schub的身份验证信息");
357 }
358 Dictionary<string, string> dictionary = WebManager.UrlParametersFromString(uri.Fragment.TrimStart('#'));
359 if (!dictionary.TryGetValue("access_token", out string value)) {
360 if (dictionary.TryGetValue("error", out string value1)) {
361 throw new Exception(value1);
362 }
363 throw new Exception("不能接收来自Schub的身份验证信息");
364 }
366 loginProcessData.Succeed(this);
367 }
368 catch (Exception error) {
369 loginProcessData.Fail(this, error);
370 }
371 }
372 }
373
374 public void VerifyLoggedIn() {
375 if (!IsLoggedIn) {
376 throw new InvalidOperationException("这个应用未登录到Schub中国社区");
377 }
378 }
379
380 public static ExternalContentEntry JsonElementToEntry(JsonElement jsonElement) {
381 ExternalContentEntry externalContentEntry = new();
382 if (jsonElement.TryGetProperty("entries", out JsonElement entries)) {
383 foreach (JsonProperty item in entries.EnumerateObject()) {
384 ExternalContentEntry externalContentEntry2 = new() { Path = item.Value.GetProperty("path_display").GetString() };
385 externalContentEntry2.Type = item.Value.GetProperty(".tag").GetString() == "folder"
386 ? ExternalContentType.Directory
387 : ExternalContentManager.ExtensionToType(Storage.GetExtension(externalContentEntry2.Path));
388 if (externalContentEntry2.Type != ExternalContentType.Directory) {
389 externalContentEntry2.Time = item.Value.TryGetProperty("server_modified", out JsonElement server_modified)
390 ? DateTime.Parse(server_modified.GetString(), CultureInfo.InvariantCulture)
391 : new DateTime(2000, 1, 1);
392 externalContentEntry2.Size = item.Value.TryGetProperty("size", out JsonElement size) ? size.GetInt64() : 0;
393 }
394 externalContentEntry.ChildEntries.Add(externalContentEntry2);
395 }
396 }
397 return externalContentEntry;
398 }
399
400 //获取分享连接
401 public static string JsonElementToLinkAddress(JsonElement jsonElement) {
402 if (jsonElement.TryGetProperty("url", out JsonElement url)) {
403 return $"{url.GetString()?.Replace("www.dropbox.", "dl.dropbox.").Replace("?dl=0", "")}?dl=1";
404 }
405 throw new InvalidOperationException("Share information not found.");
406 }
407
408 public static string NormalizePath(string path) {
409 if (path == "/") {
410 return string.Empty;
411 }
412 if (path.Length > 0
413 && path[0] != '/') {
414 return $"/{path}";
415 }
416 return path;
417 }
418 }
419}
Android.Net.Uri Uri
static Action Activated
static void ShowDialog(ContainerWidget parentWidget, Dialog dialog)
string Path
List< ExternalContentEntry > ChildEntries
ExternalContentType Type
static readonly JsonDocumentOptions DefaultJsonOptions
static Action< Uri > HandleUri
void Fail(SchubExternalContentProvider provider, Exception error)
static ExternalContentEntry JsonElementToEntry(JsonElement jsonElement)
void Upload(string path, Stream stream, CancellableProgress progress, Action< string > success, Action< Exception > failure)
void Link(string path, CancellableProgress progress, Action< string > success, Action< Exception > failure)
static string JsonElementToLinkAddress(JsonElement jsonElement)
void List(string path, CancellableProgress progress, Action< ExternalContentEntry > success, Action< Exception > failure)
void Download(string path, CancellableProgress progress, Action< Stream > success, Action< Exception > failure)
void Login(CancellableProgress progress, Action success, Action< Exception > failure)
static void Post(string address, Dictionary< string, string > parameters, Dictionary< string, string > headers, Stream data, CancellableProgress progress, Action< byte[]> success, Action< Exception > failure)
static bool IsInternetConnectionAvailable()
static void Get(string address, Dictionary< string, string > parameters, Dictionary< string, string > headers, CancellableProgress progress, Action< byte[]> success, Action< Exception > failure)