forked from textadventures/quest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Play.aspx.cs
430 lines (368 loc) · 14.3 KB
/
Play.aspx.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using TextAdventures.Utility.JSInterop;
namespace WebPlayer
{
public partial class Play : System.Web.UI.Page
{
private PlayerHandler m_player;
private OutputBuffer m_buffer;
private string m_gameId;
protected void Page_Load(object sender, EventArgs e)
{
// We store the game in the Session, but use a dictionary keyed by GUIDs which
// are stored in the ViewState. This allows the same user in the same browser
// to open multiple games in different browser tabs.
if (Games == null)
{
Games = new Dictionary<string, PlayerHandler>();
}
if (OutputBuffers == null)
{
OutputBuffers = new Dictionary<string, OutputBuffer>();
}
if (Resources == null)
{
Resources = new SessionResources();
}
m_gameId = (string)ViewState["GameId"];
if (m_gameId == null)
{
m_gameId = Guid.NewGuid().ToString();
ViewState["GameId"] = m_gameId;
}
if (Page.IsPostBack)
{
if (Games.ContainsKey(m_gameId))
{
m_player = Games[m_gameId];
}
if (!OutputBuffers.ContainsKey(m_gameId))
{
// TO DO: Think this only ever happens while debugging?
return;
}
m_buffer = OutputBuffers[m_gameId];
}
else
{
m_buffer = new OutputBuffer(m_gameId);
OutputBuffers.Add(m_gameId, m_buffer);
m_buffer.AddJavaScriptToBuffer("setOutputBufferId", new StringParameter(m_gameId));
}
}
protected void InitTimerTick(object sender, EventArgs e)
{
if (m_buffer == null) return;
m_buffer.InitStage++;
switch (m_buffer.InitStage)
{
case 1:
string initialText = LoadGameForRequest();
if (m_player == null)
{
tmrInit.Enabled = false;
}
else
{
RegisterExternalScripts();
RegisterExternalStylesheets();
}
OutputTextNow(initialText);
break;
case 2:
tmrInit.Enabled = false;
m_player.BeginGame();
OutputTextNow(m_player.ClearBuffer());
break;
}
}
private string LoadGameForRequest()
{
string folder = null;
string gameFile = Request["file"];
string id = Request["id"];
if (string.IsNullOrEmpty(gameFile))
{
if (!string.IsNullOrEmpty(id))
{
IFileManager fileManager = FileManagerLoader.GetFileManager();
if (fileManager != null)
{
gameFile = fileManager.GetFileForID(id);
}
}
}
AzureFileManager.ApiGame apiGameData = null;
var loadData = Session["LoadData"] as string;
Session["LoadData"] = null;
if (loadData != null)
{
apiGameData = AzureFileManager.GetGameData(id);
if (apiGameData == null)
{
throw new InvalidOperationException("No API data returned for game id " + id);
}
}
return LoadGame(gameFile, id, folder, loadData, apiGameData);
}
private string LoadGame(string gameFile, string id, string folder, string loadData, AzureFileManager.ApiGame apiGameData)
{
if (string.IsNullOrEmpty(gameFile) && loadData == null)
{
return "No game specified";
}
string rootPath = folder ?? ConfigurationManager.AppSettings["GameFolder"];
string libPath = ConfigurationManager.AppSettings["LibraryFolder"];
string filename;
if (Config.ReadGameFileFromAzureBlob)
{
filename = gameFile;
}
else
{
filename = WebPlayer.Play.GetGameFilename(gameFile, rootPath);
if (filename == null)
{
return "Invalid filename";
}
}
List<string> errors;
try
{
m_player = new PlayerHandler(filename, m_buffer);
m_player.LoadData = loadData;
m_player.ApiGameData = apiGameData;
m_player.GameId = m_gameId;
m_player.LibraryFolder = libPath;
Games[m_gameId] = m_player;
m_player.BeginWait += m_player_BeginWait;
m_player.BeginPause += m_player_BeginPause;
m_player.ShowMenuDelegate = m_player_ShowMenu;
m_player.ShowQuestionDelegate = m_player_ShowQuestion;
m_player.AddResource += AddResource;
m_player.PlayAudio += m_player_PlayAudio;
m_player.StopAudio += m_player_StopAudio;
if (Config.ReadGameFileFromAzureBlob)
{
m_player.ResourceUrlRoot = AzureFileManager.GetResourceUrlRoot(id);
}
if (m_player.Initialise(out errors))
{
Resources.AddGame(m_player.Game);
// Successful game start
return m_player.ClearBuffer();
}
}
catch (Exception ex)
{
return "<b>Error loading game:</b><br/>" + ex.Message;
}
string output = string.Empty;
foreach (string error in errors)
{
output += error + "<br/>";
}
return output;
}
public static string GetGameFilename(string gameFile, string rootPath)
{
string filename;
if (rootPath == null)
{
filename = gameFile;
}
else
{
filename = Path.Combine(rootPath, gameFile);
var directory = new DirectoryInfo(Path.GetDirectoryName(filename));
var directoryName = directory.FullName;
if (rootPath.EndsWith(@"\") && !directoryName.EndsWith(@"\"))
{
directoryName += @"\";
}
// Block attempts to access files outside the GameFolder
if (!directoryName.StartsWith(rootPath))
{
return null;
}
}
return filename;
}
void RegisterExternalScripts()
{
int count = 0;
foreach (string url in m_player.SetUpExternalScripts())
{
count++;
ScriptManager.RegisterClientScriptInclude(this, this.GetType(), "scriptResource" + count.ToString(), url);
}
}
private void RegisterExternalStylesheets()
{
var stylesheets = m_player.GetExternalStylesheets();
if (stylesheets == null) return;
foreach (var stylesheet in stylesheets)
{
m_buffer.AddJavaScriptToBuffer("addExternalStylesheet", new StringParameter(stylesheet));
}
}
void m_player_PlayAudio(object sender, PlayerHandler.PlayAudioEventArgs e)
{
string functionName = null;
if (e.Filename.EndsWith(".wav", StringComparison.InvariantCultureIgnoreCase)) functionName = "playWav";
if (e.Filename.EndsWith(".mp3", StringComparison.InvariantCultureIgnoreCase)) functionName = "playMp3";
if (functionName == null) return;
string url = m_player.GetURL(e.Filename);
m_buffer.AddJavaScriptToBuffer(
functionName,
new StringParameter(url),
new BooleanParameter(e.Synchronous),
new BooleanParameter(e.Looped));
}
void m_player_StopAudio()
{
m_buffer.AddJavaScriptToBuffer("stopAudio");
}
string AddResource(string gameId, string filename)
{
return "Resource.ashx?id=" + gameId + "&filename=" + Uri.EscapeDataString(filename);
}
void m_player_BeginWait()
{
m_buffer.AddJavaScriptToBuffer("beginWait");
}
void m_player_BeginPause(int ms)
{
m_buffer.AddJavaScriptToBuffer("beginPause", new IntParameter(ms));
}
void m_player_ShowMenu(string caption, IDictionary<string, string> options, bool allowCancel)
{
m_buffer.AddJavaScriptToBuffer("showMenu", new StringParameter(caption), new DictionaryParameter(options), new BooleanParameter(allowCancel));
}
void m_player_ShowQuestion(string caption)
{
m_buffer.AddJavaScriptToBuffer("showQuestion", new StringParameter(caption));
}
protected void cmdSubmit_Click(object sender, EventArgs e)
{
if (m_player == null)
{
SessionTimeoutMessage("<b>Sorry, your session has expired and the game has finished.</b><br/><br/>Press your browser's Refresh button to start again.");
return;
}
int tickCount = 0;
if (fldUITickCount.Value.Length > 0)
{
int.TryParse(fldUITickCount.Value, out tickCount);
fldUITickCount.Value = "";
}
if (fldUIMsg.Value.Length > 0)
{
string[] args = fldUIMsg.Value.Split(new[] { ' ' }, 2);
switch (args[0])
{
case "command":
m_player.SendCommand(args[1], tickCount);
break;
case "endwait":
m_player.EndWait();
break;
case "endpause":
m_player.EndPause();
break;
case "choice":
m_player.SetMenuResponse(args[1]);
break;
case "choicecancel":
m_player.CancelMenu();
break;
case "msgbox":
m_player.SetQuestionResponse(args[1]);
break;
case "event":
SendEvent(args[1]);
break;
case "tick":
m_player.Tick(tickCount);
break;
case "save":
string unescapedHtml = args[1].Replace(">", ">").Replace("<", "<").Replace("&", "&");
m_player.RequestSave(unescapedHtml);
break;
}
fldUIMsg.Value = "";
}
string output = m_player.ClearBuffer();
m_buffer.OutputText(output);
ClearJavaScriptBuffer();
}
void OutputTextNow(string text)
{
m_buffer.OutputText(text);
ClearJavaScriptBuffer();
}
void SessionTimeoutMessage(string text)
{
m_buffer = new OutputBuffer(null);
m_buffer.OutputText(text);
m_buffer.AddJavaScriptToBuffer("sessionTimeout");
ClearJavaScriptBuffer();
}
void ClearJavaScriptBuffer()
{
int count = 0;
foreach (string javaScript in m_buffer.ClearJavaScriptBuffer())
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "script" + count.ToString(), javaScript, true);
count++;
}
}
void SendEvent(string data)
{
string[] args = data.Split(new[] { ';' }, 2);
m_player.SendEvent(args[0], args[1]);
}
private SessionResources Resources
{
get { return Session["Resources"] as SessionResources; }
set { Session["Resources"] = value; }
}
private Dictionary<string, PlayerHandler> Games
{
get { return Session["Games"] as Dictionary<string, PlayerHandler>; }
set { Session["Games"] = value; }
}
private Dictionary<string, OutputBuffer> OutputBuffers
{
get { return Session["OutputBuffers"] as Dictionary<string, OutputBuffer>; }
set { Session["OutputBuffers"] = value; }
}
protected string GetUI()
{
return PlayerHandler.GetUI();
}
protected string GetVersionHeader()
{
return "WebPlayer " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
protected string CacheBuster(string file)
{
return file + "?c=" + (Convert.ToInt32((DateTime.Now - (new DateTime(2012, 1, 1))).TotalSeconds)).ToString();
}
protected string ApiRoot()
{
return ConfigurationManager.AppSettings["BaseURI"] ?? "http://textadventures.co.uk/";
}
protected string GameSessionLogId()
{
return string.IsNullOrEmpty(ConfigurationManager.AppSettings["AzureLogSessionsBlob"]) ? "" : m_gameId;
}
}
}