Project

General

Profile

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

magiccube / src / main / java / org / distorted / network / RubikNetwork.java @ 9d4c38eb

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 android.app.Activity;
23
import android.content.pm.PackageInfo;
24
import android.content.pm.PackageManager;
25

    
26
import androidx.appcompat.app.AppCompatActivity;
27
import androidx.fragment.app.FragmentActivity;
28

    
29
import org.distorted.library.main.DistortedLibrary;
30
import org.distorted.objects.ObjectList;
31

    
32
import java.io.InputStream;
33
import java.net.HttpURLConnection;
34
import java.net.URL;
35
import java.net.UnknownHostException;
36
import java.security.MessageDigest;
37
import java.security.NoSuchAlgorithmException;
38

    
39
import static org.distorted.objects.ObjectList.MAX_LEVEL;
40

    
41
///////////////////////////////////////////////////////////////////////////////////////////////////
42

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

    
52
  public static final int MAX_PLACES = 10;
53

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

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

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

    
99
  private static final int mTotal = ObjectList.getTotal();
100
  private static final String[][][] mCountry = new String[mTotal][MAX_LEVEL][MAX_PLACES];
101
  private static final String[][][] mName    = new String[mTotal][MAX_LEVEL][MAX_PLACES];
102
  private static final  float[][][] mTime    = new  float[mTotal][MAX_LEVEL][MAX_PLACES];
103
  private static final int[][] mPlaces = new int[mTotal][MAX_LEVEL];
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 String computeHash(String stringToHash, byte[] salt)
115
    {
116
    String generatedPassword;
117

    
118
    try
119
      {
120
      MessageDigest md = MessageDigest.getInstance("MD5");
121
      md.update(salt);
122
      byte[] bytes = md.digest(stringToHash.getBytes());
123
      StringBuilder sb = new StringBuilder();
124

    
125
      for (byte aByte : bytes)
126
        {
127
        sb.append(Integer.toString((aByte & 0xff) + 0x100, 16).substring(1));
128
        }
129

    
130
      generatedPassword = sb.toString();
131
      }
132
    catch (NoSuchAlgorithmException e)
133
      {
134
      return "NoSuchAlgorithm";
135
      }
136

    
137
    return generatedPassword;
138
    }
139

    
140
///////////////////////////////////////////////////////////////////////////////////////////////////
141

    
142
  private boolean fillValues()
143
    {
144
    int begin=-1 ,end, len = mScores.length();
145
    String row;
146

    
147
    if( len==0 )
148
      {
149
      mReceiver.error("1");
150
      return false;
151
      }
152
    else if( len<=2 )
153
      {
154
      mReceiver.error(mScores);
155
      return false;
156
      }
157

    
158
    for(int i=0; i<mTotal; i++)
159
      for(int j=0; j<MAX_LEVEL; j++)
160
        {
161
        mPlaces[i][j] = 0;
162
        }
163

    
164
    while( begin<len )
165
      {
166
      end = mScores.indexOf('\n', begin+1);
167
      if( end<0 ) end = len;
168

    
169
      try
170
        {
171
        row = mScores.substring(begin+1,end);
172
        fillRow(row);
173
        }
174
      catch(Exception ex)
175
        {
176
        // faulty row - ignore
177
        }
178

    
179
      begin = end;
180
      }
181

    
182
    return true;
183
    }
184

    
185
///////////////////////////////////////////////////////////////////////////////////////////////////
186

    
187
  private void fillRow(String row)
188
    {
189
    int s1 = row.indexOf(' ');
190
    int s2 = row.indexOf(' ',s1+1);
191
    int s3 = row.indexOf(' ',s2+1);
192
    int s4 = row.indexOf(' ',s3+1);
193
    int s5 = row.length();
194

    
195
    if( s5>s4 && s4>s3 && s3>s2 && s2>s1 && s1>0 )
196
      {
197
      int object = ObjectList.unpackObjectFromString( row.substring(0,s1) );
198

    
199
      if( object>=0 && object<mTotal )
200
        {
201
        int level      = Integer.parseInt( row.substring(s1+1,s2) );
202
        String name    = row.substring(s2+1, s3);
203
        int time       = Integer.parseInt( row.substring(s3+1,s4) );
204
        String country = row.substring(s4+1, s5);
205

    
206
        if( country.equals("do") ) country = "dm"; // see RubikScores.setCountry()
207

    
208
        if(level>=0 && level<MAX_LEVEL)
209
          {
210
          int p = mPlaces[object][level];
211
          mPlaces[object][level]++;
212

    
213
          mCountry[object][level][p] = country;
214
          mName   [object][level][p] = name;
215
          mTime   [object][level][p] = ((float)(time/10))/100.0f;
216
          }
217
        }
218
      }
219
    else
220
      {
221
      tryDoCommand(row);
222
      }
223
    }
