-
Notifications
You must be signed in to change notification settings - Fork 2
/
HubClient.cs
392 lines (323 loc) · 11.5 KB
/
HubClient.cs
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Carto.Core;
using Octokit;
namespace mobile_style_editor
{
public class HubClient
{
public const string MasterBranch = "master";
public const string CookieDomain = ".github.com";
public static readonly HubClient Instance = new HubClient();
public EventHandler<EventArgs> FileDownloadStarted;
/*
* Current flow:
*
* (1) Registered OAuth Application on github.com: Carto Style Editor (creates ClientId and ClientSecret),
* that we use to open the Webview at the correct (login) url, from PrepareAuthentication()
*
* (2) If login is successful (two-factor authentication support included),
* we are redirected (currently https://www.carto.com)
* with Login Code as a parameter of the url (?=<code>), that we retrieve from the Webview
*
* (3) The code, as well as the ClientId and ClientSecret are required to get Access Token (CreateAccessToken())
*
* (4) When the token is created, we use it to Authenticate() and store it as a preference (cf. LocalStorage.cs).
*
* This process is only required once, as later we retrieve the stored access token,
* use that to Authenticate() and we can start retrieving repository content
*
* TODO Ask if a user would like their access token to be stored locally,
* it's not nice (and probably illegal) to store and use personal information without their consent
*
* NOTES:
*
* Because of the low rate limit for un-authenticated users,
* authentication is necessary even when accessing public repositories:
* https://developer.github.com/changes/2012-10-14-rate-limit-changes/
*
* This entire complicated login process is required only so each user could authenticate themself,
* for inhouse use-cases we could simply create one access token in one account and use that,
* (https://github.com/settings/tokens) instead of this entire process
*
*/
GitHubClient client;
public bool IsAuthenticated
{
get
{
return client.Credentials.AuthenticationType == AuthenticationType.Oauth && client.Credentials.Password != null;
}
}
HubClient()
{
Initialize();
}
void Initialize()
{
client = new GitHubClient(new ProductHeaderValue("com.carto.style.editor"));
}
public async Task<User> GetCurrentUser()
{
return await client.User.Current();
}
public async Task<Stream> GetUserAvatar(string url)
{
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(url);
return await response.Content.ReadAsStreamAsync();
}
}
public void LogOut()
{
Initialize();
}
public const int PageSize = 25;
const int PageCount = 1;
ApiOptions GetOptions(int page)
{
var options = new ApiOptions();
options.PageSize = PageSize;
options.PageCount = PageCount;
options.StartPage = page;
return options;
}
public void Authenticate(string token)
{
client.Credentials = new Credentials(token);
}
public GithubAuthenticationData PrepareAuthention()
{
Dictionary<string, string> dict = GetCredentials();
string id = dict["client_id"];
string secret = dict["client_secret"];
var request = new OauthLoginRequest(id);
request.Scopes.Add("repo");
var url = client.Oauth.GetGitHubLoginUrl(request);
return new GithubAuthenticationData
{
Id = id,
Secret = secret,
Url = url.AbsoluteUri
};
}
public async Task<string> CreateAccessToken(string id, string secret, string code)
{
var request = new OauthTokenRequest(id, secret, code);
OauthToken token = await client.Oauth.CreateAccessToken(request);
return token.AccessToken;
}
public async Task<IReadOnlyList<Repository>> GetRepositories(int page = -1)
{
/*
* This method only works when user has been Authenticate()-d,
* else there is no "Current" user
*/
if (page != -1)
{
var repositories = await client.Repository.GetAllForCurrent(GetOptions(page));
return repositories;
}
return await client.Repository.GetAllForCurrent();
}
public async Task<IReadOnlyList<Branch>> GetBranches(string owner, string name)
{
return await client.Repository.Branch.GetAll(owner, name);
}
public async Task<IReadOnlyList<RepositoryContent>> GetRepositoryContent(string owner, string name, string branch, string path = null)
{
try
{
if (string.IsNullOrWhiteSpace(path))
{
return await client.Repository.Content.GetAllContentsByRef(owner, name, branch);
}
return await client.Repository.Content.GetAllContentsByRef(owner, name, path, branch);
}
catch (NotFoundException)
{
// For some reasons, Octokit throws an exception when a repository is completely empty.
// In that case, return an empty list
return new System.Collections.ObjectModel.ReadOnlyCollection<RepositoryContent>(new List<RepositoryContent>());
}
}
public async Task<List<RepositoryContent>> GetZipFiles(string owner, string name, string path = null)
{
IReadOnlyList<RepositoryContent> contents;
if (path != null)
{
contents = await client.Repository.Content.GetAllContents(owner, name, path);
}
else
{
contents = await client.Repository.Content.GetAllContents(owner, name);
}
List<RepositoryContent> zipfiles = new List<RepositoryContent>();
foreach (var content in contents)
{
if (content.Name.Contains(Parser.ZipExtension))
{
zipfiles.Add(content);
}
}
return zipfiles;
}
public async Task<DownloadedGithubFile> DownloadFile(RepositoryContent content)
{
string name = content.Name;
string url = content.DownloadUrl.OriginalString;
string path = content.Path;
return await DownloadFile(name, url, path);
}
public async Task<DownloadedGithubFile> DownloadFile(GithubFile content)
{
string name = content.Name;
string url = content.DownloadUrl;
string path = content.Path;
return await DownloadFile(name, url, path);
}
public async Task<DownloadedGithubFile> DownloadFile(string name, string url, string path)
{
DownloadedGithubFile result = new DownloadedGithubFile();;
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(url);
result.Name = name;
result.Path = path;
result.Stream = await response.Content.ReadAsStreamAsync();
}
return result;
}
public async Task<List<DownloadedGithubFile>> DownloadFolder(string owner, string repoName, string branch, List<GithubFile> folder)
{
List<DownloadedGithubFile> files = new List<DownloadedGithubFile>();
foreach (GithubFile file in folder)
{
if (file.IsDirectory)
{
string path = file.Path;
var items = await GetRepositoryContent(owner, repoName, branch, path);
List<GithubFile> innerFolder = items.ToGithubFiles();
List<DownloadedGithubFile> inner = await DownloadFolder(owner, repoName, branch, innerFolder);
files.AddRange(inner);
}
else
{
if (FileDownloadStarted != null)
{
FileDownloadStarted(file.Name, EventArgs.Empty);
}
Console.WriteLine("Downloading: " + file.Name + " (" + file.DownloadUrl + ")");
DownloadedGithubFile downloaded = await DownloadFile(file.Name, file.DownloadUrl, file.Path);
files.Add(downloaded);
}
}
return files;
}
public async Task<string> Update(string owner, string name, string path, string branch, ZipData data, string message)
{
/*
* TODO Perhaps it would be better to pass the List<GithubFiles> when pushing MainController,
* current we're downloading the content again
*/
var contents = await GetRepositoryContent(owner, name, branch, path);
var files = contents.ToGithubFiles();
/*
* TODO We assume that these files exist, so they're updated, not created
* Additionally, we assume the branch exists. No new branch creation is possible
*
* Branch creation possible via https://github.com/octokit/octokit.rb/issues/571,
* something like:
* client.Git.Reference.Create(owner, name, new NewReference("heads/<new-branch-name>", "<sha1-of-something>"));
*/
try
{
foreach (GithubFile file in files)
{
for (int i = 0; i < data.StyleFileNames.Count; i++)
{
string filename = data.StyleFileNames[i];
if (file.Name.Equals(filename) && data.ChangeList.Contains(filename))
{
string content = data.DecompressedFiles[i];
// Full path is required; add the filename
path += "/" + filename;
var request = new UpdateFileRequest(message + " (" + path + ")", content, file.Sha, branch);
var changeSet = await client.Repository.Content.UpdateFile(owner, name, path, request);
return null;
}
}
}
return "You haven't made any changes. What exactly should I commit?";
}
catch (Exception e)
{
return e.Message;
}
}
public async Task<bool> UpdateFile(Repository repository, RepositoryContent file, string content)
{
string url = file.DownloadUrl.AbsolutePath;
string[] split = url.Split('/');
/*
* TODO Splitting like this will not always yield positive results.
* e.g. it'll be longer if the file is in a subfolder
*/
string owner = split[1];
string name = split[2];
string branch = split[3];
string path = split[4];
// Both seem to work now, since the branch has been specified
var request = new UpdateFileRequest("test upload from octokit api", content, file.Sha, branch);
try
{
await client.Repository.Content.UpdateFile(owner, name, path, request);
return true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false;
}
}
public Dictionary<string, string> GetCredentials()
{
var dictionary = new Dictionary<string, string>();
#if __UWP__
Assembly assembly = typeof(Parser).GetTypeInfo().Assembly;
#else
Assembly assembly = Assembly.GetAssembly(typeof(HubClient));
#endif
string[] resources = assembly.GetManifestResourceNames();
string name = "github_info.json";
string path = null;
foreach (var resource in resources)
{
if (resource.Contains(name) && !resource.Contains("with-params"))
{
path = resource;
}
}
using (var stream = assembly.GetManifestResourceStream(path))
{
stream.Position = 0;
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
string result = reader.ReadToEnd();
Variant variant = Variant.FromString(result);
dictionary.Add("username", variant.GetObjectElement("username").String);
dictionary.Add("pa_token", variant.GetObjectElement("pa_token").String);
dictionary.Add("client_id", variant.GetObjectElement("client_id").String);
dictionary.Add("client_secret", variant.GetObjectElement("client_secret").String);
}
}
return dictionary;
}
}
}