-
Notifications
You must be signed in to change notification settings - Fork 29
/
Automator.cs
280 lines (221 loc) · 8.57 KB
/
Automator.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
namespace Winium.StoreApps.Driver.Automator
{
#region
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Threading;
using Microsoft.Xde.Wmi;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Winium.StoreApps.Common;
using Winium.StoreApps.Common.Exceptions;
using Winium.StoreApps.Driver.EmulatorHelpers;
#endregion
internal class Automator
{
#region Static Fields
private static readonly object LockObject = new object();
private static volatile Automator instance;
#endregion
#region Fields
#endregion
#region Constructors and Destructors
private Automator(string session)
{
this.Session = session;
}
#endregion
#region Public Properties
public Capabilities ActualCapabilities { get; set; }
public Requester CommandForwarder { get; set; }
public IDeployer Deployer { get; set; }
public EmulatorController EmulatorController { get; set; }
public string InnerIp { get; set; }
public string Session { get; private set; }
#endregion
#region Public Methods and Operators
public static T GetValue<T>(IDictionary<string, JToken> parameters, string key) where T : class
{
JToken valueObject;
if (!parameters.TryGetValue(key, out valueObject))
{
return null;
}
try
{
return valueObject.ToObject<T>();
}
catch (Exception)
{
return null;
}
}
public static Automator InstanceForSession(string sessionId)
{
if (instance == null)
{
lock (LockObject)
{
if (instance == null)
{
if (sessionId == null)
{
sessionId = "AwesomeSession";
}
// TODO: Add actual support for sessions. Temporary return single Automator for any season
instance = new Automator(sessionId);
}
}
}
return instance;
}
public void ConnectToApp()
{
const int PingThrottling = 100;
long launchTimeout = this.ActualCapabilities.LaunchTimeout;
var stopWatch = new Stopwatch();
var launchTime = new Stopwatch();
var connected = false;
launchTime.Start();
Thread.Sleep(250);
while (launchTimeout > 0)
{
stopWatch.Restart();
Logger.Trace("Pinging InnerServer");
connected = this.TryConnectToApp();
if (connected)
{
break;
}
Thread.Sleep(PingThrottling);
stopWatch.Stop();
launchTimeout -= stopWatch.ElapsedMilliseconds;
}
stopWatch.Stop();
launchTime.Stop();
Logger.Debug("Connected in {0} seconds.", launchTime.Elapsed.TotalSeconds);
if (!connected)
{
throw new AutomationException("Could not connect to the InnerServer.", ResponseStatus.SessionNotCreatedException);
}
// Gives sometime to load visuals (needed only in case of slow emulation)
Thread.Sleep(this.ActualCapabilities.LaunchDelay);
// TODO throw AutomationException with SessionNotCreatedException if timeout and uninstall the app
}
public void InitializeApp()
{
var appPath = this.ActualCapabilities.App;
var debugDoNotDeploy = this.ActualCapabilities.DebugConnectToRunningApp;
if (string.IsNullOrWhiteSpace(appPath))
{
throw new AutomationException("app capability is not set.", ResponseStatus.SessionNotCreatedException);
}
this.Deployer = new Deployer81(this.ActualCapabilities.DeviceName, appPath);
if (!debugDoNotDeploy)
{
this.Deployer.Install();
this.Deployer.SendFiles(this.ActualCapabilities.Files);
}
this.ActualCapabilities.DeviceName = this.Deployer.DeviceName;
this.EmulatorController = this.CreateEmulatorController(debugDoNotDeploy);
this.InnerIp = this.EmulatorController.GetIpAddress();
}
public Point? RequestElementLocation(JToken element)
{
var command = new Command(
DriverCommand.GetElementLocationOnceScrolledIntoView,
new Dictionary<string, JToken> { { "ID", element } });
var responseBody = this.CommandForwarder.ForwardCommand(command);
var deserializeObject = JsonConvert.DeserializeObject<JsonResponse>(responseBody);
if (deserializeObject.Status != ResponseStatus.Success)
{
return null;
}
var locationObject = deserializeObject.Value as JObject;
if (locationObject == null)
{
return null;
}
var location = locationObject.ToObject<Dictionary<string, int>>();
if (location == null)
{
return null;
}
var x = location["x"];
var y = location["y"];
return new Point(x, y);
}
#endregion
#region Methods
private EmulatorController CreateEmulatorController(bool withFallback)
{
try
{
return new EmulatorController(this.ActualCapabilities.DeviceName);
}
catch (XdeVirtualMachineException)
{
if (!withFallback)
{
throw;
}
this.ActualCapabilities.DeviceName = this.ActualCapabilities.DeviceName.Split('(')[0];
return new EmulatorController(this.ActualCapabilities.DeviceName);
}
}
private ConnectionInformation GetConnectionInformation()
{
var filePath = Path.GetTempFileName();
this.Deployer.ReceiveFile("Temp", ConnectionInformation.FileName, filePath);
using (var file = File.OpenText(filePath))
{
var serializer = new JsonSerializer();
var connectionInformation =
(ConnectionInformation)serializer.Deserialize(file, typeof(ConnectionInformation));
return connectionInformation;
}
}
private bool TryConnectToApp()
{
var usingFallbackPort = false;
const string FallbackPort = "9998";
ConnectionInformation connectionInformation;
try
{
connectionInformation = this.GetConnectionInformation();
if (connectionInformation == null)
{
return false;
}
}
catch (Exception)
{
// TODO Limit catch clause from broad Exception, to specific ones
// We expect FileNotFound exception, but in rare cases other exceptions can be thrown by SmartDevice API
usingFallbackPort = true;
connectionInformation = new ConnectionInformation { RemotePort = FallbackPort };
}
this.CommandForwarder = new Requester(this.InnerIp, connectionInformation.RemotePort);
var pingCommand = new Command("ping");
var responseBody = this.CommandForwarder.ForwardCommand(pingCommand, false, 1500);
if (responseBody.StartsWith("<pong>", StringComparison.Ordinal))
{
Logger.Info("Received connection information from device {0}.", connectionInformation);
if (usingFallbackPort)
{
Logger.Warn(
"DEPRICATION: ConnectionInformation file was not found."
+ " Make sure that you are using same versions of Driver and InnerServer."
+ " Fallback to standard innerPort == {0}. This will be depricated in later versions.",
FallbackPort);
}
return true;
}
return false;
}
#endregion
}
}