This repository was archived by the owner on Jun 21, 2023. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathModelService.cs
More file actions
610 lines (540 loc) · 24.6 KB
/
Copy pathModelService.cs
File metadata and controls
610 lines (540 loc) · 24.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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using System.Threading.Tasks;
using Akavache;
using GitHub.Api;
using GitHub.Caches;
using GitHub.Collections;
using GitHub.Extensions;
using GitHub.Extensions.Reactive;
using GitHub.Logging;
using GitHub.Models;
using GitHub.Primitives;
using Octokit;
using Octokit.GraphQL;
using Serilog;
using static Octokit.GraphQL.Variable;
namespace GitHub.Services
{
[Export(typeof(IModelService))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class ModelService : IModelService
{
static readonly ILogger log = LogManager.ForContext<ModelService>();
public const string PRPrefix = "pr";
const string TempFilesDirectory = Info.ApplicationInfo.ApplicationName;
const string CachedFilesDirectory = "CachedFiles";
readonly IBlobCache hostCache;
readonly IAvatarProvider avatarProvider;
public ModelService(
IApiClient apiClient,
IBlobCache hostCache,
IAvatarProvider avatarProvider)
{
this.ApiClient = apiClient;
this.hostCache = hostCache;
this.avatarProvider = avatarProvider;
}
public IApiClient ApiClient { get; }
public IObservable<IAccount> GetCurrentUser()
{
return GetUserFromCache().Select(Create);
}
public IObservable<IAccount> GetUser(string login)
{
return hostCache.GetAndRefreshObject("user|" + login,
() => ApiClient.GetUser(login).Select(AccountCacheItem.Create), TimeSpan.FromMinutes(5), TimeSpan.FromDays(7))
.Select(Create);
}
public IObservable<GitIgnoreItem> GetGitIgnoreTemplates()
{
return Observable.Defer(() =>
hostCache.GetAndFetchLatestFromIndex(CacheIndex.GitIgnoresPrefix, () =>
GetGitIgnoreTemplatesFromApi(),
item => { },
TimeSpan.FromMinutes(1),
TimeSpan.FromDays(7))
)
.Select(Create)
.Catch<GitIgnoreItem, Exception>(e =>
{
log.Error(e, "Failed to retrieve GitIgnoreTemplates");
return Observable.Empty<GitIgnoreItem>();
});
}
public IObservable<LicenseItem> GetLicenses()
{
return Observable.Defer(() =>
hostCache.GetAndFetchLatestFromIndex(CacheIndex.LicensesPrefix, () =>
GetLicensesFromApi(),
item => { },
TimeSpan.FromMinutes(1),
TimeSpan.FromDays(7))
)
.Select(Create)
.Catch<LicenseItem, Exception>(e =>
{
log.Error(e, "Failed to retrieve licenses");
return Observable.Empty<LicenseItem>();
});
}
public IObservable<IReadOnlyList<IAccount>> GetAccounts()
{
return Observable.Zip(
GetUser(),
GetUserOrganizations(),
(user, orgs) => user.Concat(orgs))
.ToReadOnlyList(Create);
}
public IObservable<IRemoteRepositoryModel> GetForks(IRepositoryModel repository)
{
return ApiClient.GetForks(repository.Owner, repository.Name)
.Select(x => new RemoteRepositoryModel(x));
}
IObservable<LicenseCacheItem> GetLicensesFromApi()
{
return ApiClient.GetLicenses()
.WhereNotNull()
.Select(LicenseCacheItem.Create);
}
IObservable<GitIgnoreCacheItem> GetGitIgnoreTemplatesFromApi()
{
return ApiClient.GetGitIgnoreTemplates()
.WhereNotNull()
.Select(GitIgnoreCacheItem.Create);
}
IObservable<IEnumerable<AccountCacheItem>> GetUser()
{
return hostCache.GetAndRefreshObject("user",
() => ApiClient.GetUser().Select(AccountCacheItem.Create), TimeSpan.FromMinutes(5), TimeSpan.FromDays(7))
.TakeLast(1)
.ToList();
}
IObservable<IEnumerable<AccountCacheItem>> GetUserOrganizations()
{
return GetUserFromCache().SelectMany(user =>
hostCache.GetAndRefreshObject(user.Login + "|orgs",
() => ApiClient.GetOrganizations().Select(AccountCacheItem.Create).ToList(),
TimeSpan.FromMinutes(2), TimeSpan.FromDays(7)))
// TODO: Akavache returns the cached version followed by the fresh version if > 2
// minutes have expired from the last request. Here we make sure the latest value is
// returned but it's a hack. We really need a better way to cache this stuff.
.TakeLast(1)
.Catch<IEnumerable<AccountCacheItem>, KeyNotFoundException>(
// This could in theory happen if we try to call this before the user is logged in.
e =>
{
log.Error(e, "Retrieve user organizations failed because user is not stored in the cache");
return Observable.Return(Enumerable.Empty<AccountCacheItem>());
})
.Catch<IEnumerable<AccountCacheItem>, Exception>(e =>
{
log.Error(e, "Retrieve user organizations failed");
return Observable.Return(Enumerable.Empty<AccountCacheItem>());
});
}
public IObservable<IReadOnlyList<IRemoteRepositoryModel>> GetRepositories()
{
return GetUserRepositories(RepositoryType.Owner)
.TakeLast(1)
.Concat(GetUserRepositories(RepositoryType.Member).TakeLast(1))
.Concat(GetAllRepositoriesForAllOrganizations());
}
IObservable<AccountCacheItem> GetUserFromCache()
{
return Observable.Defer(() => hostCache.GetObject<AccountCacheItem>("user"));
}
/// <summary>
/// Gets a collection of Pull Requests. If you want to refresh existing data, pass a collection in
/// </summary>
/// <param name="repo"></param>
/// <param name="collection"></param>
/// <returns></returns>
public ITrackingCollection<IPullRequestModel> GetPullRequests(IRepositoryModel repo,
ITrackingCollection<IPullRequestModel> collection)
{
// Since the api to list pull requests returns all the data for each pr, cache each pr in its own entry
// and also cache an index that contains all the keys for each pr. This way we can fetch prs in bulk
// but also individually without duplicating information. We store things in a custom observable collection
// that checks whether an item is being updated (coming from the live stream after being retrieved from cache)
// and replaces it instead of appending, so items get refreshed in-place as they come in.
var keyobs = GetUserFromCache()
.Select(user => string.Format(CultureInfo.InvariantCulture, "{0}|{1}:{2}", CacheIndex.PRPrefix, repo.Owner, repo.Name));
var source = Observable.Defer(() => keyobs
.SelectMany(key =>
hostCache.GetAndFetchLatestFromIndex(key, () =>
ApiClient.GetPullRequestsForRepository(repo.CloneUrl.Owner, repo.CloneUrl.RepositoryName)
.Select(PullRequestCacheItem.Create),
item =>
{
if (collection.Disposed) return;
// this could blow up due to the collection being disposed somewhere else
try { collection.RemoveItem(Create(item)); }
catch (ObjectDisposedException) { }
},
TimeSpan.Zero,
TimeSpan.FromDays(7))
)
.Select(Create)
);
collection.Listen(source);
return collection;
}
public IObservable<IPullRequestModel> GetPullRequest(string owner, string name, int number)
{
throw new NotImplementedException();
}
public IObservable<IRemoteRepositoryModel> GetRepository(string owner, string repo)
{
var keyobs = GetUserFromCache()
.Select(user => string.Format(CultureInfo.InvariantCulture, "{0}|{1}|{2}/{3}", CacheIndex.RepoPrefix, user.Login, owner, repo));
return Observable.Defer(() => keyobs
.SelectMany(key =>
hostCache.GetAndFetchLatest(
key,
() => ApiClient.GetRepository(owner, repo).Select(RepositoryCacheItem.Create))
.Select(Create)));
}
public ITrackingCollection<IRemoteRepositoryModel> GetRepositories(ITrackingCollection<IRemoteRepositoryModel> collection)
{
var keyobs = GetUserFromCache()
.Select(user => string.Format(CultureInfo.InvariantCulture, "{0}|{1}", CacheIndex.RepoPrefix, user.Login));
var source = Observable.Defer(() => keyobs
.SelectMany(key =>
hostCache.GetAndFetchLatestFromIndex(key, () =>
ApiClient.GetRepositories()
.Select(RepositoryCacheItem.Create),
item =>
{
if (collection.Disposed) return;
// this could blow up due to the collection being disposed somewhere else
try { collection.RemoveItem(Create(item)); }
catch (ObjectDisposedException) { }
},
TimeSpan.FromMinutes(5),
TimeSpan.FromDays(1))
)
.Select(Create)
);
collection.Listen(source);
return collection;
}
public IObservable<IPullRequestModel> CreatePullRequest(ILocalRepositoryModel sourceRepository, IRepositoryModel targetRepository,
IBranch sourceBranch, IBranch targetBranch,
string title, string body)
{
var keyobs = GetUserFromCache()
.Select(user => string.Format(CultureInfo.InvariantCulture, "{0}|{1}:{2}", CacheIndex.PRPrefix, targetRepository.Owner, targetRepository.Name));
return Observable.Defer(() => keyobs
.SelectMany(key =>
hostCache.PutAndUpdateIndex(key, () =>
ApiClient.CreatePullRequest(
new NewPullRequest(title,
string.Format(CultureInfo.InvariantCulture, "{0}:{1}", sourceRepository.Owner, sourceBranch.Name),
targetBranch.Name)
{ Body = body },
targetRepository.Owner,
targetRepository.Name)
.Select(PullRequestCacheItem.Create)
,
TimeSpan.FromMinutes(30))
)
.Select(Create)
);
}
public IObservable<Unit> InvalidateAll()
{
return hostCache.InvalidateAll().ContinueAfter(() => hostCache.Vacuum());
}
public IObservable<string> GetFileContents(IRepositoryModel repo, string commitSha, string path, string fileSha)
{
return Observable.Defer(() => Task.Run(async () =>
{
// Store cached file contents a the temp directory so they can be deleted by disk cleanup etc.
var tempDir = Path.Combine(Path.GetTempPath(), TempFilesDirectory, CachedFilesDirectory, fileSha.Substring(0, 2));
var tempFile = Path.Combine(tempDir, Path.GetFileNameWithoutExtension(path) + '@' + fileSha + Path.GetExtension(path));
if (!File.Exists(tempFile))
{
var contents = await ApiClient.GetFileContents(repo.Owner, repo.Name, commitSha, path);
Directory.CreateDirectory(tempDir);
File.WriteAllBytes(tempFile, Convert.FromBase64String(contents.EncodedContent));
}
return Observable.Return(tempFile);
}));
}
IObservable<IReadOnlyList<IRemoteRepositoryModel>> GetUserRepositories(RepositoryType repositoryType)
{
return Observable.Defer(() => GetUserFromCache().SelectMany(user =>
hostCache.GetAndRefreshObject(string.Format(CultureInfo.InvariantCulture, "{0}|{1}:repos", user.Login, repositoryType),
() => GetUserRepositoriesFromApi(repositoryType),
TimeSpan.FromMinutes(2),
TimeSpan.FromDays(7)))
.ToReadOnlyList(Create))
.Catch<IReadOnlyList<IRemoteRepositoryModel>, KeyNotFoundException>(
// This could in theory happen if we try to call this before the user is logged in.
e =>
{
log.Error(e,
"Retrieving {RepositoryType} user repositories failed because user is not stored in the cache",
repositoryType);
return Observable.Return(new IRemoteRepositoryModel[] {});
});
}
IObservable<IEnumerable<RepositoryCacheItem>> GetUserRepositoriesFromApi(RepositoryType repositoryType)
{
return ApiClient.GetUserRepositories(repositoryType)
.WhereNotNull()
.Select(RepositoryCacheItem.Create)
.ToList()
.Catch<IEnumerable<RepositoryCacheItem>, Exception>(_ => Observable.Return(Enumerable.Empty<RepositoryCacheItem>()));
}
IObservable<IReadOnlyList<IRemoteRepositoryModel>> GetAllRepositoriesForAllOrganizations()
{
return GetUserOrganizations()
.SelectMany(org => org.ToObservable())
.SelectMany(org => GetOrganizationRepositories(org.Login).TakeLast(1));
}
IObservable<IReadOnlyList<IRemoteRepositoryModel>> GetOrganizationRepositories(string organization)
{
return Observable.Defer(() => GetUserFromCache().SelectMany(user =>
hostCache.GetAndRefreshObject(string.Format(CultureInfo.InvariantCulture, "{0}|{1}|repos", user.Login, organization),
() => ApiClient.GetRepositoriesForOrganization(organization).Select(
RepositoryCacheItem.Create).ToList(),
TimeSpan.FromMinutes(2),
TimeSpan.FromDays(7)))
.ToReadOnlyList(Create))
.Catch<IReadOnlyList<IRemoteRepositoryModel>, KeyNotFoundException>(
// This could in theory happen if we try to call this before the user is logged in.
e =>
{
log.Error(e, "Retrieveing {Organization} org repositories failed because user is not stored in the cache",
organization);
return Observable.Return(new IRemoteRepositoryModel[] {});
});
}
public IObservable<IBranch> GetBranches(IRepositoryModel repo)
{
var keyobs = GetUserFromCache()
.Select(user => string.Format(CultureInfo.InvariantCulture, "{0}|{1}|branch", user.Login, repo.Name));
return Observable.Defer(() => keyobs
.SelectMany(key => ApiClient.GetBranches(repo.CloneUrl.Owner, repo.CloneUrl.RepositoryName)))
.Select(x => new BranchModel(x, repo));
}
static GitIgnoreItem Create(GitIgnoreCacheItem item)
{
return GitIgnoreItem.Create(item.Name);
}
static LicenseItem Create(LicenseCacheItem licenseCacheItem)
{
return new LicenseItem(licenseCacheItem.Key, licenseCacheItem.Name);
}
IAccount Create(AccountCacheItem accountCacheItem)
{
return new Models.Account(
accountCacheItem.Login,
accountCacheItem.IsUser,
accountCacheItem.IsEnterprise,
accountCacheItem.OwnedPrivateRepositoriesCount,
accountCacheItem.PrivateRepositoriesInPlanCount,
accountCacheItem.AvatarUrl,
avatarProvider.GetAvatar(accountCacheItem));
}
IAccount Create(string login, string avatarUrl)
{
return new Models.Account(
login,
true,
false,
0,
0,
avatarUrl,
avatarProvider.GetAvatar(avatarUrl));
}
IRemoteRepositoryModel Create(RepositoryCacheItem item)
{
return new RemoteRepositoryModel(
item.Id,
item.Name,
new UriString(item.CloneUrl),
item.Private,
item.Fork,
Create(item.Owner),
item.Parent != null ? Create(item.Parent) : null)
{
CreatedAt = item.CreatedAt,
UpdatedAt = item.UpdatedAt
};
}
GitReferenceModel Create(GitReferenceCacheItem item)
{
return new GitReferenceModel(item.Ref, item.Label, item.Sha, item.RepositoryCloneUrl);
}
IPullRequestModel Create(PullRequestCacheItem prCacheItem)
{
return new PullRequestModel(
prCacheItem.Number,
prCacheItem.Title,
Create(prCacheItem.Author),
prCacheItem.CreatedAt,
prCacheItem.UpdatedAt)
{
Assignee = prCacheItem.Assignee != null ? Create(prCacheItem.Assignee) : null,
Base = Create(prCacheItem.Base),
Body = prCacheItem.Body ?? string.Empty,
CommentCount = prCacheItem.CommentCount,
CommitCount = prCacheItem.CommitCount,
CreatedAt = prCacheItem.CreatedAt,
Head = Create(prCacheItem.Head),
State = prCacheItem.State.HasValue ?
prCacheItem.State.Value :
prCacheItem.IsOpen.Value ? PullRequestStateEnum.Open : PullRequestStateEnum.Closed,
};
}
public IObservable<Unit> InsertUser(AccountCacheItem user)
{
return hostCache.InsertObject("user", user);
}
protected virtual void Dispose(bool disposing)
{}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
static GitHub.Models.PullRequestReviewState FromGraphQL(Octokit.GraphQL.Model.PullRequestReviewState s)
{
return (GitHub.Models.PullRequestReviewState)s;
}
public class GitIgnoreCacheItem : CacheItem
{
public static GitIgnoreCacheItem Create(string ignore)
{
return new GitIgnoreCacheItem { Key = ignore, Name = ignore, Timestamp = DateTime.Now };
}
public string Name { get; set; }
}
public class LicenseCacheItem : CacheItem
{
public static LicenseCacheItem Create(LicenseMetadata licenseMetadata)
{
return new LicenseCacheItem { Key = licenseMetadata.Key, Name = licenseMetadata.Name, Timestamp = DateTime.Now };
}
public string Name { get; set; }
}
public class RepositoryCacheItem : CacheItem
{
public static RepositoryCacheItem Create(Repository apiRepository)
{
return new RepositoryCacheItem(apiRepository);
}
public RepositoryCacheItem() {}
public RepositoryCacheItem(Repository apiRepository)
{
Id = apiRepository.Id;
Name = apiRepository.Name;
Owner = AccountCacheItem.Create(apiRepository.Owner);
CloneUrl = apiRepository.CloneUrl;
Private = apiRepository.Private;
Fork = apiRepository.Fork;
Key = string.Format(CultureInfo.InvariantCulture, "{0}/{1}", Owner.Login, Name);
CreatedAt = apiRepository.CreatedAt;
UpdatedAt = apiRepository.UpdatedAt;
Timestamp = apiRepository.UpdatedAt;
Parent = apiRepository.Parent != null ? new RepositoryCacheItem(apiRepository.Parent) : null;
}
public long Id { get; set; }
public string Name { get; set; }
public AccountCacheItem Owner { get; set; }
public string CloneUrl { get; set; }
public bool Private { get; set; }
public bool Fork { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset UpdatedAt { get; set; }
public RepositoryCacheItem Parent { get; set; }
}
public class PullRequestCacheItem : CacheItem
{
public static PullRequestCacheItem Create(PullRequest pr)
{
return new PullRequestCacheItem(pr);
}
public PullRequestCacheItem() {}
public PullRequestCacheItem(PullRequest pr)
{
Title = pr.Title;
Number = pr.Number;
Base = new GitReferenceCacheItem
{
Label = pr.Base.Label,
Ref = pr.Base.Ref,
Sha = pr.Base.Sha,
RepositoryCloneUrl = pr.Base.Repository.CloneUrl,
};
Head = new GitReferenceCacheItem
{
Label = pr.Head.Label,
Ref = pr.Head.Ref,
Sha = pr.Head.Sha,
RepositoryCloneUrl = pr.Head.Repository?.CloneUrl
};
CommentCount = pr.Comments;
CommitCount = pr.Commits;
Author = new AccountCacheItem(pr.User);
Assignee = pr.Assignee != null ? new AccountCacheItem(pr.Assignee) : null;
CreatedAt = pr.CreatedAt;
UpdatedAt = pr.UpdatedAt;
Body = pr.Body;
State = GetState(pr);
IsOpen = pr.State == ItemState.Open;
Merged = pr.Merged;
Key = Number.ToString(CultureInfo.InvariantCulture);
Timestamp = UpdatedAt;
}
public string Title {get; set; }
public int Number { get; set; }
public GitReferenceCacheItem Base { get; set; }
public GitReferenceCacheItem Head { get; set; }
public int CommentCount { get; set; }
public int CommitCount { get; set; }
public AccountCacheItem Author { get; set; }
public AccountCacheItem Assignee { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset UpdatedAt { get; set; }
public string Body { get; set; }
// Nullable for compatibility with old caches.
public PullRequestStateEnum? State { get; set; }
// This fields exists only for compatibility with old caches. The State property should be used.
public bool? IsOpen { get; set; }
public bool? Merged { get; set; }
static PullRequestStateEnum GetState(PullRequest pullRequest)
{
if (pullRequest.State == ItemState.Open)
{
return PullRequestStateEnum.Open;
}
else if (pullRequest.Merged)
{
return PullRequestStateEnum.Merged;
}
else
{
return PullRequestStateEnum.Closed;
}
}
}
public class GitReferenceCacheItem
{
public string Ref { get; set; }
public string Label { get; set; }
public string Sha { get; set; }
public string RepositoryCloneUrl { get; set; }
}
}
}