224

    
225
///////////////////////////////////////////////////////////////////////////////////////////////////
226

    
227
  private void tryDoCommand(String row)
228
    {
229
    if( row.startsWith("comm") )
230
      {
231
      int colon = row.indexOf(':');
232

    
233
      if( colon>0 )
234
        {
235
        String commandNumber = row.substring(4,colon);
236
        int number;
237

    
238
        try
239
          {
240
          number = Integer.parseInt(commandNumber);
241
          }
242
        catch(NumberFormatException ex)
243
          {
244
          number=0;
245
          }
246

    
247
        if(number==1)
248
          {
249
          String country = row.substring(colon+1);
250
          RubikScores scores = RubikScores.getInstance();
251
          scores.setCountry(country);
252
          }
253
        }
254
      }
255
    }
256

    
257
///////////////////////////////////////////////////////////////////////////////////////////////////
258

    
259
  private int getRendererType(String renderer)
260
    {
261
    if( renderer.contains("Adreno")  ) return REND_ADRENO;
262
    if( renderer.contains("Mali")    ) return REND_MALI;
263
    if( renderer.contains("PowerVR") ) return REND_POWER;
264

    
265
    return REND_OTHER;
266
    }
267

    
268
///////////////////////////////////////////////////////////////////////////////////////////////////
269

    
270
  private String parseRenderer(final int type, String renderer)
271
    {
272
    if( type==REND_ADRENO || type==REND_POWER )
273
      {
274
      int lastSpace = renderer.lastIndexOf(' ');
275
      String ret = renderer.substring(lastSpace+1);
276
      return URLencode(ret);
277
      }
278

    
279
    if( type==REND_MALI )
280
      {
281
      int firstHyphen = renderer.indexOf('-');
282
      String ret = renderer.substring(firstHyphen+1);
283
      return URLencode(ret);
284
      }
285

    
286
    return "other";
287
    }
288

    
289
///////////////////////////////////////////////////////////////////////////////////////////////////
290

    
291
  private String parseVersion(final int type, String version)
292
    {
293
    switch(type)
294
      {
295
      case REND_ADRENO: int aMonkey = version.indexOf('@');
296
                        int aDot = version.indexOf('.', aMonkey);
297
                        String ret1 = aDot>=3 ? version.substring(aDot-3,aDot) : "";
298
                        return URLencode(ret1);
299
      case REND_MALI  : int mV1 = version.indexOf("v1");
300
                        int mHyphen = version.indexOf('-', mV1);
301
                        String ret2 = mHyphen>mV1+3 && mV1>=0 ? version.substring(mV1+3,mHyphen) : "";
302
                        return URLencode(ret2);
303
      case REND_POWER : int pMonkey = version.indexOf('@');
304
                        int pSpace  = version.lastIndexOf(' ');
305
                        String ret3 = pSpace>=0 && pMonkey>pSpace+1 ? version.substring(pSpace+1,pMonkey) : "";
306
                        return URLencode(ret3);
307
      default         : return "";
308
      }
309
    }
310

    
311
///////////////////////////////////////////////////////////////////////////////////////////////////
312

    
313
  private String URLencode(String s)
