Project

General

Profile

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

magiccube / src / main / java / org / distorted / external / RubikNetwork.java @ 5bda8973

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2019 Leszek Koltunski                                                               //
3
//                                                                                               //
4
// This file is part of Magic Cube.                                                              //
5
//                                                                                               //
6
// Magic Cube is proprietary software licensed under an EULA which you should have received      //
7
// along with the code. If not, check https://distorted.org/magic/License-Magic-Cube.html        //
8
///////////////////////////////////////////////////////////////////////////////////////////////////
9

    
10
package org.distorted.external;
11

    
12
import java.io.BufferedReader;
13
import java.io.IOException;
14
import java.io.InputStream;
15
import java.io.InputStreamReader;
16
import java.net.HttpURLConnection;
17
import java.net.URL;
18
import java.net.UnknownHostException;
19
import java.security.MessageDigest;
20
import java.security.NoSuchAlgorithmException;
21

    
22
import android.app.Activity;
23
import android.content.Context;
24
import android.content.pm.PackageInfo;
25
import android.content.pm.PackageManager;
26
import android.graphics.Bitmap;
27
import android.graphics.BitmapFactory;
28

    
29
import org.distorted.library.main.DistortedLibrary;
30
import org.distorted.objectlib.json.JsonWriter;
31
import org.distorted.objects.RubikObjectList;
32

    
33
import static org.distorted.main.RubikActivity.SHOW_DOWNLOADED_DEBUG;
34
import static org.distorted.screens.RubikScreenPlay.LEVELS_SHOWN;
35

    
36
///////////////////////////////////////////////////////////////////////////////////////////////////
37

    
38
public class RubikNetwork
39
  {
40
  public interface ScoresReceiver
41
    {
42
    void receive(String[][][] country, String[][][] name, float[][][] time);
43
    void message(String mess);
44
    void error(String error);
45
    }
46

    
47
  public interface IconReceiver
48
    {
49
    void iconDownloaded(int ordinal, Bitmap bitmap, boolean downloaded);
50
    }
51

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

    
58
  public interface Downloadee
59
    {
60
    void jsonDownloaded();
61
    }
62

    
63
  public static final int MAX_PLACES = 10;
64

    
65
  private static final int REND_ADRENO= 0;
66
  private static final int REND_MALI  = 1;
67
  private static final int REND_POWER = 2;
68
  private static final int REND_OTHER = 3;
69

    
70
  private static final int DEBUG_RUNNING = 1;
71
  private static final int DEBUG_SUCCESS = 2;
72
  private static final int DEBUG_FAILURE = 3;
73

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

    
109
  private static final String SERVER="https://distorted.org/magic/cgi-bin/";
110

    
111
  private static String[][][] mCountry;
112
  private static String[][][] mName;
113
  private static float[][][] mTime;
114
  private static int[][] mPlaces;
115

    
116
  private static RubikNetwork mThis;
117
  private static String mScores = "";
118
  private static boolean mRunning = false;
119
  private static Updatee mUpdatee;
120
  private static String mVersion;
121
  private static int mNumObjects;
122
  private static RubikUpdates mUpdates;
123
  private static int mDebugState;
124

    
125
///////////////////////////////////////////////////////////////////////////////////////////////////
126

    
127
  private static void initializeStatics()
128
    {
129
    int newNum = RubikObjectList.getNumObjects();
130

    
131
    if( mCountry==null || newNum!=mNumObjects ) mCountry = new String[newNum][LEVELS_SHOWN+1][MAX_PLACES];
132
    if( mName==null    || newNum!=mNumObjects ) mName    = new String[newNum][LEVELS_SHOWN+1][MAX_PLACES];
133
    if( mTime==null    || newNum!=mNumObjects ) mTime    = new  float[newNum][LEVELS_SHOWN+1][MAX_PLACES];
134
    if( mPlaces==null  || newNum!=mNumObjects ) mPlaces  = new    int[newNum][LEVELS_SHOWN+1];
135

    
136
    if( mUpdates==null ) mUpdates = new RubikUpdates();
137

    
138
    mNumObjects = newNum;
139
    }
140

    
141
///////////////////////////////////////////////////////////////////////////////////////////////////
142

    
143
  private static String computeHash(String stringToHash, byte[] salt)
144
    {
145
    String generatedPassword;
146

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

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

    
159
      generatedPassword = sb.toString();
160
      }
161
    catch (NoSuchAlgorithmException e)
162
      {
163
      return "NoSuchAlgorithm";
164
      }
165

    
166
    return generatedPassword;
167
    }
