Project

General

Profile

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

magiccube / src / main / java / org / distorted / scores / RubikScoresDownloader.java @ eaf87d1d

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

    
25
import androidx.fragment.app.FragmentActivity;
26

    
27
import org.distorted.objects.ObjectList;
28

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

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

    
38
///////////////////////////////////////////////////////////////////////////////////////////////////
39

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

    
49
  public static final int MAX_PLACES = 10;
50

    
51
  private static final int DOWNLOAD   = 0;
52
  private static final int SUBMIT     = 1;
53
  private static final int IDLE       = 2;
54

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

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

    
96
  private static RubikScoresDownloader mThis;
97
  private static String mScores = "";
98
  private static boolean mRunning = false;
99
  private static int mMode = IDLE;
100
  private static Receiver mReceiver;
101
  private static String mVersion;
102

    
103
///////////////////////////////////////////////////////////////////////////////////////////////////
104

    
105
  private static String computeHash(String stringToHash, byte[] salt)
106
    {
107
    String generatedPassword;
108

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

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

    
121
      generatedPassword = sb.toString();
122
      }
123
    catch (NoSuchAlgorithmException e)
124
      {
125
      return "NoSuchAlgorithm";
126
      }
127

    
128
    return generatedPassword;
129
    }
130

    
131
///////////////////////////////////////////////////////////////////////////////////////////////////
132

    
133
  private boolean fillValues()
134
    {
135
    int begin=-1 ,end, len = mScores.length();
136
    String row;
137

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

    
149
    for(int i=0; i<mTotal; i++)
150
      for(int j=0; j<MAX_LEVEL; j++)
151
        {
152
        mPlaces[i][j] = 0;
153
        }
154

    
155
    while( begin<len )
156
      {
157
      end = mScores.indexOf('\n', begin+1);
158
      if( end<0 ) end = len;
159

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

    
170
      begin = end;
171
      }
172

    
173
    return true;
174
    }
175

    
176
///////////////////////////////////////////////////////////////////////////////////////////////////
177

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

    
186
    if( s5>s4 && s4>s3 && s3>s2 && s2>s1 && s1>0 )
187
      {
188
      int object = ObjectList.unpackObjectFromString( row.substring(0,s1) );
189

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

    
197
        if( country.equals("do") ) country = "dm"; // see RubikScores.setCountry()
198

    
199
        if(level>=0 && level<MAX_LEVEL)
200
          {
201
          int p = mPlaces[object][level];
202
          mPlaces[object][level]++;
203

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

    
216
///////////////////////////////////////////////////////////////////////////////////////////////////
217

    
218
  private void tryDoCommand(String row)
219
    {
220
    if( row.startsWith("comm") )
221
      {
222
      int colon = row.indexOf(':');
223

    
224
      if( colon>0 )
225
        {
226
        String commandNumber = row.substring(4,colon);
227
        int number;
228

    
229
        try
230
          {
231
          number = Integer.parseInt(commandNumber);
232
          }
233
        catch(NumberFormatException ex)
234
          {
235
          number=0;
236
          }
237

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

    
248
///////////////////////////////////////////////////////////////////////////////////////////////////
249

    
250
  private String URLencode(String s)
251
    {
252
    StringBuilder sbuf = new StringBuilder();
253
    int len = s.length();
254

    
255
    for (int i = 0; i < len; i++)
256
      {
257
      int ch = s.charAt(i);
258

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

    
282
    return sbuf.toString();
283
    }
284

    
285
///////////////////////////////////////////////////////////////////////////////////////////////////
286

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

    
294
      conn.setDoInput(true);
295
      conn.setDoOutput(true);
296
      conn.setUseCaches(false);
297
      conn.setRequestMethod("GET");
298
      conn.connect();
299
      conn.getOutputStream().flush();
300

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

    
333
    if( mScores.length()==0 )
334
      {
335
      mReceiver.message("Failed to download scores");
336
      return false;
337
      }
338

    
339
    return true;
340
    }
341

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

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

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

    
357
    return url;
358
    }
359

    
360
///////////////////////////////////////////////////////////////////////////////////////////////////
361

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

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

    
381
    return url1 + "?" + url2 + "&h=" + hash;
382
    }
383

    
384
///////////////////////////////////////////////////////////////////////////////////////////////////
385

    
386
  private boolean gottaDownload()
387
    {
388
    return ((mScores.length()==0) && !mRunning);
389
    }
390

    
391
///////////////////////////////////////////////////////////////////////////////////////////////////
392

    
393
  @Override
394
  public void run()
395
    {
396
    boolean success=true;
397

    
398
    try
399
      {
400
      if( mMode==DOWNLOAD && gottaDownload() )
401
        {
402
        mRunning = true;
403
        success = network(constructDownloadURL());
404
        }
405
      if( mMode==SUBMIT )
406
        {
407
        mRunning = true;
408

    
409
        if( RubikScores.getInstance().thereAreUnsubmittedRecords() )
410
          {
411
          success = network(constructSubmitURL());
412
          }
413
        }
414
      }
415
    catch( Exception e )
416
      {
417
      mReceiver.message("Exception downloading records: "+e.getMessage() );
418
      }
419

    
420
    if( mRunning )
421
      {
422
      success = fillValues();
423
      mRunning = false;
424
      }
425

    
426
    if( success )
427
      {
428
      mReceiver.receive(mCountry, mName, mTime);
429

    
430
      if( mMode==SUBMIT )
431
        {
432
        RubikScores.getInstance().successfulSubmit();
433
        }
434
      }
435
    }
436

    
437
///////////////////////////////////////////////////////////////////////////////////////////////////
438

    
439
  private RubikScoresDownloader()
440
    {
441

    
442
    }
443

    
444
///////////////////////////////////////////////////////////////////////////////////////////////////
445
// PUBLIC API
446
///////////////////////////////////////////////////////////////////////////////////////////////////
447

    
448
  public static void onPause()
449
    {
450
    mRunning = false;
451
    }
452

    
453
///////////////////////////////////////////////////////////////////////////////////////////////////
454

    
455
  public static RubikScoresDownloader getInstance()
456
    {
457
    if( mThis==null )
458
      {
459
      mThis = new RubikScoresDownloader();
460
      }
461

    
462
    return mThis;
463
    }
464

    
465
///////////////////////////////////////////////////////////////////////////////////////////////////
466

    
467
  private void start(Receiver receiver, FragmentActivity act, int mode)
468
    {
469
    mReceiver = receiver;
470
    mMode     = mode;
471

    
472
    try
473
      {
474
      PackageInfo pInfo = act.getPackageManager().getPackageInfo( act.getPackageName(), 0);
475
      mVersion = pInfo.versionName;
476
      }
477
    catch (PackageManager.NameNotFoundException e)
478
      {
479
      mVersion = "0.9.2";
480
      }
481

    
482
    Thread networkThrd = new Thread(this);
483
    networkThrd.start();
484
    }
485

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

    
488
  public void download(Receiver receiver, FragmentActivity act)
489
    {
490
    start(receiver, act, DOWNLOAD);
491
    }
492

    
493
///////////////////////////////////////////////////////////////////////////////////////////////////
494

    
495
  public void submit(Receiver receiver, FragmentActivity act)
496
    {
497
    start(receiver, act, SUBMIT);
498
    }
499
}
(2-2/2)