314
    {
315
    StringBuilder sbuf = new StringBuilder();
316
    int len = s.length();
317

    
318
    for (int i = 0; i < len; i++)
319
      {
320
      int ch = s.charAt(i);
321

    
322
           if ('A' <= ch && ch <= 'Z') sbuf.append((char)ch);
323
      else if ('a' <= ch && ch <= 'z') sbuf.append((char)ch);
324
      else if ('0' <= ch && ch <= '9') sbuf.append((char)ch);
325
      else if (ch == ' '             ) sbuf.append('+');
326
      else if (ch == '-' || ch == '_'
327
            || ch == '.' || ch == '!'
328
            || ch == '~' || ch == '*'
329
            || ch == '\'' || ch == '('
330
            || ch == ')'             ) sbuf.append((char)ch);
331
      else if (ch <= 0x007f)           sbuf.append(hex[ch]);
332
      else if (ch <= 0x07FF)
333
        {
334
        sbuf.append(hex[0xc0 | (ch >> 6)]);
335
        sbuf.append(hex[0x80 | (ch & 0x3F)]);
336
        }
337
      else
338
        {
339
        sbuf.append(hex[0xe0 | (ch >> 12)]);
340
        sbuf.append(hex[0x80 | ((ch >> 6) & 0x3F)]);
341
        sbuf.append(hex[0x80 | (ch & 0x3F)]);
342
        }
343
      }
344

    
345
    return sbuf.toString();
346
    }
347

    
348
///////////////////////////////////////////////////////////////////////////////////////////////////
349

    
350
  private void sendDebug()
351
    {
352
    String url = constructDebugURL();
353

    
354
    try
355
      {
356
      java.net.URL connectURL = new URL(url);
357
      HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
358

    
359
      conn.setDoInput(true);
360
      conn.setDoOutput(true);
361
      conn.setUseCaches(false);
362
      conn.setRequestMethod("GET");
363
      conn.connect();
364
      conn.getOutputStream().flush();
365
      conn.getInputStream();
366
      }
367
    catch( final Exception e )
368
      {
369
      // ignore
370
      }
371
    }
372

    
373
///////////////////////////////////////////////////////////////////////////////////////////////////
374

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

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

    
389
      try( InputStream is = conn.getInputStream() )
390
        {
391
        int ch;
392
        StringBuilder sb = new StringBuilder();
393
        while( ( ch = is.read() ) != -1 )
394
          {
395
          sb.append( (char)ch );
396
          }
397
        mScores = sb.toString();
398
        }
399
      catch( final Exception e)
400
        {
401
        mReceiver.message("Failed to get an answer from the High Scores server");
402
        return false;
403
        }
404
      }
405
    catch( final UnknownHostException e )
406
      {
407
      mReceiver.message("No access to Internet");
408
      return false;
409
      }
410
    catch( final SecurityException e )
411
      {
412
      mReceiver.message("Application not authorized to connect to the Internet");
413
      return false;
414
      }
415
    catch( final Exception e )
416
      {
417
      mReceiver.message(e.getMessage());
418
      return false;
419
      }
420

    
421
    if( mScores.length()==0 )
422
      {
423
      mReceiver.message("Failed to download scores");
424
      return false;
425
      }
426

    
427
    return true;
428
    }
429

    
430
///////////////////////////////////////////////////////////////////////////////////////////////////
431

    
432
  private String constructDebugURL()
433
    {
434
    RubikScores scores = RubikScores.getInstance();
435
    String name = URLencode(scores.getName());
436
    int numRuns = scores.getNumRuns();
437
    int numPlay = scores.getNumPlays();
438
    String country = scores.getCountry();
439
    String renderer = DistortedLibrary.getDriverRenderer();
440
    String version  = DistortedLibrary.getDriverVersion();
441

    
442
    renderer = URLencode(renderer);
443
    version  = URLencode(version);
444

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

    
448
    return url;
449
    }
450

    
451
///////////////////////////////////////////////////////////////////////////////////////////////////
452

    
453
  private String constructDownloadURL()
454
    {
455
    RubikScores scores = RubikScores.getInstance();
456
    String name = URLencode(scores.getName());
457
    String veri = scores.isVerified() ? name : "";
458
    int numRuns = scores.getNumRuns();
459
    int numPlay = scores.getNumPlays();
460
    String country = scores.getCountry();
461

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

    
466
    return url;
467
    }
468

    
469
///////////////////////////////////////////////////////////////////////////////////////////////////
470

    
471
  private String constructSubmitURL()