168

    
169
///////////////////////////////////////////////////////////////////////////////////////////////////
170

    
171
  private boolean fillValuesNormal(ScoresReceiver receiver)
172
    {
173
    int begin=-1 ,end, len = mScores.length();
174
    String row;
175

    
176
    if( len==0 )
177
      {
178
      receiver.error("1");
179
      return false;
180
      }
181
    else if( len<=2 )
182
      {
183
      receiver.error(mScores);
184
      return false;
185
      }
186

    
187
    for(int i=0; i<mNumObjects; i++)
188
      for(int j=0; j<=LEVELS_SHOWN; j++)
189
        {
190
        mPlaces[i][j] = 0;
191
        }
192

    
193
    while( begin<len )
194
      {
195
      end = mScores.indexOf('\n', begin+1);
196
      if( end<0 ) end = len;
197

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

    
208
      begin = end;
209
      }
210

    
211
    return true;
212
    }
213

    
214
///////////////////////////////////////////////////////////////////////////////////////////////////
215

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

    
224
    if( s5>s4 && s4>s3 && s3>s2 && s2>s1 && s1>0 )
225
      {
226
      int object = RubikObjectList.getOrdinal( row.substring(0,s1) );
227

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

    
235
        if( country.equals("do") ) country = "dm"; // see RubikScores.setCountry()
236

    
237
        if( level>LEVELS_SHOWN ) level = LEVELS_SHOWN;
238

    
239
        if(level>=0)
240
          {
241
          int p = mPlaces[object][level];
242
          mPlaces[object][level]++;
243

    
244
          mCountry[object][level][p] = country;
245
          mName   [object][level][p] = name;
246
          mTime   [object][level][p] = ((float)(time/10))/100.0f;
247
          }
248
        }
249
      }
250
    else
251
      {
252
      tryDoCommand(row);
253
      }
254
    }
255

    
256
///////////////////////////////////////////////////////////////////////////////////////////////////
257

    
258
  private void tryDoCommand(String row)
259
    {
260
    if( row.startsWith("comm") )
261
      {
262
      int colon = row.indexOf(':');
263

    
264
      if( colon>0 )
265
        {
266
        String commandNumber = row.substring(4,colon);
267
        int number;
268

    
269
        try
270
          {
271
          number = Integer.parseInt(commandNumber);
272
          }
273
        catch(NumberFormatException ex)
274
          {
275
          number=0;
276
          }
277

    
278
        if(number==1)
279
          {
280
          String country = row.substring(colon+1);
281
          RubikScores scores = RubikScores.getInstance();
282
          scores.setCountry(country);
283
          }
284
        }
285
      }
286
    }
287

    
288
///////////////////////////////////////////////////////////////////////////////////////////////////
289

    
290
  private int getRendererType(String renderer)
291
    {
292
    if( renderer.contains("Adreno")  ) return REND_ADRENO;
293
    if( renderer.contains("Mali")    ) return REND_MALI;
294
    if( renderer.contains("PowerVR") ) return REND_POWER;
295

    
296
    return REND_OTHER;
297
    }
298

    
299
///////////////////////////////////////////////////////////////////////////////////////////////////
300

    
301
  private String parseRenderer(final int type, String renderer)
302
    {
303
    if( type==REND_ADRENO || type==REND_POWER )
304
      {
305
      int lastSpace = renderer.lastIndexOf(' ');
306
      String ret = renderer.substring(lastSpace+1);
307
      return URLencode(ret);
308
      }
309

    
310
    if( type==REND_MALI )
311
      {
312
      int firstHyphen = renderer.indexOf('-');
313
      String ret = renderer.substring(firstHyphen+1);
314
      return URLencode(ret);
315
      }
316

    
317
    return "other";
318
    }
