Project

General

Profile

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

magiccube / src / main / java / org / distorted / scores / RubikScoresDownloader.java @ 36b9ee93

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.scores;
21

    
22
import android.app.Activity;
23
import android.content.pm.PackageInfo;
24
import android.content.pm.PackageManager;
25

    
26
import androidx.fragment.app.FragmentActivity;
27

    
28
import org.distorted.objects.ObjectList;
29

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

    
37
import static org.distorted.objects.ObjectList.MAX_LEVEL;
38

    
39
///////////////////////////////////////////////////////////////////////////////////////////////////
40

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

    
50
  public static final int MAX_PLACES = 10;
51

    
52
  private static final int DOWNLOAD   = 0;
53
  private static final int SUBMIT     = 1;
54
  private static final int ERROR      = 2;
55
  private static final int IDLE       = 3;
56

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

    
92
  private static final int mTotal = ObjectList.getTotal();
93
  private static final String[][][] mCountry = new String[mTotal][MAX_LEVEL][MAX_PLACES];
94
  private static final String[][][] mName    = new String[mTotal][MAX_LEVEL][MAX_PLACES];
95
  private static final  float[][][] mTime    = new  float[mTotal][MAX_LEVEL][MAX_PLACES];
96
  private static final int[][] mPlaces = new int[mTotal][MAX_LEVEL];
97

    
98
  private static RubikScoresDownloader mThis;
99
  private static String mScores = "";
100
  private static boolean mRunning = false;
101
  private static int mMode = IDLE;
102
  private static Receiver mReceiver;
103
  private static String mVersion;
104
  private static String mError = "";
105

    
106
///////////////////////////////////////////////////////////////////////////////////////////////////
107

    
108
  private static String computeHash(String stringToHash, byte[] salt)
109
    {
110
    String generatedPassword;
111

    
112
    try
113
      {
114
      MessageDigest md = MessageDigest.getInstance("MD5");
115
      md.update(salt);
116
      byte[] bytes = md.digest(stringToHash.getBytes());
117
      StringBuilder sb = new StringBuilder();
118

    
119
      for (byte aByte : bytes)
120
        {
121
        sb.append(Integer.toString((aByte & 0xff) + 0x100, 16).substring(1));
122
        }
123

    
124
      generatedPassword = sb.toString();
125
      }
126
    catch (NoSuchAlgorithmException e)
127
      {
128
      return "NoSuchAlgorithm";
129
      }
130

    
131
    return generatedPassword;
132
    }
133

    
134
///////////////////////////////////////////////////////////////////////////////////////////////////
135

    
136
  private boolean fillValues()
137
    {
138
    int begin=-1 ,end, len = mScores.length();
139
    String row;
140

    
141
    if( len==0 )
142
      {
143
      mReceiver.error("1");
144
      return false;
145
      }
146
    else if( len<=2 )
147
      {
148
      mReceiver.error(mScores);
149
      return false;
150
      }
151

    
152
    for(int i=0; i<mTotal; i++)
153
      for(int j=0; j<MAX_LEVEL; j++)
154
        {
155
        mPlaces[i][j] = 0;
156
        }
157

    
158
    while( begin<len )
159
      {
160
      end = mScores.indexOf('\n', begin+1);
161
      if( end<0 ) end = len;
162

    
163
      try
164
        {
165
        row = mScores.substring(begin+1,end);
166
        fillRow(row);
167
        }
168
      catch(Exception ex)
169
        {
170
        // faulty row - ignore
171
        }
172

    
173
      begin = end;
174
      }
175

    
176
    return true;
177
    }
178

    
179
///////////////////////////////////////////////////////////////////////////////////////////////////
180

    
181
  private void fillRow(String row)
182
    {
183
    int s1 = row.indexOf(' ');
184
    int s2 = row.indexOf(' ',s1+1);
185
    int s3 = row.indexOf(' ',s2+1);
186
    int s4 = row.indexOf(' ',s3+1);
187
    int s5 = row.length();
188

    
189
    if( s5>s4 && s4>s3 && s3>s2 && s2>s1 && s1>0 )
190
      {
191
      int object = ObjectList.unpackObjectFromString( row.substring(0,s1) );
192

    
193
      if( object>=0 && object<mTotal )
194
        {
195
        int level      = Integer.parseInt( row.substring(s1+1,s2) );
196
        String name    = row.substring(s2+1, s3);
197
        int time       = Integer.parseInt( row.substring(s3+1,s4) );
198
        String country = row.substring(s4+1, s5);
199

    
200
        if( country.equals("do") ) country = "dm"; // see RubikScores.setCountry()
201

    
202
        if(level>=0 && level<MAX_LEVEL)
203
          {
204
          int p = mPlaces[object][level];
205
          mPlaces[object][level]++;
206

    
207
          mCountry[object][level][p] = country;
208
          mName   [object][level][p] = name;
209
          mTime   [object][level][p] = ((float)(time/10))/100.0f;
210
          }
211
        }
212
      }
213
    else
214
      {
215
      tryDoCommand(row);
216
      }
217
    }