472
    {
473
    RubikScores scores = RubikScores.getInstance();
474
    String name = URLencode(scores.getName());
475
    String veri = scores.isVerified() ? name : "";
476
    int numRuns = scores.getNumRuns();
477
    int numPlay = scores.getNumPlays();
478
    int deviceID= scores.getDeviceID();
479
    String reclist = scores.getRecordList("&o=","&l=","&t=");
480
    String country = scores.getCountry();
481
    long epoch = System.currentTimeMillis();
482
    String salt = "cuboid";
483

    
484
    String renderer = DistortedLibrary.getDriverRenderer();
485
    String version  = DistortedLibrary.getDriverVersion();
486

    
487
    int type = getRendererType(renderer);
488
    renderer = parseRenderer(type,renderer);
489
    version  = parseVersion(type,version);
490

    
491
    String url1="https://distorted.org/magic/cgi-bin/submit.cgi";
492
    String url2 = "n="+name+"&v="+veri+"&r="+numRuns+"&p="+numPlay+"&i="+deviceID+"&e="+mVersion+"d";
493
    url2 += "&d="+renderer+"&s="+version;
494
    url2 += reclist+"&c="+country+"&f="+epoch+"&oo="+ ObjectList.getObjectList();
495
    url2 += "&min=0&max="+MAX_LEVEL+"&lo="+MAX_PLACES;
496
    String hash = computeHash( url2, salt.getBytes() );
497

    
498
    return url1 + "?" + url2 + "&h=" + hash;
499
    }
500

    
501
///////////////////////////////////////////////////////////////////////////////////////////////////
502

    
503
  private boolean gottaDownload()
504
    {
505
    return ((mScores.length()==0) && !mRunning);
506
    }
507

    
508
///////////////////////////////////////////////////////////////////////////////////////////////////
509

    
510
  @Override
511
  public void run()
512
    {
513
    boolean receiveValues=true;
514

    
515
    try
516
      {
517
      if( mMode==DOWNLOAD && gottaDownload() )
518
        {
519
        mRunning = true;
520
        receiveValues = network(constructDownloadURL());
521
        }
522
      if( mMode==SUBMIT )
523
        {
524
        mRunning = true;
525

    
526
        if( RubikScores.getInstance().thereAreUnsubmittedRecords() )
527
          {
528
          receiveValues = network(constructSubmitURL());
529
          }
530
        }
531
      if( mMode==DEBUG )
532
        {
533
        sendDebug();
534
        receiveValues = false;
535
        mRunning = false;
536
        }
537
      }
538
    catch( Exception e )
539
      {
540
      if( mReceiver!=null ) mReceiver.message("Exception downloading records: "+e.getMessage() );
541
      }
542

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

    
549
    if( receiveValues )
550
      {
551
      if( mReceiver!=null ) mReceiver.receive(mCountry, mName, mTime);
552

    
553
      if( mMode==SUBMIT )
554
        {
555
        RubikScores.getInstance().successfulSubmit();
556
        }
557
      }
558
    }
559

    
560
///////////////////////////////////////////////////////////////////////////////////////////////////
561

    
562
  private RubikNetwork()
563
    {
564

    
565
    }
566

    
567
///////////////////////////////////////////////////////////////////////////////////////////////////
568
// PUBLIC API
569
///////////////////////////////////////////////////////////////////////////////////////////////////
570

    
571
  public static void onPause()
572
    {
573
    mRunning = false;
574
    }
575

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

    
578
  public static RubikNetwork getInstance()
579
    {
580
    if( mThis==null )
581
      {
582
      mThis = new RubikNetwork();
583
      }
584

    
585
    return mThis;
586
    }
587

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

    
590
  private void start(Receiver receiver, Activity act, int mode)
591
    {
592
    mReceiver = receiver;
593
    mMode     = mode;
594

    
595
    try
596
      {
597
      PackageInfo pInfo = act.getPackageManager().getPackageInfo( act.getPackageName(), 0);
598
      mVersion = pInfo.versionName;
599
      }
600
    catch (PackageManager.NameNotFoundException e)
601
      {
602
      mVersion = "0.9.2";
603
      }
604

    
605
    Thread networkThrd = new Thread(this);
606
    networkThrd.start();
607
    }
608

    
609
///////////////////////////////////////////////////////////////////////////////////////////////////
610

    
611
  public void download(Receiver receiver, FragmentActivity act)
612
    {
613
    start(receiver, act, DOWNLOAD);
614
    }
615

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

    
618
  public void submit(Receiver receiver, FragmentActivity act)
619
    {
620
    start(receiver, act, SUBMIT);
621
    }
622

    
623
///////////////////////////////////////////////////////////////////////////////////////////////////
624

    
625
  public void debug(AppCompatActivity act)
626
    {
627
    start(null, act, DEBUG);
628
    }
629
}
(1-1/2)