· 5 years ago · Jul 15, 2020, 07:10 AM
1using System.Collections;
2using System.Collections.Generic;
3using System.Net.Http;
4using UnityEngine;
5using Newtonsoft.Json;
6using System.IO;
7using RestSharp;
8using System;
9using UnityEngine.Networking;
10using System.Runtime.Serialization.Json;
11
12public class LoomApi : MonoBehaviour
13{
14 #region Fields
15 [Space]
16 [SerializeField] [Tooltip("Enable log of progress sending file and recive messages?")] private bool _isLogEnabled = true;
17 [Space]
18 [SerializeField] [Tooltip("Client id key to get _token")] private string _clientId = default;
19 [SerializeField] [Tooltip("Client secret key to get _token")] private string _clientSecret = default;
20 [SerializeField] [Tooltip("_token to get acces to create avatar")] private string _token = "";
21 internal Dictionary<string, string> _tokenResponce;
22 [Space]
23 [Space]
24 [SerializeField] [Tooltip("Path to photo for get avatar")] private string _photoPath = "image.jpeg";
25 internal string _location = default;
26 [SerializeField] private string _avatarId = default;
27 [Space]
28 [Space]
29 [SerializeField] private AvatarItem _avatar;
30 [SerializeField] private Texture2D _textureAvatar;
31 #endregion
32
33 #region Methods
34
35 #region Unity events
36#if DEBUG || UNITY_EDITOR
37 private void Update()
38 {
39 if (Input.GetKeyDown(KeyCode.D))
40 {
41 GetToken();
42 }
43 if (Input.GetKeyDown(KeyCode.F))
44 {
45 CreateAvatar();
46 }
47 if (Input.GetKeyDown(KeyCode.G))
48 {
49 _avatar = new AvatarItem();
50 StartCoroutine(GetRequest());
51 }
52 }
53#endif
54 #endregion
55
56 #region Web methods
57 private async void GetToken()
58 {
59 HttpClient client = new HttpClient();
60 Dictionary<string, string> values = new Dictionary<string, string>()
61 {
62 { "content-type", "application/x-www-form-urlencoded" },
63 { "grant_type", "client_credentials"},
64 { "client_id", _clientId},
65 { "client_secret", _clientSecret},
66 { "audience", @"https://api.loomai.com/"}
67 };
68 FormUrlEncodedContent content = new FormUrlEncodedContent(values);
69 HttpResponseMessage _response = await client.PostAsync("https://auth.loomai.com/oauth/token", content);
70 string _responseString = await _response.Content.ReadAsStringAsync();
71 //Deserialize responce
72 _tokenResponce = JsonConvert.DeserializeObject<Dictionary<string, string>>(_responseString);
73 if (_isLogEnabled)
74 {
75 print(_response.Content);
76 print("access token: " + _tokenResponce["access_token"]);
77 }
78
79 _token = _tokenResponce["access_token"];
80
81 }
82
83 internal void CreateAvatar()
84 {
85 //create avatar by loomai API
86 var _client = new RestClient("https://api.live.loomai.com/v0.5/avatars");
87 _client.Timeout = -1;
88 var _request = new RestRequest(Method.POST);
89 //use loomai _token to get acces on api
90 _request.AddHeader("Authorization", "Bearer " + _tokenResponce["access_token"]);
91 _request.AddHeader("Cookie", "csrf=3d662c5a-69e9-4361-a58f-47f810652b10");
92 //add file to POST method
93 _request.AddFile("image", _photoPath);
94 IRestResponse _response = _client.Execute(_request);
95 foreach (var x in _response.Headers)
96 {
97 //search _location of avatar from responce
98 if (x.Name == "_location")
99 _location = x.Value.ToString();
100 if (x.Name == "X-Loom-Status")
101 _avatarId = x.Value.ToString();
102 if (_isLogEnabled)
103 print(x.Name + ": " + x.Value + ";");
104 }
105 }
106
107 private IEnumerator GetRequest()
108 {
109 int _counter = 20;
110 while ((_avatar == null || _avatar.type != "renderings_preview") && _counter > 0)
111 {
112 //get data from api, get url of render_preview
113 var _client = new RestClient("https://api.live.loomai.com/v0.5/avatars/" + _avatarId + "/attachments");
114 _client.Timeout = -1;
115 var _request = new RestRequest(Method.GET);
116 _request.AddHeader("Authorization", "Bearer " + _token);
117 _request.AddHeader("Cookie", "csrf=3d662c5a-69e9-4361-a58f-47f810652b10");
118 IRestResponse _response = _client.Execute(_request);
119 if (_isLogEnabled)
120 {
121 foreach (var x in _response.Headers)
122 {
123 print(x.Name + ": " + x.Value + ";");
124 }
125 Debug.Log(_response.Content);
126 }
127
128 Entries _avatarData = null;
129 using (var ms = new MemoryStream(_response.RawBytes))
130 {
131 var _serializer = new DataContractJsonSerializer(typeof(Entries));
132 _avatarData = _serializer.ReadObject(ms) as Entries;
133 }
134 foreach (var i in _avatarData.entries)
135 {
136 if (i.type == "renderings_preview")
137 {
138 if (_isLogEnabled)
139 i.GetData();
140 _avatar = i;
141 StartCoroutine(DownloadImage(_avatar.url));
142 break;
143 }
144 if (i.type == "features_texture")
145 _counter++;
146 }
147 _counter--;
148 yield return new WaitForSeconds(1f);
149 }
150 if(_avatar.type != "renderings_preview" && _counter <= 0)
151 {
152 Debug.LogException(new Exception("Error with upload this photo, try another"));
153 }
154 else if(_avatar.type == "renderings_preview")
155 {
156 Debug.Log("avatar url: " + _avatar.url);
157 }
158 }
159 #endregion
160
161 #region Corutins
162 private IEnumerator DownloadImage(string mediaUrl)
163 {
164 UnityWebRequest _webRequest = new UnityWebRequest(mediaUrl);
165 _webRequest.downloadHandler = new DownloadHandlerBuffer();
166 yield return _webRequest.SendWebRequest();
167 byte[] _data = new byte[0];
168 if (_webRequest.isNetworkError || _webRequest.isHttpError)
169 {
170 Debug.Log(_webRequest.error);
171 }
172 else
173 {
174 // Or retrieve results as binary data
175 _data = _webRequest.downloadHandler.data;
176 }
177
178
179 //Write avatar image to Assets/avatarImg.png
180 if (_data.Length > 0)
181 File.WriteAllBytes("Assets/GLTFReader/Test/avatarImg.png", _data);
182 else if (_isLogEnabled)
183 Debug.LogError("There is no file to receive on this url");
184 _webRequest.Dispose();
185 _webRequest = null;
186 }
187
188 #endregion
189
190 #endregion
191
192 #region Additional objects
193 //Avatar data item
194 [Serializable]
195 public class AvatarItem
196 {
197 public long id;
198 public string type;
199 public string name;
200 public string url;
201 public string updated_at;
202
203 public AvatarItem()
204 {
205 this.id = 0;
206 this.type = "";
207 this.name = "";
208 this.url = "";
209 this.updated_at = "";
210 }
211
212 //call after get request data
213 public AvatarItem(string id, string type, string name, string url, string updated_at)
214 {
215 long _id = 0;
216 if (long.TryParse(id, out _id))
217 this.id = _id;
218 else
219 this.id = 0;
220
221 this.type = type;
222 this.name = name;
223 this.url = url;
224 this.updated_at = updated_at;
225 }
226 //Print item Data
227 public void GetData()
228 {
229 print("id of item: " + id);
230 print("type of item: " + type);
231 print("name: " + name);
232 print("url: " + url);
233 print("last update: " + updated_at);
234 }
235
236
237 }
238
239
240 [Serializable]
241 public class Entries
242 {
243 public AvatarItem[] entries;
244 }
245 #endregion
246}