Project

General

Profile

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

magiccube / src / main / java / org / distorted / network / RubikNetwork.java @ 8ab435b9

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.InputStream;
23
import java.net.HttpURLConnection;
24
import java.net.URL;
25
import java.net.UnknownHostException;
26
import java.security.MessageDigest;
27
import java.security.NoSuchAlgorithmException;
28

    
29
import android.app.Activity;
30
import android.content.pm.PackageInfo;
31
import android.content.pm.PackageManager;
32

    
33
import androidx.appcompat.app.AppCompatActivity;
34
import androidx.fragment.app.FragmentActivity;
35

    
36
import org.distorted.library.main.DistortedLibrary;
37
import org.distorted.objectlib.main.ObjectType;
38

    
39
import static org.distorted.screens.RubikScreenPlay.MAX_LEVEL;
40
import static org.distorted.objectlib.main.ObjectType.NUM_OBJECTS;
41

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

    
44
public class RubikNetwork implements Runnable
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 static final int MAX_PLACES = 10;
54

    
55
  private static final int DOWNLOAD   = 0;
56
  private static final int SUBMIT     = 1;
57
  private static final int DEBUG      = 2;
58
  private static final int IDLE       = 3;
59

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

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

    
100
  private static String[][][] mCountry;
101
  private static String[][][] mName;
102
  private static float[][][] mTime;
103
  private static int[][] mPlaces;
104

    
105
  private static RubikNetwork mThis;
106
  private static String mScores = "";
107
  private static boolean mRunning = false;
108
  private static int mMode = IDLE;
109
  private static Receiver mReceiver;
110
  private static String mVersion;
111

    
112
///////////////////////////////////////////////////////////////////////////////////////////////////
113

    
114
  private static void initializeStatics()
115
    {
116
    if( mCountry==null ) mCountry = new String[NUM_OBJECTS][MAX_LEVEL][MAX_PLACES];
117
    if( mName==null    ) mName    = new String[NUM_OBJECTS][MAX_LEVEL][MAX_PLACES];
118
    if( mTime==null    ) mTime    = new  float[NUM_OBJECTS][MAX_LEVEL][MAX_PLACES];
119
    if( mPlaces==null  ) mPlaces  = new int[NUM_OBJECTS][MAX_LEVEL];
120
    }
121

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

    
124
  private static String computeHash(String stringToHash, byte[] salt)
125
    {
126
    String generatedPassword;
127

    
128
    try
129
      {
130
      MessageDigest md = MessageDigest.getInstance("MD5");
131
      md.update(salt);
132
      byte[] bytes = md.digest(stringToHash.getBytes());
133
      StringBuilder sb = new StringBuilder();
134

    
135
      for (byte aByte : bytes)
136
        {
137
        sb.append(Integer.toString((aByte & 0xff) + 0x100, 16).substring(1));
138
        }
139

    
140
      generatedPassword = sb.toString();
141
      }
142
    catch (NoSuchAlgorithmException e)
143
      {
144
      return "NoSuchAlgorithm";
145
      }
146

    
147
    return generatedPassword;
148
    }
149

    
150
///////////////////////////////////////////////////////////////////////////////////////////////////
151

    
152
  private boolean fillValues()
153
    {
154
    int begin=-1 ,end, len = mScores.length();
155
    String row;
156

    
157
    if( len==0 )
158
      {
159
      mReceiver.error("1");
160
      return false;
161
      }
162
    else if( len<=2 )
163
      {
164
      mReceiver.error(mScores);
165
      return false;
166
      }
167

    
168
    for(int i=0; i<NUM_OBJECTS; i++)
169
      for(int j=0; j<MAX_LEVEL; j++)
170
        {
171
        mPlaces[i][j] = 0;
172
        }
173

    
174
    while( begin<len )
175
      {
176
      end = mScores.indexOf('\n', begin+1);
177
      if( end<0 ) end = len;
178

    
179
      try
180
        {
181
        row = mScores.substring(begin+1,end);
182
        fillRow(row);
183
        }
184
      catch(Exception ex)
185
        {
186
        // faulty row - ignore
187
        }
188

    
189
      begin = end;
190
      }
191

    
192
    return true;
193
    }
194

    
195
///////////////////////////////////////////////////////////////////////////////////////////////////
196

    
197
  private void fillRow(String row)