218

    
219
///////////////////////////////////////////////////////////////////////////////////////////////////
220

    
221
  private void tryDoCommand(String row)
222
    {
223
    if( row.startsWith("comm") )
224
      {
225
      int colon = row.indexOf(':');
226

    
227
      if( colon>0 )
228
        {
229
        String commandNumber = row.substring(4,colon);
230
        int number;
231

    
232
        try
233
          {
234
          number = Integer.parseInt(commandNumber);
235
          }
236
        catch(NumberFormatException ex)
237
          {
238
          number=0;
239
          }
240

    
241
        if(number==1)
242
          {
243
          String country = row.substring(colon+1);
244
          RubikScores scores = RubikScores.getInstance();
245
          scores.setCountry(country);
246
          }
247
        }
248
      }
249
    }
250

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

    
253
  private String URLencode(String s)
254
    {
255
    StringBuilder sbuf = new StringBuilder();
256
    int len = s.length();
257

    
258
    for (int i = 0; i < len; i++)
259
      {
260
      int ch = s.charAt(i);
261

    
262
           if ('A' <= ch && ch <= 'Z') sbuf.append((char)ch);
263
      else if ('a' <= ch && ch <= 'z') sbuf.append((char)ch);
264
      else if ('0' <= ch && ch <= '9') sbuf.append((char)ch);
265
      else if (ch == ' '             ) sbuf.append('+');
266
      else if (ch == '-' || ch == '_'
267
            || ch == '.' || ch == '!'
268
            || ch == '~' || ch == '*'
269
            || ch == '\'' || ch == '('
270
            || ch == ')'             ) sbuf.append((char)ch);
271
      else if (ch <= 0x007f)           sbuf.append(hex[ch]);
272
      else if (ch <= 0x07FF)
273
        {
274
        sbuf.append(hex[0xc0 | (ch >> 6)]);
275
        sbuf.append(hex[0x80 | (ch & 0x3F)]);
276
        }
277
      else
278
        {
279
        sbuf.append(hex[0xe0 | (ch >> 12)]);
280
        sbuf.append(hex[0x80 | ((ch >> 6) & 0x3F)]);
281
        sbuf.append(hex[0x80 | (ch & 0x3F)]);
282
        }
283
      }
284

    
285
    return sbuf.toString();
286
    }
287

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

    
290
  private boolean network(String url)
291
    {
292
    try
293
      {
294
      java.net.URL connectURL = new URL(url);
295
      HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
296

    
297
      conn.setDoInput(true);
298
      conn.setDoOutput(true);
299
      conn.setUseCaches(false);
300
      conn.setRequestMethod("GET");
301
      conn.connect();
302
      conn.getOutputStream().flush();
303

    
304
      try( InputStream is = conn.getInputStream() )
305
        {
306
        int ch;
307
        StringBuilder sb = new StringBuilder();
308
        while( ( ch = is.read() ) != -1 )
309
          {
310
          sb.append( (char)ch );
311
          }
312
        mScores = sb.toString();
313
        }
314
      catch( final Exception e)
315
        {
316
        mReceiver.message("Failed to get an answer from the High Scores server");
317
        return false;
318
        }
319
      }
320
    catch( final UnknownHostException e )
321
      {
322
      mReceiver.message("No access to Internet");
323
      return false;
324
      }
325
    catch( final SecurityException e )
326
      {
327
      mReceiver.message("Application not authorized to connect to the Internet");
328
      return false;
329
      }
330
    catch( final Exception e )
331
      {
332
      mReceiver.message(e.getMessage());
333
      return false;
334
      }
335

    
336
    if( mScores.length()==0 )
337
      {
338
      mReceiver.message("Failed to download scores");
339
      return false;
340
      }
341

    
342
    return true;
343
    }
344

    
345
///////////////////////////////////////////////////////////////////////////////////////////////////
346

    
347
  private String constructDownloadURL()
348
    {
349
    RubikScores scores = RubikScores.getInstance();
350
    String name = URLencode(scores.getName());
351
    String veri = scores.isVerified() ? name : "";
352
    int numRuns = scores.getNumRuns();
353
    int numPlay = scores.getNumPlays();
354
    String country = scores.getCountry();
355

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

    
360
    return url;
361
    }
362

    
363
///////////////////////////////////////////////////////////////////////////////////////////////////
364

    
365
  private String constructSubmitURL()
