-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathReloadClient.cpp
More file actions
1282 lines (1101 loc) · 30.8 KB
/
Copy pathReloadClient.cpp
File metadata and controls
1282 lines (1101 loc) · 30.8 KB
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (C) 2011 MoSync AB
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
*/
/**
* @file ReloadClient.cpp
*
* Created on: Feb 27, 2012
* Author: Ali Sarrafi, Iraklis Rossis
*/
#include "mastdlib.h"
#include <MAUtil/Environment.h>
#include <Wormhole/HighLevelHttpConnection.h>
#include <Wormhole/Encoder.h>
#include <maapi.h>
#include "ReloadClient.h"
#include "ReloadNativeUIMessageHandler.h"
#include "Log.h"
#include "MainScreenSingleton.h"
#include "MainScreen.h"
#include "SplashScreen.h"
#define SERVER_TCP_PORT "7000"
#define SERVER_HTTP_PORT "8283"
// Namespaces we want to access.
using namespace MAUtil;
using namespace NativeUI;
using namespace Wormhole;
// ========== Error messages ==========
#define RELOAD_ERROR_COULD_NOT_CONNECT_TO_SERVER 0
static String sErrorMessages[] =
{
"Could not connect to the server", // 0
"Could not connect to the server", // -1
"Could not connect to the server", //GENERIC = -2;
"The maximum number of open connections allowed has been reached", //MAX = -3;
"DNS resolution error", //DNS = -4;
"Internal error. Please report any occurrences", //INTERNAL = -5;
"The connection was closed by the remote peer", //CLOSED = -6;
"Attempted to write to a read-only connection", //READONLY = -7;
"The OS does not trust you enough to let you open this connection", //FORBIDDEN = -8;
"No operation has been started yet", //UNINITIALIZED = -9;
"The Content-Length header could not be found", //CONLEN = -10;
"You supplied a malformed URL", //URL = -11;
"The protocol is not available", //UNAVAILABLE = -12;
"You canceled the operation", //CANCELED = -13;
"The server gave an invalid response", //PROTOCOL = -14;
"The network connection could not be established", //NETWORK = -15;
"The requested header could not be found", //NOHEADER = -16;
"The requested object could not be found", //NOTFOUND = -17;
"An error occurred during SSL negotiation" //SSL = -18;
};
// ========== Helper class ==========
/**
* Helper class for making a HTTP request for a remote log message.
* This class is just used to send a request, it will not do anything
* with the result sent back from the server.
*/
class RemoteLogConnection : public HighLevelHttpConnection
{
public:
RemoteLogConnection()
: HighLevelHttpConnection()
{
}
void dataDownloaded(MAHandle data, int result)
{
// If we get data then delete it.
if (NULL != data)
{
maDestroyPlaceholder(data);
}
// Delete this instance.
delete this;
}
};
/**
* Helper function to read a string resource.
*/
static String SysLoadStringResource(MAHandle data)
{
// Get size of data.
int size = maGetDataSize(data);
// Allocate space for text plus zero termination character.
char* text = (char*) malloc(size + 1);
if (NULL == text)
{
return NULL;
}
// Read data.
maReadData(data, text, 0, size);
// Zero terminate string.
text[size] = 0;
String s = text;
free(text);
return s;
}
/**
* Helper function to delete a directory and its sub directories.
*/
static void DeleteFolderRecursively(const char *path)
{
char fileName[128];
char fullPath[256];
//LOG("@@@ RELOAD: Deleting files in folder: %s", path);
MAHandle list = maFileListStart(path, "*", MA_FL_SORT_NONE);
int length = maFileListNext(list, fileName, 128);
while (length > 0)
{
sprintf(fullPath, "%s%s", path, fileName);
if (fileName[length-1] == '/')
{
DeleteFolderRecursively(fullPath);
}
MAHandle appDirHandle = maFileOpen(fullPath, MA_ACCESS_READ_WRITE);
if (maFileExists(appDirHandle))
{
//LOG("@@@ RELOAD: Deleting: %s", fileName);
maFileDelete(appDirHandle);
}
maFileClose(appDirHandle);
length = maFileListNext(list, fileName, 128);
}
maFileListClose(list);
}
// ========== Creation and destruction ==========
ReloadClient::ReloadClient()
{
// Initialize application.
lprintfln("@@@ ReloadClient");
setScreenOrientation();
Screen *splashScreen = new SplashScreen();
splashScreen->show();
MAUtil::Environment::addTimer(this, 2000, 1);
}
ReloadClient::~ReloadClient()
{
}
void ReloadClient::runTimerEvent()
{
// Order of calls are important as data needed by
// later calls are created in earlier calls.
initializeWebView();
initializeVariables();
initializeFiles();
createScreens();
createMessageHandlers();
createNetworkHandlers();
// Show first screen.
mReloadScreenController->showNotConnectedScreen();
// Register custom function callable from javascript.
addMessageFun("EvalResponse", (FunTable::MessageHandlerFun)&ReloadClient::evalResponse);
}
// Send result of script evaluation to the server.
void ReloadClient::evalResponse(Wormhole::MessageStream& message)
{
MAUtil::String msg = message.getNext();
LOG("@@@@@ evalResponse %s", msg.c_str());
MAUtil::String out = "{\"message\":\"evalResponse\",\"params\": [\"" + Encoder::escape(msg) +"\"]}";
sendTCPMessage(out);
}
void ReloadClient::setScreenOrientation()
{
char buffer[64];
maGetSystemProperty(
"mosync.device.OS",
buffer,
64);
MAUtil::String os = buffer;
// Android orientation events not implemented.
if(os.find("Android", 0) < 0)
{
// Android and Windows Phone.
maScreenSetOrientation(SCREEN_ORIENTATION_DYNAMIC);
// iOS and Windows Phone.
maScreenSetSupportedOrientations(
MA_SCREEN_ORIENTATION_LANDSCAPE_LEFT |
MA_SCREEN_ORIENTATION_LANDSCAPE_RIGHT |
MA_SCREEN_ORIENTATION_PORTRAIT |
MA_SCREEN_ORIENTATION_PORTRAIT_UPSIDE_DOWN);
}
else
{
maScreenSetOrientation(SCREEN_ORIENTATION_PORTRAIT);
maScreenSetSupportedOrientations(
MA_SCREEN_ORIENTATION_PORTRAIT |
MA_SCREEN_ORIENTATION_PORTRAIT_UPSIDE_DOWN);
}
}
void ReloadClient::initializeWebView()
{
// Create WebView widget and message handlers.
// This code is from HybridMoblet::initialize().
mInitialized = true;
createUI();
enableWebViewMessages();
getMessageHandler()->initialize(this);
// Set the beep sound. This is defined in the
// Resources/Resources.lst file. You can change
// this by changing the sound file in that folder.
setBeepSound(BEEP_WAV);
}
void ReloadClient::initializeVariables()
{
mHasPage = false;
mAppsFolder = "apps/";
mSavedAppsFolder = "saved/";
mRunningApp = false;
mProtocolVersion = 0;
mProjectToSave = "";
mRunTests = false;
// Get the OS we are on.
char buffer[64];
maGetSystemProperty(
"mosync.device.OS",
buffer,
64);
mOS = buffer;
}
void ReloadClient::initializeFiles()
{
// Create folder where apps are unpacked.
MAHandle appDirHandle = maFileOpen(
(mFileUtil->getLocalPath() + mAppsFolder).c_str(),
MA_ACCESS_READ_WRITE);
if (!maFileExists(appDirHandle))
{
maFileCreate(appDirHandle);
}
maFileClose(appDirHandle);
// Create folder where saved apps are stored
appDirHandle = maFileOpen(
(mFileUtil->getLocalPath() + mSavedAppsFolder).c_str(),
MA_ACCESS_READ_WRITE);
if (!maFileExists(appDirHandle))
{
maFileCreate(appDirHandle);
}
maFileClose(appDirHandle);
// load stored project data
MAUtil::String storedProjectData;
bool success = mFileUtil->readTextFromFile(
mFileUtil->getLocalPath() + "SavedAppsData.txt",
storedProjectData);
// parse the data read and populate the mSavedProjects Vector
if (success && storedProjectData.length() > 0)
{
struct reloadProject node;
char *prPtr = NULL;
char * spa = new char[storedProjectData.length()+1];
memcpy(spa, storedProjectData.c_str(),storedProjectData.length()+1);
prPtr = strtok( spa, "\n");
while( prPtr != NULL)
{
node.name = prPtr;
node.path = strtok(NULL, "\n");
this->mSavedProjects.add(node);
prPtr = strtok(NULL, "\n");
}
}
// Reading information resource file and populate mInfo
// and mProtocolVersion
// TODO: What is this? Some resource string?
// TODO: Use SysLoadStringResource(MAHandle data)
int size = maGetDataSize(INFO_TEXT);
if (size > 0)
{
// Read the whole information resource file
mInfo.resize(size);
maReadData(INFO_TEXT, mInfo.pointer(), 0, size);
// Get the Protocol Version from the data read.
const char* prv;
char * infoTemp = new char[size + 1];
memcpy(infoTemp, mInfo.c_str(), size + 1);
int stringsRead = 0;
prv = strtok(infoTemp, "\r\n");
while(true)
{
if(prv != NULL)
{
stringsRead++;
//LOG("@@@RELOAD: %s", prv);
}
if(stringsRead == 3)
{
break;
}
prv = strtok(NULL, "\r\n");
}
mProtocolVersion = (char*)prv;
}
else
{
maPanic(0, "RELOAD: Could not read INFO_TEXT");
}
// Get the most recently used server ip address.
success = mFileUtil->readTextFromFile(
mFileUtil->getLocalPath() + "LastServerAddress.txt",
mServerAddress);
if (!success)
{
mServerAddress = "localhost";
}
}
void ReloadClient::createScreens()
{
// Create login screen and loading screen.
mReloadScreenController = new ReloadScreenController(this);
int orientation = maScreenGetCurrentOrientation();
mReloadScreenController->initializeScreen(mOS, orientation);
mLoadingScreen = new LoadingScreen(this);
mLoadingScreen->initializeScreen(mOS);
// Set the most recently used server IP address.
//mReloadScreenController->defaultAddress(mServerAddress.c_str());
}
void ReloadClient::createMessageHandlers()
{
// Set the log message listener.
getMessageHandler()->setLogMessageListener(this);
}
void ReloadClient::createNetworkHandlers()
{
mDownloadHandler.setListener(this);
mDownloadHandler.addDownloadListener(mLoadingScreen);
mSocketHandler.setListener(this);
}
// ========== Implemented (inherited) methods ==========
/**
* Called from JavaScript when a Wormhole app has been loaded.
*/
void ReloadClient::openWormhole(MAHandle webViewHandle)
{
// Apply customizations to functions loaded in wormhole.js.
String script = SysLoadStringResource(CUSTOM_JS);
script += "('" + mAppPath + "')";
callJS(webViewHandle, script.c_str());
// Run tests when wormhole is loaded.
if (mRunTests)
{
script = SysLoadStringResource(RUN_TESTS_JS);
script += "('" + mAppPath + "')";
callJS(webViewHandle, script.c_str());
}
// Call super class method to handler initialization.
HybridMoblet::openWormhole(webViewHandle);
}
/**
* This method is called when a key is pressed.
* Forwards the event to PhoneGapMessageHandler.
*/
void ReloadClient::keyPressEvent(int keyCode, int nativeCode)
{
if (mRunningApp)
{
// Forward to PhoneGap MessageHandler.
mMessageHandler->keyPressEvent(keyCode, nativeCode);
}
else
{
if (MAK_BACK == keyCode)
{
if (mReloadScreenController->shouldExit())
{
// on wp7, we cannot exit the application programmatically - the
// system closes the application on back button press
if (mOS.find("Windows", 0) < 0)
{
exit();
}
}
else
{
disconnectFromServer();
}
}
}
}
/**
* We want to quit the ReloadClient only if an app is not running.
* This method is called from the Wormhole library when a JavaScript
* application requests to exit.
*/
void ReloadClient::exit()
{
if (mRunningApp)
{
// Close the running app and show the start screen.
mRunningApp = false;
// Show the Tab Screen
MainScreenSingleton::getInstance()->show();
}
else
{
// Exit the ReloadClient.
exitEventLoop();
}
}
/**
* Log message handler.
*/
void ReloadClient::onLogMessage(const char* message, const char* url)
{
// If the url is set to "undefined", we will use JsonRPC to
// send the log message to the Reload server. Otherwise, we
// just call the url supplied using a REST convention.
if (0 == strcmp("undefined", url))
{
#if(1)
// New method (TCP).
// Send the result back to the server as a JSON string
MAUtil::String messageString = Encoder::escape(message);
MAUtil::String json(
"{"
"\"message\":\"remoteLogRequest\","
"\"params\":["
"\"" + messageString + "\""
"],"
"\"id\":0"
"}");
sendTCPMessage(json);
#endif
#if(0)
// Unused method (HTTP).
// Set URL for remote log service.
MAUtil::String messageString = message;
MAUtil::String json(
"{"
"\"method\": \"client.remoteLog\","
"\"params\": [ "
"\"" + messageString + "\""
"],"
"\"id\": 0"
"}");
MAUtil::String commandUrl =
"http://" + mServerAddress + ":" + SERVER_HTTP_PORT +
"/proccess?jsonRPC=" + Encoder::escape(json);
// Send request to server.
RemoteLogConnection* connection = new RemoteLogConnection();
connection->get(commandUrl.c_str());
#endif
}
else
{
MAUtil::String urlString = url;
// Escape ("percent encode") the message.
MAUtil::String request = urlString + Encoder::escape(message);
// Send request to server.
RemoteLogConnection* connection = new RemoteLogConnection();
connection->get(request.c_str());
}
}
// ========== SocketHandlerListener methods ==========
/**
* A connection to the server has been established.
*/
void ReloadClient::socketHandlerConnected(int result)
{
if (result > 0)
{
LOG("@@@ RELOAD connected to: %s", mServerAddress.c_str());
getProjectListFromServer();
// Tell UI we are connected.
mReloadScreenController->connectedTo(mServerAddress.c_str());
// Send info about this device to the server.
sendClientDeviceInfo();
}
else
{
// Special handling of error code -13, which is sent
// when a maConnect fails, on Android at least. Is this
// a bug in the runtime? See issue RELOAD-133.
if (-13 == result)
{
showConnectionErrorMessage(
RELOAD_ERROR_COULD_NOT_CONNECT_TO_SERVER);
}
else
{
showConnectionErrorMessage(result);
}
}
}
/**
* We received a message from the server.
*/
void ReloadClient::socketHandlerDisconnected(int result)
{
LOG("@@@ RELOAD: ERROR socketHandlerDisconnected: %i", result);
// Do not show the alert if we have result code zero.
// This means we have closed the connection manually,
// it is not an error. Does this work the same on all
// platforms? (Tested on Android.)
if (0 != result)
{
showConnectionErrorMessage(result);
// Go back to the login screen.
mReloadScreenController->showNotConnectedScreen();
}
}
/**
* We received a message from the server.
*/
void ReloadClient::socketHandlerMessageReceived(const char* message)
{
if (NULL != message)
{
handleJSONMessage(message);
}
else
{
LOG("@@@ RELOAD: ERROR socketHandlerMessageReceived");
// TODO: Add error message.
//showConErrorMessage(result);
// Go back to the login screen.
mReloadScreenController->showNotConnectedScreen();
}
}
// ========== DownloadHandlerListener methods ==========
void ReloadClient::downloadHandlerError(int code)
{
LOG("@@@ RELOAD: Download handler error: %d", code);
showConnectionErrorMessage(code);
}
void ReloadClient::downloadHandlerSuccess(MAHandle data)
{
// Check that we have the expected bundle size.
int dataSize = maGetDataSize(data);
LOG("@@@ RELOAD: Received size: %d, expected size: %d", dataSize, mBundleSize);
if (dataSize != mBundleSize)
{
maDestroyPlaceholder(data);
// TODO: Show LoginScreen or error message?
// We should not try to download again, because
// this could case an infinite download loop.
return;
}
// Check if the project exists
bool projectExists = false;
if(mProjectToSave != "")
{
for(MAUtil::Vector <reloadProject>::iterator i = mSavedProjects.begin(); i != mSavedProjects.end(); i++)
{
if(i->name == mProjectToSave)
{
projectExists = true;
lprintfln("@@@ RELOAD: The project %s already exists", mProjectToSave.c_str());
break;
}
}
}
// Delete old files if necessary.
if(mProjectToSave == "" || projectExists )
{
clearAppsFolder(mProjectToSave);
}
// Set the project Path depending on weather the
// we are reloading or saving
if (mProjectToSave == "")
{
char buf[1024];
sprintf(buf, (mAppsFolder + "%d/").c_str(), maGetMilliSecondCount());
mAppPath = buf;
}
else
{
mAppPath = mSavedAppsFolder + "RLDPRJ" + mProjectToSave +"/";
}
String fullPath = mFileUtil->getLocalPath() + mAppPath;
// Extract files.
setCurrentFileSystem(data, 0);
int result = MAFS_extractCurrentFileSystem(fullPath.c_str());
freeCurrentFileSystem();
maDestroyPlaceholder(data);
// Load the app if reloading or return to workspace screen if saving.
if (result > 0)
{
// Save the new project to the vector and write the data on file
if(mProjectToSave != "")
{
if( !projectExists)
{
struct reloadProject projectItem;
projectItem.name = mProjectToSave;
projectItem.path = mFileUtil->getLocalPath() + mSavedAppsFolder + "RLDPRJ" + mProjectToSave +"/";
mSavedProjects.add(projectItem);
MAUtil::String stringToWrite = "";
for(MAUtil::Vector <reloadProject>::iterator i = mSavedProjects.begin(); i != mSavedProjects.end(); i++)
{
stringToWrite += i->name + "\n" + i->path + "\n";
}
mFileUtil->writeTextToFile(
mFileUtil->getLocalPath() + "SavedAppsData.txt",
stringToWrite);
}
maAlert("Saving Project", ("Project " + mProjectToSave + " was succesfully saved").c_str(),
NULL, "OK", NULL);
mProjectToSave = "";
mReloadScreenController->showConnectedScreen();
// Update the local list of projects
mReloadScreenController->loadStoredProjects();
}
else
{
// We are in reload mode. Just start the saved app
// without providing project Name
launchSavedApp("");
}
}
else
{
// TODO: Show LoginScreen or error message?
// We should not try to download again, because
// this could case an infinite download loop.
}
}
// ========== Methods called from the UI ==========
void ReloadClient::cancelDownload()
{
/* TODO: Reveert to Previous commit after the downloader
* class is fixed
* commit 84ee4985a892f121cd25529b006bd8ae72330f36
* Merge: f5af6fc e0426b8
* Author: Abi Waqas <abi@mosync.com>
* Date: Wed May 22 03:14:38 2013 -0700
*/
mDownloadHandler.cancelDownload();
mReloadScreenController->showConnectedScreen();
}
void ReloadClient::connectToServer(const char* serverAddress)
{
// Store the server address.
mServerAddress = serverAddress;
// Save the server address on file.
mFileUtil->writeTextToFile(
mFileUtil->getLocalPath() + "LastServerAddress.txt",
mServerAddress);
// Initiate connection sequence.
int result = mSocketHandler.connectToServer(
serverAddress,
SERVER_TCP_PORT);
if (result < 0)
{
showConnectionErrorMessage(RELOAD_ERROR_COULD_NOT_CONNECT_TO_SERVER);
}
}
void ReloadClient::disconnectFromServer()
{
// Close the socket, and show the connect controls again.
mSocketHandler.closeConnection();
mReloadScreenController->disconnected();
}
void ReloadClient::showDisconnectionMessage (MAUtil::String disconnectData)
{
MAUtil::String finalString = "";
int disconnectDataSize = disconnectData.length();
int startPos = 0;
while (startPos < disconnectDataSize)
{
finalString += disconnectData.substr(startPos,40) + "\n";
startPos += 40;
}
// Add \n every 40 characters so alert will be shown
// correctly on all devices
maAlert("Disconnection",
finalString.c_str(),
NULL,"OK",NULL);
}
// ========== Server message handling ==========
/**
* Handle JSON messages.
*/
void ReloadClient::handleJSONMessage(const String& json)
{
// Parse JSON data.
YAJLDom::Value* jsonRoot = YAJLDom::parse(
(const unsigned char*)json.c_str(),
json.size());
// Check that the root is valid.
if (NULL == jsonRoot
|| YAJLDom::Value::NUL == jsonRoot->getType()
|| YAJLDom::Value::MAP != jsonRoot->getType())
{
maPanic(0, "RELOAD: The JSON message format is incorrect");
}
// Get the message name.
String message = (jsonRoot->getValueForKey("message"))->toString();
// Download a bundle.
if (message == "ReloadBundle")
{
mRunTests = false;
LOG("@@@@@ Reload Bundle");
reloadBundle(json);
}
// Disconnect from server.
else if (message == "Disconnect")
{
LOG("@@@ disconnect");
disconnectFromServer();
}
else if (message == "RunTests")
{
mRunTests = true;
reloadBundle(json);
}
// Evaluate a JavaScript string.
else if (message == "EvalJS")
{
// Get message parameters.
String script = (jsonRoot->getValueForKey("script"))->toString();
evaluateScript(script);
}
// Evaluate a JavaScript string for a test case.
else if (message == "Evaluate")
{
// Get message parameters.
String script = (jsonRoot->getValueForKey("script"))->toString();
String fingerprint = (jsonRoot->getValueForKey("fingerprint"))->toString();
evaluate(script, fingerprint);
}
else if (message == "Disconnect")
{
this->disconnectFromServer();
YAJLDom::Value* tempstr = jsonRoot->getValueForKey("data");
if(!tempstr->isNull())
{
MAUtil::String disconnectData = (tempstr->toString()) + "\n";
this->showDisconnectionMessage(disconnectData);
}
}
else if (message == "projectList")
{
mProjects.clear();
YAJLDom::Value *data = jsonRoot->getValueForKey("data");
int totalProjects = (int)data->getValueForKey("projectsCount")->toDouble();
struct reloadProject tmp;
YAJLDom::Value *projectArray = data->getValueForKey("projects");
for(int i = 0; i < totalProjects; i++)
{
YAJLDom::Value *row = projectArray->getValueByIndex(i);
tmp.name = row->getValueForKey("name")->toString();
tmp.path = row->getValueForKey("path")->toString();
tmp.url = row->getValueForKey("url")->toString();
mProjects.add(tmp);
}
mReloadScreenController->showConnectedScreen();
//mReloadScreenController->pushWorkspaceScreen();
}
else
{
maPanic(0,"RELOAD: Unknown server message");
}
// Delete the JSON tree.
YAJLDom::deleteValue(jsonRoot);
}
// ========== Download methods ==========
void ReloadClient::downloadBundle(const String& urlData, int fileSize)
{
// Check that we have valid file size field.
if (fileSize <= 0 )
{
maPanic(0, "RELOAD: downloadBundle file size is invalid");
}
// If there is an ongoing download, then cancel it.
if (mDownloadHandler.isDownloading())
{
mDownloadHandler.cancelDownload();
}
// Create download request.
MAUtil::String jsonRequest("{"
"\"method\":\"client.getBundle\","
"\"params\":["
"\"" + urlData + "\""
"],"
"\"id\":1"
"}");
LOG("@@@ RELOAD urlData: %s", urlData.c_str() );
LOG("@@@ RELOAD jsonRequest: %s", jsonRequest.c_str() );
MAUtil::String url =
"http://" + mServerAddress + ":" + SERVER_HTTP_PORT +
"/proccess?jsonRPC=" + Encoder::escape(jsonRequest);
LOG("@@@ RELOAD: downloadBundle before downloading bundle: "
"url: %s fileSize: %d",
url.c_str(), fileSize);
// Save the file size so that we can verify the download.
mBundleSize = fileSize;
// Start the download.
int result = mDownloadHandler.startDownload(url.c_str());
if (result > 0)
{
LOG("@@@ RELOAD: downloadBundle started with result: %d\n", result);
// Show the loading screen during downloading.
mLoadingScreen->show();
}
else
{
LOG("@@@ RELOAD: downloadBundle ERROR: %d\n", result);
showConnectionErrorMessage(result);
}
}
void ReloadClient::reloadBundle(const String& json)
{
// Parse JSON data.
YAJLDom::Value* jsonRoot = YAJLDom::parse(
(const unsigned char*)json.c_str(),
json.size());
// Get message parameters.
String urlData = (jsonRoot->getValueForKey("url"))->toString();
int fileSize = (jsonRoot->getValueForKey("fileSize"))->toInt();
getWebView()->callJS("try{mosync.nativeui.destroyAll()}catch{console.log(\"error cleaning up\")}");
// Initiate the download.
downloadBundle(urlData, fileSize);
}
/**
* New function called to download index.html from the server.
* TODO: This is experimental code. NOT USED.
*/
/*
void ReloadClient::downloadHTML()
{
// Clear web view cache.
getWebView()->setProperty("cache", "clearall");
// Set URL (uses experimental port).
String url = "http://";
url += mServerAddress + ":4042/index.html";
lprintfln("downloadHTML: %s", url.c_str());
// Open the page.
showPage(url);
mHasPage = true;
mRunningApp = true;
}
*/
// ========== Evaluate JavaScript ==========
void ReloadClient::evaluateScript(const String& script)
{
String url = "javascript:";
url += "try{var res=eval(unescape('";
url += script;
url += "'));";
url += "if (typeof res!=='undefined'){mosync.rlog('javascript:'+JSON.stringify(res));}}";
url += "catch(err){mosync.rlog('javascript:'+err);}";
getWebView()->openURL(url);
}
// ========== Evaluate JavaScript for a specific test case ==========
void ReloadClient::evaluate(const String& script, const String& fingerprint)
{