198
    {
199
    int s1 = row.indexOf(' ');
200
    int s2 = row.indexOf(' ',s1+1);
201
    int s3 = row.indexOf(' ',s2+1);
202
    int s4 = row.indexOf(' ',s3+1);
203
    int s5 = row.length();
204

    
205
    if( s5>s4 && s4>s3 && s3>s2 && s2>s1 && s1>0 )
206
      {
207
      int object = ObjectType.getOrdinal( row.substring(0,s1) );
208

    
209
      if( object>=0 && object<NUM_OBJECTS )
210
        {
211
        int level      = Integer.parseInt( row.substring(s1+1,s2) );
212
        String name    = row.substring(s2+1, s3);
213
        int time       = Integer.parseInt( row.substring(s3+1,s4) );
214
        String country = row.substring(s4+1, s5);
215

    
216
        if( country.equals("do") ) country = "dm"; // see RubikScores.setCountry()
217

    
218
        if(level>=0 && level<MAX_LEVEL)
219
          {
220
          int p = mPlaces[object][level];
221
          mPlaces[object][level]++;
222

    
223
          mCountry[object][level][p] = country;
224
          mName   [object][level][p] = name;
225
          mTime   [object][level][p] = ((float)(time/10))/100.0f;
226
          }
227
        }
228
      }
229
    else
230
      {
231
      tryDoCommand(row);
232
      }
233
    }
234

    
235
///////////////////////////////////////////////////////////////////////////////////////////////////
236

    
237
  private void tryDoCommand(String row)
238
    {
239
    if( row.startsWith("comm") )
240
      {
241
      int colon = row.indexOf(':');
242

    
243
      if( colon>0 )
244
        {
245
        String commandNumber = row.substring(4,colon);
246
        int number;
247

    
248
        try
249
          {
250
          number = Integer.parseInt(commandNumber);
251
          }
252
        catch(NumberFormatException ex)
253
          {
254
          number=0;
255
          }
256

    
257
        if(number==1)
258
          {
259
          String country = row.substring(colon+1);
260
          RubikScores scores = RubikScores.getInstance();
261
          scores.setCountry(country);
262
          }
263
        }
264
      }
265
    }
266

    
267
///////////////////////////////////////////////////////////////////////////////////////////////////
268

    
269
  private int getRendererType(String renderer)
270
    {
271
    if( renderer.contains("Adreno")  ) return REND_ADRENO;
272
    if( renderer.contains("Mali")    ) return REND_MALI;
273
    if( renderer.contains("PowerVR") ) return REND_POWER;
274

    
275
    return REND_OTHER;
276
    }
277

    
278
///////////////////////////////////////////////////////////////////////////////////////////////////
279

    
280
  private String parseRenderer(final int type, String renderer)
281
    {
282
    if( type==REND_ADRENO || type==REND_POWER )
283
      {
284
      int lastSpace = renderer.lastIndexOf(' ');
285
      String ret = renderer.substring(lastSpace+1);
286
      return URLencode(ret);
287
      }
288

    
289
    if( type==REND_MALI )
290
      {
291
      int firstHyphen = renderer.indexOf('-');
292
      String ret = renderer.substring(firstHyphen+1);
293
      return URLencode(ret);
294
      }
295

    
296
    return "other";
297
    }
298

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

    
301
  private String parseVersion(final int type, String version)
302
    {
303
    switch(type)
304
      {
305
      case REND_ADRENO: int aMonkey = version.indexOf('@');
306
                        int aDot = version.indexOf('.', aMonkey);
307
                        String ret1 = aDot>=3 ? version.substring(aDot-3,aDot) : "";
308
                        return URLencode(ret1);
309
      case REND_MALI  : int mV1 = version.indexOf("v1");
310
                        int mHyphen = version.indexOf('-', mV1);
311
                        String ret2 = mHyphen>mV1+3 && mV1>=0 ? version.substring(mV1+3,mHyphen) : "";
312
                        return URLencode(ret2);
313
      case REND_POWER : int pMonkey = version.indexOf('@');
314
                        int pSpace  = version.lastIndexOf(' ');
315
                        String ret3 = pSpace>=0 && pMonkey>pSpace+1 ? version.substring(pSpace+1,pMonkey) : "";
316
                        return URLencode(ret3);
317
      default         : return "";
318
      }
319
    }
320

    
321
///////////////////////////////////////////////////////////////////////////////////////////////////
322

    
323
  private String URLencode(String s)