366
    {
367
    RubikScores scores = RubikScores.getInstance();
368
    String name = URLencode(scores.getName());
369
    String veri = scores.isVerified() ? name : "";
370
    int numRuns = scores.getNumRuns();
371
    int numPlay = scores.getNumPlays();
372
    int deviceID= scores.getDeviceID();
373
    String reclist = scores.getRecordList("&o=","&l=","&t=");
374
    String country = scores.getCountry();
375
    long epoch = System.currentTimeMillis();
376
    String salt = "cuboid";
377

    
378
    String url1="https://distorted.org/magic/cgi-bin/submit.cgi";
379
    String url2 = "n="+name+"&v="+veri+"&r="+numRuns+"&p="+numPlay+"&i="+deviceID+"&e="+mVersion+"d";
380
    url2 += reclist+"&c="+country+"&f="+epoch+"&oo="+ ObjectList.getObjectList();
381
    url2 += "&min=0&max="+MAX_LEVEL+"&lo="+MAX_PLACES;
382
    String hash = computeHash( url2, salt.getBytes() );
383

    
384
    return url1 + "?" + url2 + "&h=" + hash;
385
    }
386

    
387
///////////////////////////////////////////////////////////////////////////////////////////////////
388

    
389
  private String constructErrorURL()
390
    {
391
    return "https://distorted.org/magic/cgi-bin/error.cgi?e="+URLencode(mError);
392
    }
393

    
394
///////////////////////////////////////////////////////////////////////////////////////////////////
395

    
396
  private boolean gottaDownload()
397
    {
398
    return ((mScores.length()==0) && !mRunning);
399
    }
400

    
401
///////////////////////////////////////////////////////////////////////////////////////////////////
402

    
403
  @Override
404
  public void run()
405
    {
406
    boolean success=true;
407

    
408
    try
409
      {
410
      if( mMode==DOWNLOAD && gottaDownload() )
411
        {
412
        mRunning = true;
413
        success = network(constructDownloadURL());
414
        }
415
      if( mMode==SUBMIT )
416
        {
417
        mRunning = true;
418

    
419
        if( RubikScores.getInstance().thereAreUnsubmittedRecords() )
420
          {
421
          success = network(constructSubmitURL());
422
          }
423
        }
424
      if( mMode==ERROR )
425
        {
426
        mRunning = true;
427
        success = network(constructErrorURL());
428
        }
429
      }
430
    catch( Exception e )
431
      {
432
      if( mReceiver!=null )
433
        {
434
        mReceiver.message("Exception downloading records: "+e.getMessage() );
435
        }
436
      }
437

    
438
    if( mReceiver!=null )
439
      {
440
      if( mRunning )
441
        {
442
        success = fillValues();
443
        mRunning = false;
444
        }
445

    
446
      if( success )
447
        {
448
        mReceiver.receive(mCountry, mName, mTime);
449

    
450
        if( mMode==SUBMIT )
451
          {
452
          RubikScores.getInstance().successfulSubmit();
453
          }
454
        }
455
      }
456
    }
457

    
458
///////////////////////////////////////////////////////////////////////////////////////////////////
459

    
460
  private RubikScoresDownloader()
461
    {
462

    
463
    }
464

    
465
///////////////////////////////////////////////////////////////////////////////////////////////////
466
// PUBLIC API
467
///////////////////////////////////////////////////////////////////////////////////////////////////
468

    
469
  public static void onPause()
470
    {
471
    mRunning = false;
472
    }
473

    
474
///////////////////////////////////////////////////////////////////////////////////////////////////
475

    
476
  public static RubikScoresDownloader getInstance()
477
    {
478
    if( mThis==null )
479
      {
480
      mThis = new RubikScoresDownloader();
481
      }
482

    
483
    return mThis;
484
    }
485

    
486
///////////////////////////////////////////////////////////////////////////////////////////////////
487

    
488
  private void start(Receiver receiver, Activity act, int mode)
489
    {
490
    mReceiver = receiver;
491
    mMode     = mode;
492

    
493
    try
494
      {
495
      if( act!=null )
496
        {
497
        PackageInfo pInfo = act.getPackageManager().getPackageInfo( act.getPackageName(), 0);
498
        mVersion = pInfo.versionName;
499
        }
500
      }
501
    catch (PackageManager.NameNotFoundException e)
502
      {
503
      mVersion = "0.9.2";
504
      }
505

    
506
    Thread networkThrd = new Thread(this);
507
    networkThrd.start();
508
    }
509

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

    
512
  public void error(String error)
513
    {
514
    mError = error;
515
    start(null, null, ERROR);
516
    }
517

    
518
///////////////////////////////////////////////////////////////////////////////////////////////////
519

    
520
  public void download(Receiver receiver, FragmentActivity act)
521
    {
522
    start(receiver, act, DOWNLOAD);
523
    }
524

    
525
///////////////////////////////////////////////////////////////////////////////////////////////////
526

    
527
  public void submit(Receiver receiver, FragmentActivity act)
528
    {
529
    start(receiver, act, SUBMIT);
530
    }
531
}
(2-2/2)