-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathAvatarTemplateFetcher.cs
71 lines (63 loc) · 2.33 KB
/
AvatarTemplateFetcher.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ReadyPlayerMe.Core;
namespace ReadyPlayerMe.AvatarCreator
{
public enum TemplateVersions
{
All,
V1,
V2
}
/// <summary>
/// This class can be used to fetch avatar template data including icon renders from the avatarAPI.
/// </summary>
public class AvatarTemplateFetcher
{
private readonly CancellationToken ctx;
private readonly AvatarAPIRequests avatarAPIRequests;
public AvatarTemplateFetcher(CancellationToken ctx = default)
{
this.ctx = ctx;
avatarAPIRequests = new AvatarAPIRequests(ctx);
}
/// <summary>
/// Fetches all avatar templates without the icon renders via the avatarAPI.
/// </summary>
/// <returns></returns>
public async Task<List<AvatarTemplateData>> GetTemplates()
{
return await avatarAPIRequests.GetAvatarTemplates();
}
/// <summary>
/// Fetches all avatar template data with the icon renders via the avatarAPI.
/// This will wait for all the icons to be downloaded.
/// </summary>
/// <returns></returns>
public async Task<List<AvatarTemplateData>> GetTemplatesWithRenders(Action<AvatarTemplateData> onIconDownloaded = null)
{
return await FetchTemplateRenders(await avatarAPIRequests.GetAvatarTemplates(), onIconDownloaded);
}
/// <summary>
/// Fetches the renders for all the templates provided.
/// </summary>
public async Task<List<AvatarTemplateData>> FetchTemplateRenders(List<AvatarTemplateData> templates, Action<AvatarTemplateData> onIconDownloaded = null)
{
var tasks = templates.Select(async templateData =>
{
var requestDispatcher = new WebRequestDispatcher();
templateData.Texture = await requestDispatcher.DownloadTexture(templateData.ImageUrl, ctx);
onIconDownloaded?.Invoke(templateData);
}).ToList();
while (!tasks.All(x => x.IsCompleted) &&
!ctx.IsCancellationRequested)
{
await Task.Yield();
}
return templates;
}
}
}