324
    {
325
    StringBuilder sbuf = new StringBuilder();
326
    int len = s.length();
327

    
328
    for (int i = 0; i < len; i++)
329
      {
330
      int ch = s.charAt(i);
331

    
332
           if ('A' <= ch && ch <= 'Z') sbuf.append((char)ch);
333
      else if ('a' <= ch && ch <= 'z') sbuf.append((char)ch);
334
      else if ('0' <= ch && ch <= '9') sbuf.append((char)ch);
335
      else if (ch == ' '             ) sbuf.append('+');
336
      else if (ch == '-' || ch == '_'
337
            || ch == '.' || ch == '!'
338
            || ch == '~' || ch == '*'
339
            || ch == '\'' || ch == '('
340
            || ch == ')'             ) sbuf.append((char)ch);
341
      else if (ch <= 0x007f)           sbuf.append(hex[ch]);
342
      else if (ch <= 0x07FF)
343
        {
344
        sbuf.append(hex[0xc0 | (ch >> 6)]);
345
        sbuf.append(hex[0x80 | (ch & 0x3F)]);
346
        }
347
      else
348
        {
349
        sbuf.append(hex[0xe0 | (ch >> 12)]);
350
        sbuf.append(hex[0x80 | ((ch >> 6) & 0x3F)]);
351
        sbuf.append(hex[0x80 | (ch & 0x3F)]);
352
        }
353
      }
354

    
355
    return sbuf.toString();
356
    }
357

    
358
///////////////////////////////////////////////////////////////////////////////////////////////////
359

    
360
  private void sendDebug()
361
    {
362
    String url = constructDebugURL();
363

    
364
    try
365
      {
366
      java.net.URL connectURL = new URL(url);
367
      HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
368

    
369
      conn.setDoInput(true);
370
      conn.setDoOutput(true);
371
      conn.setUseCaches(false);
372
      conn.setRequestMethod("GET");
373
      conn.connect();
374
      conn.getOutputStream().flush();
375
      conn.getInputStream();
376
      }
377
    catch( final Exception e )
378
      {
379
      // ignore
380
      }
381
    }
382

    
383
///////////////////////////////////////////////////////////////////////////////////////////////////
384

    
385
  private boolean network(String url)
386
    {
387
    try
388
      {
389
      java.net.URL connectURL = new URL(url);
390
      HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
391

    
392
      conn.setDoInput(true);
393
      conn.setDoOutput(true);
394
      conn.setUseCaches(false);
395
      conn.setRequestMethod("GET");
396
      conn.connect();
397
      conn.getOutputStream().flush();
398

    
399
      try( InputStream is = conn.getInputStream() )
400
        {
401
        int ch;
402
        StringBuilder sb = new StringBuilder();
403
        while( ( ch = is.read() ) != -1 )
404
          {
405
          sb.append( (char)ch );
406
          }
407
        mScores = sb.toString();
408
        }
409
      catch( final Exception e)
410
        {
411
        mReceiver.message("Failed to get an answer from the High Scores server");
412
        return false;
413
        }
414
      }
415
    catch( final UnknownHostException e )
416
      {
417
      mReceiver.message("No access to Internet");
418
      return false;
419
      }
420
    catch( final SecurityException e )
421
      {
422
      mReceiver.message("Application not authorized to connect to the Internet");
423
      return false;
424
      }
425
    catch( final Exception e )
426
      {
427
      mReceiver.message(e.getMessage());
428
      return false;
429
      }
430

    
431
    if( mScores.length()==0 )
432
      {
433
      mReceiver.message("Failed to download scores");
434
      return false;
435
      }
436

    
437
    return true;
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

    
452
    renderer = URLencode(renderer);
453
    version  = URLencode(version);
454

    
455
    String url="https://distorted.org/magic/cgi-bin/debugs.cgi";
456
    url += "?n="+name+"&r="+numRuns+"&p="+numPlay+"&c="+country+"&e="+mVersion+"d"+"&d="+renderer+"&v="+version;
457

    
458
    return url;
459
    }
460

    
461
///////////////////////////////////////////////////////////////////////////////////////////////////
462

    
463
  private static String getObjectList()
464
    {
465
    StringBuilder list = new StringBuilder();
466
    ObjectType[] objects = ObjectType.values();
467

    
468
    for(int i=0; i<NUM_OBJECTS; i++)
469
      {
470
      if( i>0 ) list.append(',');
471
      list.append(objects[i].name());
472
      }
473

    
474
    return list.toString();
475
    }
476

    
477
///////////////////////////////////////////////////////////////////////////////////////////////////
478

    
479
  private String constructDownloadURL()
480
    {
481
    RubikScores scores = RubikScores.getInstance();
482
    String name = URLencode(scores.getName());
483
    String veri = scores.isVerified() ? name : "";
484
    int numRuns = scores.getNumRuns();
485
    int numPlay = scores.getNumPlays();
486
    String country = scores.getCountry();
487

    
488
    String url="https://distorted.org/magic/cgi-bin/download.cgi";
489
    url += "?n="+name+"&v="+veri+"&r="+numRuns+"&p="+numPlay+"&c="+country+"&e="+mVersion+"d";
490
    url += "&o="+getObjectList()+"&min=0&max="+MAX_LEVEL+"&l="+MAX_PLACES;
491

    
492
    return url;
493
    }