319

    
320
///////////////////////////////////////////////////////////////////////////////////////////////////
321

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

    
342
///////////////////////////////////////////////////////////////////////////////////////////////////
343

    
344
  private String URLencode(String s)
345
    {
346
    StringBuilder sbuf = new StringBuilder();
347
    int len = s.length();
348

    
349
    for (int i = 0; i < len; i++)
350
      {
351
      int ch = s.charAt(i);
352

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

    
376
    return sbuf.toString();
377
    }
378

    
379
///////////////////////////////////////////////////////////////////////////////////////////////////
380

    
381
  private boolean network(String url, ScoresReceiver receiver)
382
    {
383
    try
384
      {
385
      java.net.URL connectURL = new URL(url);
386
      HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
387

    
388
      conn.setDoInput(true);
389
      conn.setDoOutput(true);
390
      conn.setUseCaches(false);
391
      conn.setRequestMethod("GET");
392
      conn.connect();
393
      conn.getOutputStream().flush();
394

    
395
      InputStream is = conn.getInputStream();
396
      BufferedReader r = new BufferedReader(new InputStreamReader(is));
397
      StringBuilder total = new StringBuilder();
398

    
399
      for (String line; (line = r.readLine()) != null; )
400
        {
401
        total.append(line).append('\n');
402
        }
403

    
404
      mScores = total.toString();
405
      conn.disconnect();
406
      }
407
    catch( final UnknownHostException e )
408
      {
409
      receiver.message("No access to Internet");
410
      return false;
411
      }
412
    catch( final SecurityException e )
413
      {
414
      receiver.message("Application not authorized to connect to the Internet");
415
      return false;
416
      }
417
    catch( final Exception e )
418
      {
419
      receiver.message(e.getMessage());
420
      return false;
421
      }
422

    
423
    if( mScores.length()==0 )
424
      {
425
      receiver.message("Failed to download scores");
426
      return false;
427
      }
428

    
429
    return true;
430
    }
431

    
432
///////////////////////////////////////////////////////////////////////////////////////////////////
433

    
434
  private String constructSuspiciousURL(String suspURL)
435
    {
436
    RubikScores scores = RubikScores.getInstance();
437
    int deviceID       = scores.getDeviceID();
438
    String suspicious  = URLencode(suspURL);
439

    
440
    return SERVER+"suspicious.cgi?i="+deviceID+"&d="+suspicious;
441
    }
442

    
443
///////////////////////////////////////////////////////////////////////////////////////////////////
444

    
445
  private String constructTokenURL(String token)
446
    {
447
    RubikScores scores = RubikScores.getInstance();
448
    String name = URLencode(scores.getName());
449
    int deviceID= scores.getDeviceID();
450
    String country = scores.getCountry();
451
    String version = mVersion==null ? "null" : mVersion;
452
    String tkn = URLencode(token);
453

    
454
    return SERVER+"token.cgi?n="+name+"&i="+deviceID+"&e="+version+"&c="+country+"&t="+tkn;
455
    }
456

    
457
///////////////////////////////////////////////////////////////////////////////////////////////////
458

    
459
  private String constructDebugURL()
460
    {
461
    RubikScores scores = RubikScores.getInstance();
462
    String name = URLencode(scores.getName());
463
    int numRuns = scores.getNumRuns();
464
    int numPlay = scores.getNumPlays();
465
    String country = scores.getCountry();
466
    String renderer = DistortedLibrary.getDriverRenderer();
467
    String version  = DistortedLibrary.getDriverVersion();
468
    int objectAPI   = JsonWriter.VERSION_OBJECT_MAJOR;
469
    int tutorialAPI = JsonWriter.VERSION_EXTRAS_MAJOR;
470

    
471
    renderer = URLencode(renderer);
472
    version  = URLencode(version);
473

    
474
    String url=SERVER+"debugs.cgi";
475
    url += "?n="+name+"&r="+numRuns+"&p="+numPlay+"&c="+country+"&e="+mVersion+"d";
476
    url += "&d="+renderer+"&v="+version+"&a="+objectAPI+"&b="+tutorialAPI;
477

    
478
    return url;
479
    }
480

    
481
///////////////////////////////////////////////////////////////////////////////////////////////////
482

    
483
  private String constructDownloadURL()
484
    {
485
    RubikScores scores = RubikScores.getInstance();
486
    String name = URLencode(scores.getName());
487
    int numRuns = scores.getNumRuns();
488
    int numPlay = scores.getNumPlays();
489
    String country = scores.getCountry();
490

    
491
    return SERVER+"download.cgi?n="+name+"&r="+numRuns+"&p="+numPlay+"&c="+country+"&e="+mVersion;
492
    }
493

    
494
///////////////////////////////////////////////////////////////////////////////////////////////////
495

    
496
  private String constructSubmitURL()
497
    {
498
    RubikScores scores = RubikScores.getInstance();
499
    String name = URLencode(scores.getName());
500
    String veri = scores.isVerified() ? "1" : "";
501
    int numRuns = scores.getNumRuns();
502
    int numPlay = scores.getNumPlays();
503
    int deviceID= scores.getDeviceID();
504
    String reclist = scores.getRecordList("&o=","&l=","&t=");
505
    String country = scores.getCountry();
506
    long epoch = System.currentTimeMillis();
507
    String salt = "cuboid";
508

    
509
    String renderer = DistortedLibrary.getDriverRenderer();
510
    String version  = DistortedLibrary.getDriverVersion();
511

    
512
    int type = getRendererType(renderer);
513
    renderer = parseRenderer(type,renderer);
514
    version  = parseVersion(type,version);
515

    
516
    String url1=SERVER+"submit.cgi";
517
    String url2 = "n="+name+"&v="+veri+"&r="+numRuns+"&p="+numPlay+"&i="+deviceID+"&e="+mVersion;
518
    url2 += "&d="+renderer+"&s="+version+reclist+"&c="+country+"&f="+epoch;
519
    String hash = computeHash( url2, salt.getBytes() );
520

    
521
    return url1 + "?" + url2 + "&h=" + hash;
522
    }
523

    
524
///////////////////////////////////////////////////////////////////////////////////////////////////
525

    
526
  private boolean gottaDownload()
527
    {
528
    return ((mScores.length()==0) && !mRunning);
529
    }
530

    
531
///////////////////////////////////////////////////////////////////////////////////////////////////
532

    
533
  private void figureOutVersion(Activity act)
534
    {
535
    if( mVersion==null )
536
      {
537
      try
538
        {
539
        PackageInfo pInfo = act.getPackageManager().getPackageInfo( act.getPackageName(), 0);
540
        mVersion = pInfo.versionName;
541
        }
542
      catch (PackageManager.NameNotFoundException e)
543
        {
544
        mVersion = "0.9.2";
545
        }
546
      }
547
    }
548

    
549
///////////////////////////////////////////////////////////////////////////////////////////////////
550

    
551
  private void downloadThread(ScoresReceiver receiver)
552
    {
553
    boolean receiveValues=true;
554

    
555
    try
556
      {
557
      if( gottaDownload() )
558
        {
559
        mRunning = true;
560
        receiveValues = network(constructDownloadURL(),receiver);
561

    
562
        if( mRunning )
563
          {
564
          receiveValues = fillValuesNormal(receiver);
565
          mRunning = false;
566
          }
567
        }
568
      if( receiveValues ) receiver.receive(mCountry, mName, mTime);
569
      }
570
    catch( Exception e )
571
      {
572
      receiver.message("Exception downloading records: "+e.getMessage() );
573
      }
574
    }
575

    
576
///////////////////////////////////////////////////////////////////////////////////////////////////
577

    
578
  private void submitThread(ScoresReceiver receiver)
579
    {
580
    try
581
      {
582
      mRunning = true;
583
      RubikScores scores = RubikScores.getInstance();
584

    
585
      if( scores.thereAreUnsubmittedRecords() )
586
        {
587
        boolean receiveValues = network(constructSubmitURL(),receiver);
588

    
589
        if( mRunning )
590
          {
591
          receiveValues = fillValuesNormal(receiver);
592
          mRunning = false;
593
          }
594

    
595
        if( receiveValues )
596
          {
597
          RubikScores.getInstance().successfulSubmit();
598
          receiver.receive(mCountry, mName, mTime);
599
          }
600
        }
601
      }
602
    catch( Exception e )
603
      {
604
      receiver.message("Exception submitting records: "+e.getMessage() );
605
      }
606
    }
607

    
608
///////////////////////////////////////////////////////////////////////////////////////////////////
609

    
610
  private void debugThread()
611
    {
612
    String url = constructDebugURL();
613

    
614
    try
615
      {
616
      java.net.URL connectURL = new URL(url);
617
      HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
618

    
619
      conn.setDoInput(true);
620
      conn.setDoOutput(true);
621
      conn.setUseCaches(false);
622
      conn.setRequestMethod("GET");
623
      conn.connect();
624
      conn.getOutputStream().flush();
625

    
626
      InputStream is = conn.getInputStream();
627
      BufferedReader r = new BufferedReader(new InputStreamReader(is));
628
      StringBuilder answer = new StringBuilder();
629

    
630
      for (String line; (line = r.readLine()) != null; )
631
        {
632
        answer.append(line).append('\n');
633
        }
634

    
635
      String updates = answer.toString();
636
      conn.disconnect();
637
      mUpdates.parse(updates);
638

    
639
      if( mUpdatee!=null ) mUpdatee.receiveUpdate(mUpdates);
640
      mDebugState = DEBUG_SUCCESS;
641
      }
642
    catch( final Exception e )
643
      {
644
      if( mUpdatee!=null ) mUpdatee.errorUpdate();
645
      mDebugState = DEBUG_FAILURE;
646
      }
647
    }
648

    
649
///////////////////////////////////////////////////////////////////////////////////////////////////
650

    
651
  private void suspiciousThread(String suspURL)
652
    {
653
    String url = constructSuspiciousURL(suspURL);
654

    
655
    try
656
      {
657
      java.net.URL connectURL = new URL(url);
658
      HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
659

    
660
      conn.setDoInput(true);
661
      conn.setDoOutput(true);
662
      conn.setUseCaches(false);
663
      conn.setRequestMethod("GET");
664
      conn.connect();
665
      conn.getOutputStream().flush();
666
      conn.getInputStream();
667
      conn.disconnect();
668
      }
669
    catch( final Exception e )
670
      {
671
      // ignore
672
      }
673
    }
674

    
675
///////////////////////////////////////////////////////////////////////////////////////////////////
676

    
677
  private void tokenThread(String token)
678
    {
679
    String url = constructTokenURL(token);
680

    
681
    try
682
      {
683
      java.net.URL connectURL = new URL(url);
684
      HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
685

    
686
      conn.setDoInput(true);
687
      conn.setDoOutput(true);
688
      conn.setUseCaches(false);
689
      conn.setRequestMethod("GET");
690
      conn.connect();
691
      conn.getOutputStream().flush();
692
      conn.getInputStream();
693
      conn.disconnect();
694
      }
695
    catch( final Exception e )
696
      {
697
      // ignore
698
      }
699
    }
700

    
701
///////////////////////////////////////////////////////////////////////////////////////////////////
702

    
703
  private Bitmap downloadIcon(String url)
704
    {
705
    try
706
      {
707
      java.net.URL connectURL = new URL(url);
708
      HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();
709
      conn.setDoInput(true);
710
      conn.connect();
711
      InputStream input = conn.getInputStream();
712
      Bitmap icon = BitmapFactory.decodeStream(input);
713
      conn.disconnect();
714
      return icon;
715
      }
716
    catch (IOException e)
717
      {
718
      android.util.Log.e("D", "Failed to download "+url);
719
      android.util.Log.e("D", e.getMessage() );
720
      return null;
721
      }
722
    }
723

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

    
726
  private void iconThread(Context context, IconReceiver receiver)
727
    {
728
    int numC = mUpdates.getCompletedNumber();
729
    int numS = mUpdates.getStartedNumber();
730

    
731
    for(int c=0; c<numC; c++)
732
      {
733
      int iconPresent = mUpdates.getCompletedIconPresent(c);
734

    
735
      if( iconPresent!=0 )
736
        {
737
        boolean downloaded = false;
738
        Bitmap icon = mUpdates.getCompletedIcon(context,c);
739

    
740
        if( icon==null )
741
          {
742
          String url = mUpdates.getCompletedURL(c);
743
          icon = downloadIcon(url);
744
          downloaded = true;
745

    
746
          if( SHOW_DOWNLOADED_DEBUG ) android.util.Log.e("D", "Downloading icon "+url);
747
          }
748
        if( icon!=null )
749
          {
750
          mUpdates.setCompletedIcon(c,icon);
751
          receiver.iconDownloaded(c,icon,downloaded);
752
          }
753
        }
754
      }
755

    
756
    for(int s=0; s<numS; s++)
757
      {
758
      int iconPresent = mUpdates.getStartedIconPresent(s);
759

    
760
      if( iconPresent!=0 )
761
        {
762
        boolean downloaded = false;
763
        Bitmap icon = mUpdates.getStartedIcon(context,s);
764

    
765
        if( icon==null )
766
          {
767
          String url = mUpdates.getStartedURL(s);
768
          icon = downloadIcon(url);
769
          downloaded = true;
770

    
771
          if( SHOW_DOWNLOADED_DEBUG ) android.util.Log.e("D", "Downloading icon "+url);
772
          }
773
        if( icon!=null )
774
          {
775
          mUpdates.setStartedIcon(s,icon);
776
          receiver.iconDownloaded(numC+s,icon,downloaded);
777
          }
778
        }
779
      }
780
    }
781

    
782
///////////////////////////////////////////////////////////////////////////////////////////////////
783

    
784
  private InputStream downloadJSON(String name)
785
    {
786
    String url = mUpdates.getURL() + name;
787

    
788
    try
789
      {
790
      if( SHOW_DOWNLOADED_DEBUG ) android.util.Log.e("D", "Downloading JSON "+url);
791

    
792
      java.net.URL connectURL = new URL(url);
793
      HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();
794
      conn.setDoInput(true);
795
      conn.connect();
796
      return conn.getInputStream();
797
      }
798
    catch (IOException e)
799
      {
800
      android.util.Log.e("D", "Failed to download "+url);
801
      android.util.Log.e("D", e.getMessage() );
802
      return null;
803
      }
804
    }
805

    
806
///////////////////////////////////////////////////////////////////////////////////////////////////
807

    
808
  private void jsonThread(final RubikUpdates.UpdateInfo info, Downloadee downloadee)
809
    {
810
    if(info.mUpdateObject) info.mObjectStream = downloadJSON(info.mObjectShortName+"_object.json");
811
    if(info.mUpdateExtras) info.mExtrasStream = downloadJSON(info.mObjectShortName+"_extras.json");
812

    
813
    downloadee.jsonDownloaded();
814

    
815
    try
816
      {
817
      if( info.mObjectStream!=null ) info.mObjectStream.close();
818
      }
819
    catch(IOException ioe)
820
      {
821
      android.util.Log.e("D", "failed to close object input stream");
822
      }
823

    
824
    try
825
      {
826
      if( info.mExtrasStream!=null ) info.mExtrasStream.close();
827
      }
828
    catch(IOException ioe)
829
      {
830
      android.util.Log.e("D", "failed to close extras input stream");
831
      }
832
    }
833

    
834
///////////////////////////////////////////////////////////////////////////////////////////////////
835

    
836
  private RubikNetwork()
837
    {
838

    
839
    }
840

    
841
///////////////////////////////////////////////////////////////////////////////////////////////////
842
// PUBLIC API
843
///////////////////////////////////////////////////////////////////////////////////////////////////
844

    
845
  public static void onPause()
846
    {
847
    mRunning = false;
848
    }
849

    
850
///////////////////////////////////////////////////////////////////////////////////////////////////
851

    
852
  public static RubikNetwork getInstance()
853
    {
854
    if( mThis==null ) mThis = new RubikNetwork();
855
    return mThis;
856
    }
857

    
858
///////////////////////////////////////////////////////////////////////////////////////////////////
859

    
860
  public void download(final ScoresReceiver receiver, final Activity act)
861
    {
862
    initializeStatics();
863
    figureOutVersion(act);
864

    
865
    Thread thread = new Thread()
866
      {
867
      public void run()
868
        {
869
        downloadThread(receiver);
870
        }
871
      };
872

    
873
    thread.start();
874
    }
875

    
876
///////////////////////////////////////////////////////////////////////////////////////////////////
877

    
878
  public void submit(ScoresReceiver receiver, final Activity act)
879
    {
880
    initializeStatics();
881
    figureOutVersion(act);
882

    
883
    Thread thread = new Thread()
884
      {
885
      public void run()
886
        {
887
        submitThread(receiver);
888
        }
889
      };
890

    
891
    thread.start();
892
    }
893

    
894
///////////////////////////////////////////////////////////////////////////////////////////////////
895

    
896
  public void debug(final Activity act)
897
    {
898
    initializeStatics();
899
    figureOutVersion(act);
900
    mDebugState = DEBUG_RUNNING;
901

    
902
    Thread thread = new Thread()
903
      {
904
      public void run()
905
        {
906
        debugThread();
907
        }
908
      };
909

    
910
    thread.start();
911
    }
912

    
913
///////////////////////////////////////////////////////////////////////////////////////////////////
914

    
915
  public void suspicious(final String suspicious, final Activity act)
916
    {
917
    initializeStatics();
918
    figureOutVersion(act);
919

    
920
    Thread thread = new Thread()
921
      {
922
      public void run()
923
        {
924
        suspiciousThread(suspicious);
925
        }
926
      };
927

    
928
    thread.start();
929
    }
930

    
931
///////////////////////////////////////////////////////////////////////////////////////////////////
932

    
933
  public void token(final String token)
934
    {
935
    initializeStatics();
936

    
937
    Thread thread = new Thread()
938
      {
939
      public void run()
940
        {
941
        tokenThread(token);
942
        }
943
      };
944

    
945
    thread.start();
946
    }
947

    
948
///////////////////////////////////////////////////////////////////////////////////////////////////
949
// Yes it can happen that the second Updatee registers before we sent an update to the first one
950
// and, as a result, the update never gets sent to the first one. This is not a problem (now, when
951
// there are only two updatees - the RubikStatePlay and the UpdateDialog)
952
//
953
// Yes, there is also a remote possibility that the two threads executing this function and executing
954
// the sendDebug() get swapped exactly in unlucky moment and the update never gets to the updatee.
955
// We don't care about such remote possibility, then the app simply would signal that there are no
956
// updates available.
957

    
958
  public void signUpForUpdates(Updatee updatee)
959
    {
960
         if( mDebugState==DEBUG_SUCCESS ) updatee.receiveUpdate(mUpdates);
961
    else if( mDebugState==DEBUG_FAILURE ) updatee.errorUpdate();
962
    else mUpdatee = updatee;
963
    }
964

    
965
///////////////////////////////////////////////////////////////////////////////////////////////////
966

    
967
  public void downloadIcons(final Context context, final IconReceiver receiver)
968
    {
969
    initializeStatics();
970

    
971
    Thread thread = new Thread()
972
      {
973
      public void run()
974
        {
975
        iconThread(context,receiver);
976
        }
977
      };
978

    
979
    thread.start();
980
    }
981

    
982
///////////////////////////////////////////////////////////////////////////////////////////////////
983

    
984
  public void downloadJSON(final RubikUpdates.UpdateInfo info, final Downloadee downloadee)
985
    {
986
    initializeStatics();
987

    
988
    Thread thread = new Thread()
989
      {
990
      public void run()
991
        {
992
        jsonThread(info,downloadee);
993
        }
994
      };
995

    
996
    thread.start();
997
    }
998

    
999
///////////////////////////////////////////////////////////////////////////////////////////////////
1000

    
1001
  public void updateDone(String shortName)
1002
    {
1003
    mUpdates.updateDone(shortName);
1004
    mScores = "";
1005
    }
1006
}
(2-2/4)