Project

General

Profile

Download (24.3 KB) Statistics
| Branch: | Tag: | Revision:

magiccube / src / main / java / org / distorted / network / RubikNetwork.java @ ffe7e55d

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2019 Leszek Koltunski                                                               //
3
//                                                                                               //
4
// This file is part of Magic Cube.                                                              //
5
//                                                                                               //
6
// Magic Cube is free software: you can redistribute it and/or modify                            //
7
// it under the terms of the GNU General Public License as published by                          //
8
// the Free Software Foundation, either version 2 of the License, or                             //
9
// (at your option) any later version.                                                           //
10
//                                                                                               //
11
// Magic Cube is distributed in the hope that it will be useful,                                 //
12
// but WITHOUT ANY WARRANTY; without even the implied warranty of                                //
13
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                                 //
14
// GNU General Public License for more details.                                                  //
15
//                                                                                               //
16
// You should have received a copy of the GNU General Public License                             //
17
// along with Magic Cube.  If not, see <http://www.gnu.org/licenses/>.                           //
18
///////////////////////////////////////////////////////////////////////////////////////////////////
19

    
20
package org.distorted.network;
21

    
22
import java.io.BufferedReader;
23
import java.io.InputStream;
24
import java.io.InputStreamReader;
25
import java.net.HttpURLConnection;
26
import java.net.URL;
27
import java.net.UnknownHostException;
28
import java.security.MessageDigest;
29
import java.security.NoSuchAlgorithmException;
30

    
31
import android.content.pm.PackageInfo;
32
import android.content.pm.PackageManager;
33

    
34
import androidx.fragment.app.FragmentActivity;
35

    
36
import org.distorted.library.main.DistortedLibrary;
37
import org.distorted.objectlib.json.JsonWriter;
38
import org.distorted.objects.RubikObjectList;
39

    
40
import static org.distorted.objects.RubikObjectList.MAX_LEVEL;
41

    
42
///////////////////////////////////////////////////////////////////////////////////////////////////
43

    
44
public class RubikNetwork
45
  {
46
  public interface Receiver
47
    {
48
    void receive(String[][][] country, String[][][] name, float[][][] time);
49
    void message(String mess);
50
    void error(String error);
51
    }
52

    
53
  public interface Updatee
54
    {
55
    void iconDownloaded();
56
    void receiveUpdate(RubikUpdates update);
57
    void errorUpdate();
58
    }
59

    
60
  public static final int MAX_PLACES = 10;
61

    
62
  private static final int REND_ADRENO= 0;
63
  private static final int REND_MALI  = 1;
64
  private static final int REND_POWER = 2;
65
  private static final int REND_OTHER = 3;
66

    
67
  private static final int DEBUG_RUNNING = 1;
68
  private static final int DEBUG_SUCCESS = 2;
69
  private static final int DEBUG_FAILURE = 3;
70

    
71
  private final String[] hex = {
72
    "%00", "%01", "%02", "%03", "%04", "%05", "%06", "%07",
73
    "%08", "%09", "%0a", "%0b", "%0c", "%0d", "%0e", "%0f",
74
    "%10", "%11", "%12", "%13", "%14", "%15", "%16", "%17",
75
    "%18", "%19", "%1a", "%1b", "%1c", "%1d", "%1e", "%1f",
76
    "%20", "%21", "%22", "%23", "%24", "%25", "%26", "%27",
77
    "%28", "%29", "%2a", "%2b", "%2c", "%2d", "%2e", "%2f",
78
    "%30", "%31", "%32", "%33", "%34", "%35", "%36", "%37",
79
    "%38", "%39", "%3a", "%3b", "%3c", "%3d", "%3e", "%3f",
80
    "%40", "%41", "%42", "%43", "%44", "%45", "%46", "%47",
81
    "%48", "%49", "%4a", "%4b", "%4c", "%4d", "%4e", "%4f",
82
    "%50", "%51", "%52", "%53", "%54", "%55", "%56", "%57",
83
    "%58", "%59", "%5a", "%5b", "%5c", "%5d", "%5e", "%5f",
84
    "%60", "%61", "%62", "%63", "%64", "%65", "%66", "%67",
85
    "%68", "%69", "%6a", "%6b", "%6c", "%6d", "%6e", "%6f",
86
    "%70", "%71", "%72", "%73", "%74", "%75", "%76", "%77",
87
    "%78", "%79", "%7a", "%7b", "%7c", "%7d", "%7e", "%7f",
88
    "%80", "%81", "%82", "%83", "%84", "%85", "%86", "%87",
89
    "%88", "%89", "%8a", "%8b", "%8c", "%8d", "%8e", "%8f",
90
    "%90", "%91", "%92", "%93", "%94", "%95", "%96", "%97",
91
    "%98", "%99", "%9a", "%9b", "%9c", "%9d", "%9e", "%9f",
92
    "%a0", "%a1", "%a2", "%a3", "%a4", "%a5", "%a6", "%a7",
93
    "%a8", "%a9", "%aa", "%ab", "%ac", "%ad", "%ae", "%af",
94
    "%b0", "%b1", "%b2", "%b3", "%b4", "%b5", "%b6", "%b7",
95
    "%b8", "%b9", "%ba", "%bb", "%bc", "%bd", "%be", "%bf",
96
    "%c0", "%c1", "%c2", "%c3", "%c4", "%c5", "%c6", "%c7",
97
    "%c8", "%c9", "%ca", "%cb", "%cc", "%cd", "%ce", "%cf",
98
    "%d0", "%d1", "%d2", "%d3", "%d4", "%d5", "%d6", "%d7",
99
    "%d8", "%d9", "%da", "%db", "%dc", "%dd", "%de", "%df",
100
    "%e0", "%e1", "%e2", "%e3", "%e4", "%e5", "%e6", "%e7",
101
    "%e8", "%e9", "%ea", "%eb", "%ec", "%ed", "%ee", "%ef",
102
    "%f0", "%f1", "%f2", "%f3", "%f4", "%f5", "%f6", "%f7",
103
    "%f8", "%f9", "%fa", "%fb", "%fc", "%fd", "%fe", "%ff"
104
    };
105

    
106
  private static String[][][] mCountry;
107
  private static String[][][] mName;
108
  private static float[][][] mTime;
109
  private static int[][] mPlaces;
110

    
111
  private static RubikNetwork mThis;
112
  private static String mScores = "";
113
  private static boolean mRunning = false;
114
  private static Receiver mReceiver;
115
  private static Updatee mUpdatee;
116
  private static String mVersion;
117
  private static String mSuspicious;
118
  private static int mNumObjects;
119
  private static RubikUpdates mUpdates;
120
  private static int mDebugState;
121

    
122
///////////////////////////////////////////////////////////////////////////////////////////////////
123

    
124
  private static void initializeStatics()
125
    {
126
    int newNum = RubikObjectList.getNumObjects();
127

    
128
    if( mCountry==null || newNum!=mNumObjects ) mCountry = new String[newNum][MAX_LEVEL][MAX_PLACES];
129
    if( mName==null    || newNum!=mNumObjects ) mName    = new String[newNum][MAX_LEVEL][MAX_PLACES];
130
    if( mTime==null    || newNum!=mNumObjects ) mTime    = new  float[newNum][MAX_LEVEL][MAX_PLACES];
131
    if( mPlaces==null  || newNum!=mNumObjects ) mPlaces  = new    int[newNum][MAX_LEVEL];
132

    
133
    if( mUpdates==null ) mUpdates = new RubikUpdates();
134

    
135
    mNumObjects = newNum;
136
    }
137

    
138
///////////////////////////////////////////////////////////////////////////////////////////////////
139

    
140
  private static String computeHash(String stringToHash, byte[] salt)
141
    {
142
    String generatedPassword;
143

    
144
    try
145
      {
146
      MessageDigest md = MessageDigest.getInstance("MD5");
147
      md.update(salt);
148
      byte[] bytes = md.digest(stringToHash.getBytes());
149
      StringBuilder sb = new StringBuilder();
150

    
151
      for (byte aByte : bytes)
152
        {
153
        sb.append(Integer.toString((aByte & 0xff) + 0x100, 16).substring(1));
154
        }
155

    
156
      generatedPassword = sb.toString();
157
      }
158
    catch (NoSuchAlgorithmException e)
159
      {
160
      return "NoSuchAlgorithm";
161
      }
162

    
163
    return generatedPassword;
164
    }
165

    
166
///////////////////////////////////////////////////////////////////////////////////////////////////
167

    
168
  private boolean fillValuesNormal()
169
    {
170
    int begin=-1 ,end, len = mScores.length();
171
    String row;
172

    
173
    if( len==0 )
174
      {
175
      if( mReceiver!=null ) mReceiver.error("1");
176
      return false;
177
      }
178
    else if( len<=2 )
179
      {
180
      if( mReceiver!=null ) mReceiver.error(mScores);
181
      return false;
182
      }
183

    
184
    for(int i=0; i<mNumObjects; i++)
185
      for(int j=0; j<MAX_LEVEL; j++)
186
        {
187
        mPlaces[i][j] = 0;
188
        }
189

    
190
    while( begin<len )
191
      {
192
      end = mScores.indexOf('\n', begin+1);
193
      if( end<0 ) end = len;
194

    
195
      try
196
        {
197
        row = mScores.substring(begin+1,end);
198
        fillRow(row);
199
        }
200
      catch(Exception ex)
201
        {
202
        // faulty row - ignore
203
        }
204

    
205
      begin = end;
206
      }
207

    
208
    return true;
209
    }
210

    
211
///////////////////////////////////////////////////////////////////////////////////////////////////
212

    
213
  private void fillRow(String row)
214
    {
215
    int s1 = row.indexOf(' ');
216
    int s2 = row.indexOf(' ',s1+1);
217
    int s3 = row.indexOf(' ',s2+1);
218
    int s4 = row.indexOf(' ',s3+1);
219
    int s5 = row.length();
220

    
221
    if( s5>s4 && s4>s3 && s3>s2 && s2>s1 && s1>0 )
222
      {
223
      int object = RubikObjectList.getOrdinal( row.substring(0,s1) );
224

    
225
      if( object>=0 && object<mNumObjects )
226
        {
227
        int level      = Integer.parseInt( row.substring(s1+1,s2) );
228
        String name    = row.substring(s2+1, s3);
229
        int time       = Integer.parseInt( row.substring(s3+1,s4) );
230
        String country = row.substring(s4+1, s5);
231

    
232
        if( country.equals("do") ) country = "dm"; // see RubikScores.setCountry()
233

    
234
        if(level>=0 && level<MAX_LEVEL)
235
          {
236
          int p = mPlaces[object][level];
237
          mPlaces[object][level]++;
238

    
239
          mCountry[object][level][p] = country;
240
          mName   [object][level][p] = name;
241
          mTime   [object][level][p] = ((float)(time/10))/100.0f;
242
          }
243
        }
244
      }
245
    else
246
      {
247
      tryDoCommand(row);
248
      }
249
    }
250

    
251
///////////////////////////////////////////////////////////////////////////////////////////////////
252

    
253
  private void tryDoCommand(String row)
254
    {
255
    if( row.startsWith("comm") )
256
      {
257
      int colon = row.indexOf(':');
258

    
259
      if( colon>0 )
260
        {
261
        String commandNumber = row.substring(4,colon);
262
        int number;
263

    
264
        try
265
          {
266
          number = Integer.parseInt(commandNumber);
267
          }
268
        catch(NumberFormatException ex)
269
          {
270
          number=0;
271
          }
272

    
273
        if(number==1)
274
          {
275
          String country = row.substring(colon+1);
276
          RubikScores scores = RubikScores.getInstance();
277
          scores.setCountry(country);
278
          }
279
        }
280
      }
281
    }
282

    
283
///////////////////////////////////////////////////////////////////////////////////////////////////
284

    
285
  private int getRendererType(String renderer)
286
    {
287
    if( renderer.contains("Adreno")  ) return REND_ADRENO;
288
    if( renderer.contains("Mali")    ) return REND_MALI;
289
    if( renderer.contains("PowerVR") ) return REND_POWER;
290

    
291
    return REND_OTHER;
292
    }
293

    
294
///////////////////////////////////////////////////////////////////////////////////////////////////
295

    
296
  private String parseRenderer(final int type, String renderer)
297
    {
298
    if( type==REND_ADRENO || type==REND_POWER )
299
      {
300
      int lastSpace = renderer.lastIndexOf(' ');
301
      String ret = renderer.substring(lastSpace+1);
302
      return URLencode(ret);
303
      }
304

    
305
    if( type==REND_MALI )
306
      {
307
      int firstHyphen = renderer.indexOf('-');
308
      String ret = renderer.substring(firstHyphen+1);
309
      return URLencode(ret);
310
      }
311

    
312
    return "other";
313
    }
314

    
315
///////////////////////////////////////////////////////////////////////////////////////////////////
316

    
317
  private String parseVersion(final int type, String version)
318
    {
319
    switch(type)
320
      {
321
      case REND_ADRENO: int aMonkey = version.indexOf('@');
322
                        int aDot = version.indexOf('.', aMonkey);
323
                        String ret1 = aDot>=3 ? version.substring(aDot-3,aDot) : "";
324
                        return URLencode(ret1);
325
      case REND_MALI  : int mV1 = version.indexOf("v1");
326
                        int mHyphen = version.indexOf('-', mV1);
327
                        String ret2 = mHyphen>mV1+3 && mV1>=0 ? version.substring(mV1+3,mHyphen) : "";
328
                        return URLencode(ret2);
329
      case REND_POWER : int pMonkey = version.indexOf('@');
330
                        int pSpace  = version.lastIndexOf(' ');
331
                        String ret3 = pSpace>=0 && pMonkey>pSpace+1 ? version.substring(pSpace+1,pMonkey) : "";
332
                        return URLencode(ret3);
333
      default         : return "";
334
      }
335
    }
336

    
337
///////////////////////////////////////////////////////////////////////////////////////////////////
338

    
339
  private String URLencode(String s)
340
    {
341
    StringBuilder sbuf = new StringBuilder();
342
    int len = s.length();
343

    
344
    for (int i = 0; i < len; i++)
345
      {
346
      int ch = s.charAt(i);
347

    
348
           if ('A' <= ch && ch <= 'Z') sbuf.append((char)ch);
349
      else if ('a' <= ch && ch <= 'z') sbuf.append((char)ch);
350
      else if ('0' <= ch && ch <= '9') sbuf.append((char)ch);
351
      else if (ch == ' '             ) sbuf.append('+');
352
      else if (ch == '-' || ch == '_'
353
            || ch == '.' || ch == '!'
354
            || ch == '~' || ch == '*'
355
            || ch == '\'' || ch == '('
356
            || ch == ')'             ) sbuf.append((char)ch);
357
      else if (ch <= 0x007f)           sbuf.append(hex[ch]);
358
      else if (ch <= 0x07FF)
359
        {
360
        sbuf.append(hex[0xc0 | (ch >> 6)]);
361
        sbuf.append(hex[0x80 | (ch & 0x3F)]);
362
        }
363
      else
364
        {
365
        sbuf.append(hex[0xe0 | (ch >> 12)]);
366
        sbuf.append(hex[0x80 | ((ch >> 6) & 0x3F)]);
367
        sbuf.append(hex[0x80 | (ch & 0x3F)]);
368
        }
369
      }
370

    
371
    return sbuf.toString();
372
    }
373

    
374
///////////////////////////////////////////////////////////////////////////////////////////////////
375

    
376
  private boolean network(String url)
377
    {
378
    try
379
      {
380
      java.net.URL connectURL = new URL(url);
381
      HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
382

    
383
      conn.setDoInput(true);
384
      conn.setDoOutput(true);
385
      conn.setUseCaches(false);
386
      conn.setRequestMethod("GET");
387
      conn.connect();
388
      conn.getOutputStream().flush();
389

    
390
      InputStream is = conn.getInputStream();
391
      BufferedReader r = new BufferedReader(new InputStreamReader(is));
392
      StringBuilder total = new StringBuilder();
393

    
394
      for (String line; (line = r.readLine()) != null; )
395
        {
396
        total.append(line).append('\n');
397
        }
398

    
399
      mScores = total.toString();
400
      }
401
    catch( final UnknownHostException e )
402
      {
403
      if( mReceiver!=null ) mReceiver.message("No access to Internet");
404
      return false;
405
      }
406
    catch( final SecurityException e )
407
      {
408
      if( mReceiver!=null ) mReceiver.message("Application not authorized to connect to the Internet");
409
      return false;
410
      }
411
    catch( final Exception e )
412
      {
413
      if( mReceiver!=null ) mReceiver.message(e.getMessage());
414
      return false;
415
      }
416

    
417
    if( mScores.length()==0 )
418
      {
419
      if( mReceiver!=null ) mReceiver.message("Failed to download scores");
420
      return false;
421
      }
422

    
423
    return true;
424
    }
425

    
426
///////////////////////////////////////////////////////////////////////////////////////////////////
427

    
428
  private String constructSuspiciousURL()
429
    {
430
    RubikScores scores = RubikScores.getInstance();
431
    int deviceID= scores.getDeviceID();
432
    String suspicious = URLencode(mSuspicious);
433

    
434
    String url="https://distorted.org/magic/cgi-bin/suspicious.cgi";
435
    url += "?i="+deviceID+"&d="+suspicious;
436

    
437
    return url;
438
    }
439

    
440
///////////////////////////////////////////////////////////////////////////////////////////////////
441

    
442
  private String constructDebugURL()
443
    {
444
    RubikScores scores = RubikScores.getInstance();
445
    String name = URLencode(scores.getName());
446
    int numRuns = scores.getNumRuns();
447
    int numPlay = scores.getNumPlays();
448
    String country = scores.getCountry();
449
    String renderer = DistortedLibrary.getDriverRenderer();
450
    String version  = DistortedLibrary.getDriverVersion();
451
    int objectAPI   = JsonWriter.VERSION_OBJECT_MAJOR;
452
    int tutorialAPI = JsonWriter.VERSION_EXTRAS_MAJOR;
453

    
454
    renderer = URLencode(renderer);
455
    version  = URLencode(version);
456

    
457
    String url="https://distorted.org/magic/cgi-bin/debugs-new.cgi";
458
    url += "?n="+name+"&r="+numRuns+"&p="+numPlay+"&c="+country+"&e="+mVersion+"d";
459
    url += "&d="+renderer+"&v="+version+"&a="+objectAPI+"&b="+tutorialAPI;
460

    
461
    return url;
462
    }
463

    
464
///////////////////////////////////////////////////////////////////////////////////////////////////
465

    
466
  private String constructDownloadURL()
467
    {
468
    RubikScores scores = RubikScores.getInstance();
469
    String name = URLencode(scores.getName());
470
    int numRuns = scores.getNumRuns();
471
    int numPlay = scores.getNumPlays();
472
    String country = scores.getCountry();
473

    
474
    String url="https://distorted.org/magic/cgi-bin/download.cgi";
475
    url += "?n="+name+"&r="+numRuns+"&p="+numPlay+"&c="+country+"&e="+mVersion;
476

    
477
    return url;
478
    }
479

    
480
///////////////////////////////////////////////////////////////////////////////////////////////////
481

    
482
  private String constructSubmitURL()
483
    {
484
    RubikScores scores = RubikScores.getInstance();
485
    String name = URLencode(scores.getName());
486
    String veri = scores.isVerified() ? "1" : "";
487
    int numRuns = scores.getNumRuns();
488
    int numPlay = scores.getNumPlays();
489
    int deviceID= scores.getDeviceID();
490
    String reclist = scores.getRecordList("&o=","&l=","&t=");
491
    String country = scores.getCountry();
492
    long epoch = System.currentTimeMillis();
493
    String salt = "cuboid";
494

    
495
    String renderer = DistortedLibrary.getDriverRenderer();
496
    String version  = DistortedLibrary.getDriverVersion();
497

    
498
    int type = getRendererType(renderer);
499
    renderer = parseRenderer(type,renderer);
500
    version  = parseVersion(type,version);
501

    
502
    String url1="https://distorted.org/magic/cgi-bin/submit.cgi";
503
    String url2 = "n="+name+"&v="+veri+"&r="+numRuns+"&p="+numPlay+"&i="+deviceID+"&e="+mVersion;
504
    url2 += "&d="+renderer+"&s="+version+reclist+"&c="+country+"&f="+epoch;
505
    String hash = computeHash( url2, salt.getBytes() );
506

    
507
    return url1 + "?" + url2 + "&h=" + hash;
508
    }
509

    
510
///////////////////////////////////////////////////////////////////////////////////////////////////
511

    
512
  private boolean gottaDownload()
513
    {
514
    return ((mScores.length()==0) && !mRunning);
515
    }
516

    
517
///////////////////////////////////////////////////////////////////////////////////////////////////
518

    
519
  private void figureOutVersion(FragmentActivity act)
520
    {
521
    try
522
      {
523
      PackageInfo pInfo = act.getPackageManager().getPackageInfo( act.getPackageName(), 0);
524
      mVersion = pInfo.versionName;
525
      }
526
    catch (PackageManager.NameNotFoundException e)
527
      {
528
      mVersion = "0.9.2";
529
      }
530
    }
531

    
532
///////////////////////////////////////////////////////////////////////////////////////////////////
533

    
534
  private void downloadThread()
535
    {
536
    try
537
      {
538
      if( gottaDownload() )
539
        {
540
        mRunning = true;
541
        boolean receiveValues = network(constructDownloadURL());
542

    
543
        if( mRunning )
544
          {
545
          receiveValues = fillValuesNormal();
546
          mRunning = false;
547
          }
548

    
549
        if( receiveValues && mReceiver!=null ) mReceiver.receive(mCountry, mName, mTime);
550
        }
551
      }
552
    catch( Exception e )
553
      {
554
      if( mReceiver!=null ) mReceiver.message("Exception downloading records: "+e.getMessage() );
555
      }
556
    }
557

    
558
///////////////////////////////////////////////////////////////////////////////////////////////////
559

    
560
  private void submitThread()
561
    {
562
    try
563
      {
564
      mRunning = true;
565
      RubikScores scores = RubikScores.getInstance();
566

    
567
      if( scores.thereAreUnsubmittedRecords() )
568
        {
569
        boolean receiveValues = network(constructSubmitURL());
570

    
571
        if( mRunning )
572
          {
573
          receiveValues = fillValuesNormal();
574
          mRunning = false;
575
          }
576

    
577
        if( receiveValues )
578
          {
579
          RubikScores.getInstance().successfulSubmit();
580
          if( mReceiver!=null ) mReceiver.receive(mCountry, mName, mTime);
581
          }
582
        }
583
      }
584
    catch( Exception e )
585
      {
586
      if( mReceiver!=null ) mReceiver.message("Exception submitting records: "+e.getMessage() );
587
      }
588
    }
589

    
590
///////////////////////////////////////////////////////////////////////////////////////////////////
591

    
592
  private void debugThread()
593
    {
594
    String url = constructDebugURL();
595
/*
596
    try { Thread.sleep(5000); }
597
    catch( InterruptedException ignored) {}
598
*/
599
    try
600
      {
601
      java.net.URL connectURL = new URL(url);
602
      HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
603

    
604
      conn.setDoInput(true);
605
      conn.setDoOutput(true);
606
      conn.setUseCaches(false);
607
      conn.setRequestMethod("GET");
608
      conn.connect();
609
      conn.getOutputStream().flush();
610

    
611
      InputStream is = conn.getInputStream();
612
      BufferedReader r = new BufferedReader(new InputStreamReader(is));
613
      StringBuilder answer = new StringBuilder();
614

    
615
      for (String line; (line = r.readLine()) != null; )
616
        {
617
        answer.append(line).append('\n');
618
        }
619

    
620
      String updates = answer.toString();
621
      mUpdates.parse(updates);
622

    
623
      if( mUpdatee!=null ) mUpdatee.receiveUpdate(mUpdates);
624
      mDebugState = DEBUG_SUCCESS;
625
      }
626
    catch( final Exception e )
627
      {
628
      if( mUpdatee!=null ) mUpdatee.errorUpdate();
629
      mDebugState = DEBUG_FAILURE;
630
      }
631
    }
632

    
633
///////////////////////////////////////////////////////////////////////////////////////////////////
634

    
635
  private void suspiciousThread()
636
    {
637
    String url = constructSuspiciousURL();
638

    
639
    try
640
      {
641
      java.net.URL connectURL = new URL(url);
642
      HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
643

    
644
      conn.setDoInput(true);
645
      conn.setDoOutput(true);
646
      conn.setUseCaches(false);
647
      conn.setRequestMethod("GET");
648
      conn.connect();
649
      conn.getOutputStream().flush();
650
      conn.getInputStream();
651
      }
652
    catch( final Exception e )
653
      {
654
      // ignore
655
      }
656
    }
657

    
658
///////////////////////////////////////////////////////////////////////////////////////////////////
659

    
660
  private RubikNetwork()
661
    {
662

    
663
    }
664

    
665
///////////////////////////////////////////////////////////////////////////////////////////////////
666
// PUBLIC API
667
///////////////////////////////////////////////////////////////////////////////////////////////////
668

    
669
  public static void onPause()
670
    {
671
    mRunning = false;
672
    }
673

    
674
///////////////////////////////////////////////////////////////////////////////////////////////////
675

    
676
  public static RubikNetwork getInstance()
677
    {
678
    if( mThis==null )
679
      {
680
      mThis = new RubikNetwork();
681
      }
682

    
683
    return mThis;
684
    }
685

    
686
///////////////////////////////////////////////////////////////////////////////////////////////////
687

    
688
  public void download(Receiver receiver, FragmentActivity act)
689
    {
690
    initializeStatics();
691
    mReceiver = receiver;
692
    figureOutVersion(act);
693

    
694
    Thread thread = new Thread()
695
      {
696
      public void run()
697
        {
698
        downloadThread();
699
        }
700
      };
701

    
702
    thread.start();
703
    }
704

    
705
///////////////////////////////////////////////////////////////////////////////////////////////////
706

    
707
  public void submit(Receiver receiver, FragmentActivity act)
708
    {
709
    initializeStatics();
710
    mReceiver = receiver;
711
    figureOutVersion(act);
712

    
713
    Thread thread = new Thread()
714
      {
715
      public void run()
716
        {
717
        submitThread();
718
        }
719
      };
720

    
721
    thread.start();
722
    }
723

    
724
///////////////////////////////////////////////////////////////////////////////////////////////////
725

    
726
  public void debug()
727
    {
728
    initializeStatics();
729
    mDebugState = DEBUG_RUNNING;
730

    
731
    Thread thread = new Thread()
732
      {
733
      public void run()
734
        {
735
        debugThread();
736
        }
737
      };
738

    
739
    thread.start();
740
    }
741

    
742
///////////////////////////////////////////////////////////////////////////////////////////////////
743

    
744
  public void suspicious(String suspicious)
745
    {
746
    initializeStatics();
747
    mSuspicious = suspicious;
748

    
749
    Thread thread = new Thread()
750
      {
751
      public void run()
752
        {
753
        suspiciousThread();
754
        }
755
      };
756

    
757
    thread.start();
758
    }
759

    
760
///////////////////////////////////////////////////////////////////////////////////////////////////
761
// Yes it can happen that the second Updatee registers before we sent an update to the first one
762
// and, as a result, the update never gets sent to the first one. This is not a problem (now, when
763
// there are only two updatees - the RubikStatePlay and the UpdateDialog)
764
//
765
// Yes, there is also a remote possibility that the two threads executing this function and executing
766
// the sendDebug() get swapped exactly in unlucky moment and the update never gets to the updatee.
767
// We don't care about such remote possibility, then the app simply would signal that there are no
768
// updates available.
769

    
770
  public void signUpForUpdates(Updatee updatee)
771
    {
772
         if( mDebugState==DEBUG_SUCCESS ) updatee.receiveUpdate(mUpdates);
773
    else if( mDebugState==DEBUG_FAILURE ) updatee.errorUpdate();
774
    else mUpdatee = updatee;
775
    }
776

    
777
///////////////////////////////////////////////////////////////////////////////////////////////////
778

    
779
  public void downloadIcons(Updatee updatee)
780
    {
781

    
782
    }
783

    
784
///////////////////////////////////////////////////////////////////////////////////////////////////
785

    
786
  public void updateDone(String shortName)
787
    {
788
    mUpdates.updateDone(shortName);
789
    }
790
}
(1-1/3)