494

    
495
///////////////////////////////////////////////////////////////////////////////////////////////////
496

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

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

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

    
517
    String url1="https://distorted.org/magic/cgi-bin/submit.cgi";
518
    String url2 = "n="+name+"&v="+veri+"&r="+numRuns+"&p="+numPlay+"&i="+deviceID+"&e="+mVersion+"d";
519
    url2 += "&d="+renderer+"&s="+version;
520
    url2 += reclist+"&c="+country+"&f="+epoch+"&oo="+getObjectList();
521
    url2 += "&min=0&max="+MAX_LEVEL+"&lo="+MAX_PLACES;
522
    String hash = computeHash( url2, salt.getBytes() );
523

    
524
    return url1 + "?" + url2 + "&h=" + hash;
525
    }
526

    
527
///////////////////////////////////////////////////////////////////////////////////////////////////
528

    
529
  private boolean gottaDownload()
530
    {
531
    return ((mScores.length()==0) && !mRunning);
532
    }
533

    
534
///////////////////////////////////////////////////////////////////////////////////////////////////
535

    
536
  @Override
537
  public void run()
538
    {
539
    boolean receiveValues=true;
540

    
541
    initializeStatics();
542

    
543
    try
544
      {
545
      if( mMode==DOWNLOAD && gottaDownload() )
546
        {
547
        mRunning = true;
548
        receiveValues = network(constructDownloadURL());
549
        }
550
      if( mMode==SUBMIT )
551
        {
552
        mRunning = true;
553

    
554
        if( RubikScores.getInstance().thereAreUnsubmittedRecords() )
555
          {
556
          receiveValues = network(constructSubmitURL());
557
          }
558
        }
559
      if( mMode==DEBUG )
560
        {
561
        sendDebug();
562
        receiveValues = false;
563
        mRunning = false;
564
        }
565
      }
566
    catch( Exception e )
567
      {
568
      if( mReceiver!=null ) mReceiver.message("Exception downloading records: "+e.getMessage() );
569
      }
570

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

    
577
    if( receiveValues )
578
      {
579
      if( mReceiver!=null ) mReceiver.receive(mCountry, mName, mTime);
580

    
581
      if( mMode==SUBMIT )
582
        {
583
        RubikScores.getInstance().successfulSubmit();
584
        }
585
      }
586
    }
587

    
588
///////////////////////////////////////////////////////////////////////////////////////////////////
589

    
590
  private RubikNetwork()
591
    {
592

    
593
    }
594

    
595
///////////////////////////////////////////////////////////////////////////////////////////////////
596
// PUBLIC API
597
///////////////////////////////////////////////////////////////////////////////////////////////////
598

    
599
  public static void onPause()
600
    {
601
    mRunning = false;
602
    }
603

    
604
///////////////////////////////////////////////////////////////////////////////////////////////////
605

    
606
  public static RubikNetwork getInstance()
607
    {
608
    if( mThis==null )
609
      {
610
      mThis = new RubikNetwork();
611
      }
612

    
613
    return mThis;
614
    }
615

    
616
///////////////////////////////////////////////////////////////////////////////////////////////////
617

    
618
  private void start(Receiver receiver, Activity act, int mode)
619
    {
620
    mReceiver = receiver;
621
    mMode     = mode;
622

    
623
    try
624
      {
625
      PackageInfo pInfo = act.getPackageManager().getPackageInfo( act.getPackageName(), 0);
626
      mVersion = pInfo.versionName;
627
      }
628
    catch (PackageManager.NameNotFoundException e)
629
      {
630
      mVersion = "0.9.2";
631
      }
632

    
633
    Thread networkThrd = new Thread(this);
634
    networkThrd.start();
635
    }
636

    
637
///////////////////////////////////////////////////////////////////////////////////////////////////
638

    
639
  public void download(Receiver receiver, FragmentActivity act)
640
    {
641
    start(receiver, act, DOWNLOAD);
642
    }
643

    
644
///////////////////////////////////////////////////////////////////////////////////////////////////
645

    
646
  public void submit(Receiver receiver, FragmentActivity act)
647
    {
648
    start(receiver, act, SUBMIT);
649
    }
650

    
651
///////////////////////////////////////////////////////////////////////////////////////////////////
652

    
653
  public void debug(AppCompatActivity act)
654
    {
655
    start(null, act, DEBUG);
656
    }
657
}
(1-1/2)