-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
BuildDeployPortal.cs
445 lines (400 loc) · 17 KB
/
BuildDeployPortal.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
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
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//
using UnityEngine;
using System.Net;
using System;
using System.IO;
using System.Collections.Generic;
namespace HoloToolkit.Unity
{
/// <summary>
/// Function used to communicate with the device through the REST API
/// </summary>
public class BuildDeployPortal
{
// Consts
public const float TimeOut = 6.0f;
public const int TimeoutMS = (int)(TimeOut * 1000.0f);
public const float MaxWaitTime = 20.0f;
public static readonly string kAPI_ProcessQuery = @"http://{0}/api/resourcemanager/processes";
public static readonly string kAPI_PackagesQuery = @"http://{0}/api/appx/packagemanager/packages";
public static readonly string kAPI_InstallQuery = @"http://{0}/api/app/packagemanager/package";
public static readonly string kAPI_InstallStatusQuery = @"http://{0}/api/app/packagemanager/state";
public static readonly string kAPI_AppQuery = @"http://{0}/api/taskmanager/app";
public static readonly string kAPI_FileQuery = @"http://{0}/api/filesystem/apps/file";
// Enums
public enum AppInstallStatus
{
Invalid,
Installing,
InstallSuccess,
InstallFail
}
// Classes & Structs
public struct ConnectInfo
{
public ConnectInfo(string ip, string user, string password)
{
IP = ip;
User = user;
Password = password;
}
public string IP;
public string User;
public string Password;
}
[Serializable]
public class AppDetails
{
public string Name;
public string PackageFamilyName;
public string PackageFullName;
public int PackageOrigin;
public string PackageRelativeId;
public string Publisher;
}
[Serializable]
public class AppList
{
public AppDetails[] InstalledPackages;
}
[Serializable]
public class ProcessDesc
{
public float CPUUsage;
public string ImageName;
public float PageFileUsage;
public int PrivateWorkingSet;
public int ProcessId;
public int SessionId;
public string UserName;
public int VirtualSize;
public int WorkingSetSize;
}
[Serializable]
public class ProcessList
{
public ProcessDesc[] Processes;
}
[Serializable]
public class InstallStatus
{
public int Code;
public string CodeText;
public string Reason;
public bool Success;
}
[Serializable]
public class Response
{
public string Reason;
}
private class TimeoutWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri uri)
{
WebRequest lWebRequest = base.GetWebRequest(uri);
lWebRequest.Timeout = BuildDeployPortal.TimeoutMS;
((HttpWebRequest)lWebRequest).ReadWriteTimeout = BuildDeployPortal.TimeoutMS;
return lWebRequest;
}
}
// Functions
public static bool IsAppInstalled(string packageFamilyName, ConnectInfo connectInfo)
{
// Look at the device for a matching app name (if not there, then not installed)
return (QueryAppDetails(packageFamilyName, connectInfo) != null);
}
public static bool IsAppRunning(string appName, ConnectInfo connectInfo)
{
using (var client = new TimeoutWebClient())
{
client.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Password);
string query = string.Format(kAPI_ProcessQuery, connectInfo.IP);
string procListJSON = client.DownloadString(query);
ProcessList procList = JsonUtility.FromJson<ProcessList>(procListJSON);
for (int i = 0; i < procList.Processes.Length; ++i)
{
string procName = procList.Processes[i].ImageName;
if (procName.Contains(appName))
{
return true;
}
}
}
return false;
}
public static AppInstallStatus GetInstallStatus(ConnectInfo connectInfo)
{
using (var client = new TimeoutWebClient())
{
client.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Password);
string query = string.Format(kAPI_InstallStatusQuery, connectInfo.IP);
string statusJSON = client.DownloadString(query);
InstallStatus status = JsonUtility.FromJson<InstallStatus>(statusJSON);
if (status == null)
{
return AppInstallStatus.Installing;
}
else if (status.Success == false)
{
Debug.LogError(status.Reason + "(" + status.CodeText + ")");
return AppInstallStatus.InstallFail;
}
return AppInstallStatus.InstallSuccess;
}
}
public static AppDetails QueryAppDetails(string packageFamilyName, ConnectInfo connectInfo)
{
using (var client = new TimeoutWebClient())
{
client.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Password);
string query = string.Format(kAPI_PackagesQuery, connectInfo.IP);
string appListJSON = client.DownloadString(query);
AppList appList = JsonUtility.FromJson<AppList>(appListJSON);
for (int i = 0; i < appList.InstalledPackages.Length; ++i)
{
string thisAppName = appList.InstalledPackages[i].PackageFamilyName;
if (thisAppName.Equals(packageFamilyName, StringComparison.OrdinalIgnoreCase))
{
return appList.InstalledPackages[i];
}
}
}
return null;
}
public static bool InstallApp(string appFullPath, ConnectInfo connectInfo, bool waitForDone = true)
{
try
{
// Calc the cert and dep paths
string fileName = Path.GetFileName(appFullPath);
string certFullPath = Path.ChangeExtension(appFullPath, ".cer");
string certName = Path.GetFileName(certFullPath);
string depPath = Path.GetDirectoryName(appFullPath) + @"\Dependencies\x86\";
// Post it using the REST API
WWWForm form = new WWWForm();
// APPX file
FileStream stream = new FileStream(appFullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
BinaryReader reader = new BinaryReader(stream);
form.AddBinaryData(fileName, reader.ReadBytes((int)reader.BaseStream.Length), fileName);
stream.Close();
// CERT file
stream = new FileStream(certFullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
reader = new BinaryReader(stream);
form.AddBinaryData(certName, reader.ReadBytes((int)reader.BaseStream.Length), certName);
stream.Close();
// Dependencies
FileInfo[] depFiles = (new DirectoryInfo(depPath)).GetFiles();
foreach (FileInfo dep in depFiles)
{
stream = new FileStream(dep.FullName, FileMode.Open, FileAccess.Read, FileShare.Read);
reader = new BinaryReader(stream);
string depFilename = Path.GetFileName(dep.FullName);
form.AddBinaryData(depFilename, reader.ReadBytes((int)reader.BaseStream.Length), depFilename);
stream.Close();
}
// Credentials
Dictionary<string, string> headers = form.headers;
headers["Authorization"] = "Basic " + EncodeTo64(connectInfo.User + ":" + connectInfo.Password);
// Unity places an extra quote in the content-type boundary parameter that the device portal doesn't care for, remove it
if (headers.ContainsKey("Content-Type"))
{
headers["Content-Type"] = headers["Content-Type"].Replace("\"", "");
}
// Query
string query = string.Format(kAPI_InstallQuery, connectInfo.IP);
query += "?package=" + WWW.EscapeURL(fileName);
WWW www = new WWW(query, form.data, headers);
DateTime queryStartTime = DateTime.Now;
while (!www.isDone &&
((DateTime.Now - queryStartTime).TotalSeconds < TimeOut))
{
System.Threading.Thread.Sleep(10);
}
// Give it a short time before checking
System.Threading.Thread.Sleep(250);
// Report
if (www.isDone)
{
if (!string.IsNullOrEmpty(www.error))
{
Debug.LogError(www.error);
}
else if (!string.IsNullOrEmpty(www.text))
{
Debug.Log(JsonUtility.FromJson<Response>(www.text).Reason);
}
else
{
Debug.LogWarning("Completed with null response string");
}
}
// Wait for done (if requested)
DateTime waitStartTime = DateTime.Now;
while (waitForDone &&
((DateTime.Now - waitStartTime).TotalSeconds < MaxWaitTime))
{
AppInstallStatus status = GetInstallStatus(connectInfo);
if (status == AppInstallStatus.InstallSuccess)
{
Debug.Log("Install Successful!");
break;
}
else if (status == AppInstallStatus.InstallFail)
{
Debug.LogError("Install Failed!");
break;
}
// Wait a bit and we'll ask again
System.Threading.Thread.Sleep(1000);
}
}
catch (System.Exception ex)
{
Debug.LogError(ex.ToString());
return false;
}
return true;
}
public static bool UninstallApp(string packageFamilyName, ConnectInfo connectInfo)
{
try
{
// Find the app description
AppDetails appDetails = QueryAppDetails(packageFamilyName, connectInfo);
if (appDetails == null)
{
Debug.LogError(string.Format("Application '{0}' not found", packageFamilyName));
return false;
}
// Setup the command
string query = string.Format(kAPI_InstallQuery, connectInfo.IP);
query += "?package=" + WWW.EscapeURL(appDetails.PackageFullName);
// Use HttpWebRequest for a delete query
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(query);
request.Timeout = TimeoutMS;
request.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Password);
request.Method = "DELETE";
using (HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse())
{
Debug.Log("Response = " + httpResponse.StatusDescription);
httpResponse.Close();
}
}
catch (System.Exception ex)
{
Debug.LogError(ex.ToString());
return false;
}
return true;
}
public static bool LaunchApp(string packageFamilyName, ConnectInfo connectInfo)
{
// Find the app description
AppDetails appDetails = QueryAppDetails(packageFamilyName, connectInfo);
if (appDetails == null)
{
Debug.LogError("Appliation not found");
return false;
}
// Setup the command
string query = string.Format(kAPI_AppQuery, connectInfo.IP);
query += "?appid=" + WWW.EscapeURL(EncodeTo64(appDetails.PackageRelativeId));
query += "&package=" + WWW.EscapeURL(EncodeTo64(appDetails.PackageFamilyName));
// Use HttpWebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(query);
request.Timeout = TimeoutMS;
request.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Password);
request.Method = "POST";
// Query
using (HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse())
{
Debug.Log("Response = " + httpResponse.StatusDescription);
httpResponse.Close();
}
return true;
}
public static bool KillApp(string packageFamilyName, ConnectInfo connectInfo)
{
try
{
// Find the app description
AppDetails appDetails = QueryAppDetails(packageFamilyName, connectInfo);
if (appDetails == null)
{
Debug.LogError("Appliation not found");
return false;
}
// Setup the command
string query = string.Format(kAPI_AppQuery, connectInfo.IP);
query += "?package=" + WWW.EscapeURL(EncodeTo64(appDetails.PackageFullName));
// And send it across
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(query);
request.Timeout = TimeoutMS;
request.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Password);
request.Method = "DELETE";
using (HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse())
{
Debug.Log("Response = " + httpResponse.StatusDescription);
httpResponse.Close();
}
}
catch (System.Exception ex)
{
Debug.LogError(ex.ToString());
return false;
}
return true;
}
public static bool DeviceLogFile_View(string packageFamilyName, ConnectInfo connectInfo)
{
using (var client = new TimeoutWebClient())
{
client.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Password);
try
{
// Setup
string logFile = Application.temporaryCachePath + @"/deviceLog.txt";
// Get the app details...
AppDetails appDetails = QueryAppDetails(packageFamilyName, connectInfo);
if (appDetails == null)
{
Debug.LogError("Application not found on target device (" + packageFamilyName + ")");
return false;
}
// Download the file
string query = string.Format(kAPI_FileQuery, connectInfo.IP);
query += "?knownfolderid=LocalAppData";
query += "&filename=UnityPlayer.log";
query += "&packagefullname=" + appDetails.PackageFullName;
query += "&path=%5C%5CTempState";
client.DownloadFile(query, logFile);
// Open it up in default text editor
System.Diagnostics.Process.Start(logFile);
}
catch (Exception ex)
{
Debug.LogError(ex.ToString());
return false;
}
}
return true;
}
// Helpers
static string EncodeTo64(string toEncode)
{
byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
static string DecodeFrom64(string encodedData)
{
byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);
string returnValue = System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);
return returnValue;
}
}
}