Project

General

Profile

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

magiccube / src / main / java / org / distorted / scores / RubikScoresDownloader.java @ 66e777b0

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 androidx.fragment.app.FragmentActivity;
23

    
24
import org.distorted.main.R;
25
import org.distorted.objects.RubikObjectList;
26

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

    
34
import static org.distorted.objects.RubikObjectList.MAX_LEVEL;
35

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

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

    
47
  public static final int MAX_PLACES = 10;
48

    
49
  private static final int DOWNLOAD   = 0;
50
  private static final int SUBMIT     = 1;
51
  private static final int IDLE       = 2;
52

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

    
88
  private static boolean mRunning = false;
89
  private static int mMode = IDLE;
90
  private static Receiver mReceiver;
91
  private static String mVersion;
92

    
93
  private static int mTotal = RubikObjectList.getTotal();
94
  private static String mScores = "";
95
  private static String[][][] mCountry = new String[mTotal][MAX_LEVEL][MAX_PLACES];
96
  private static String[][][] mName    = new String[mTotal][MAX_LEVEL][MAX_PLACES];
97
  private static  float[][][] mTime    = new  float[mTotal][MAX_LEVEL][MAX_PLACES];
98

    
99
  private static int[][] mPlaces = new int[mTotal][MAX_LEVEL];
100
  private static RubikScoresDownloader mThis;
101

    
102
///////////////////////////////////////////////////////////////////////////////////////////////////
103

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

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

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

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

    
127
    return generatedPassword;
128
    }
129

    
130
///////////////////////////////////////////////////////////////////////////////////////////////////
131

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

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

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

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

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

    
169
      begin = end;
170
      }
171

    
172
    return true;
173
    }
174

    
175
///////////////////////////////////////////////////////////////////////////////////////////////////
176

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

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

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

    
196
        if(level>=0 && level<MAX_LEVEL)
197
          {
198
          int p = mPlaces[object][level];
199
          mPlaces[object][level]++;
200

    
201
          mCountry[object][level][p] = country;
202
          mName   [object][level][p] = name;
203
          mTime   [object][level][p] = ((float)(time/100))/10.0f;
204
          }
205
        }
206
      }
207
    }
208

    
209
///////////////////////////////////////////////////////////////////////////////////////////////////
210

    
211
  private String URLencode(String s)
212
    {
213
    StringBuilder sbuf = new StringBuilder();
214
    int len = s.length();
215

    
216
    for (int i = 0; i < len; i++)
217
      {
218
      int ch = s.charAt(i);
219

    
220
           if ('A' <= ch && ch <= 'Z') sbuf.append((char)ch);
221
      else if ('a' <= ch && ch <= 'z') sbuf.append((char)ch);
222
      else if ('0' <= ch && ch <= '9') sbuf.append((char)ch);
223
      else if (ch == ' '             ) sbuf.append('+');
224
      else if (ch == '-' || ch == '_'
225
            || ch == '.' || ch == '!'
226
            || ch == '~' || ch == '*'
227
            || ch == '\'' || ch == '('
228
            || ch == ')'             ) sbuf.append((char)ch);
229
      else if (ch <= 0x007f)           sbuf.append(hex[ch]);
230
      else if (ch <= 0x07FF)
231
        {
232
        sbuf.append(hex[0xc0 | (ch >> 6)]);
233
        sbuf.append(hex[0x80 | (ch & 0x3F)]);
234
        }
235
      else
236
        {
237
        sbuf.append(hex[0xe0 | (ch >> 12)]);
238
        sbuf.append(hex[0x80 | ((ch >> 6) & 0x3F)]);
239
        sbuf.append(hex[0x80 | (ch & 0x3F)]);
240
        }
241
      }
242

    
243
    return sbuf.toString();
244
    }
245

    
246
///////////////////////////////////////////////////////////////////////////////////////////////////
247

    
248
  private boolean network(String url)
249
    {
250
    //android.util.Log.e("down", "url: "+url);
251

    
252
    try
253
      {
254
      java.net.URL connectURL = new URL(url);
255
      HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
256

    
257
      conn.setDoInput(true);
258
      conn.setDoOutput(true);
259
      conn.setUseCaches(false);
260
      conn.setRequestMethod("GET");
261
      conn.connect();
262
      conn.getOutputStream().flush();
263

    
264
      try( InputStream is = conn.getInputStream() )
265
        {
266
        int ch;
267
        StringBuilder sb = new StringBuilder();
268
        while( ( ch = is.read() ) != -1 )
269
          {
270
          sb.append( (char)ch );
271
          }
272
        mScores = sb.toString();
273
        }
274
      catch( final Exception e)
275
        {
276
        mReceiver.message("Failed to get an answer from the High Scores server");
277
        return false;
278
        }
279
      }
280
    catch( final UnknownHostException e )
281
      {
282
      mReceiver.message("No access to Internet");
283
      return false;
284
      }
285
    catch( final SecurityException e )
286
      {
287
      mReceiver.message("Application not authorized to connect to the Internet");
288
      return false;
289
      }
290
    catch( final Exception e )
291
      {
292
      mReceiver.message(e.getMessage());
293
      return false;
294
      }
295

    
296
    if( mScores.length()==0 )
297
      {
298
      mReceiver.message("Failed to download scores");
299
      return false;
300
      }
301

    
302
    return true;
303
    }
304

    
305
///////////////////////////////////////////////////////////////////////////////////////////////////
306

    
307
  private String constructDownloadURL()
308
    {
309
    RubikScores scores = RubikScores.getInstance();
310
    String name = URLencode(scores.getName());
311
    String veri = scores.isVerified() ? name : "";
312
    int numRuns = scores.getNumRuns();
313
    int numPlay = scores.getNumPlays();
314

    
315
    String url="https://distorted.org/magic/cgi-bin/download.cgi";
316
    url += "?n="+name+"&v="+veri+"&r="+numRuns+"&p="+numPlay+"&e="+mVersion+"d";
317
    url += "&o="+RubikObjectList.getObjectList()+"&min=0&max="+MAX_LEVEL+"&l="+MAX_PLACES;
318

    
319
    return url;
320
    }
321

    
322
///////////////////////////////////////////////////////////////////////////////////////////////////
323

    
324
  private String constructSubmitURL()
325
    {
326
    RubikScores scores = RubikScores.getInstance();
327
    String name = URLencode(scores.getName());
328
    String veri = scores.isVerified() ? name : "";
329
    int numRuns = scores.getNumRuns();
330
    int numPlay = scores.getNumPlays();
331
    int deviceID= scores.getDeviceID();
332
    String objlist = scores.getUnsubmittedObjlist();
333
    String lvllist = scores.getUnsubmittedLevellist();
334
    String timlist = scores.getUnsubmittedTimelist();
335
    String country = scores.getCountry();
336
    long epoch = System.currentTimeMillis();
337
    String salt = "cuboid";
338

    
339
    String url1="https://distorted.org/magic/cgi-bin/submit.cgi";
340
    String url2 = "n="+name+"&v="+veri+"&r="+numRuns+"&p="+numPlay+"&i="+deviceID+"&e="+mVersion+"d";
341
    url2 += "&o="+objlist+"&l="+lvllist+"&t="+timlist+"&c="+country+"&f="+epoch;
342
    url2 += "&oo="+RubikObjectList.getObjectList()+"&min=0&max="+MAX_LEVEL+"&lo="+MAX_PLACES;
343
    url2 += "&h="+computeHash( url2, salt.getBytes() );
344

    
345
    return url1 + "?" + url2;
346
    }
347

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

    
350
  private boolean gottaDownload()
351
    {
352
    return ((mScores.length()==0) && !mRunning);
353
    }
354

    
355
///////////////////////////////////////////////////////////////////////////////////////////////////
356

    
357
  @Override
358
  public void run()
359
    {
360
    boolean success=true;
361

    
362
    try
363
      {
364
      if( mMode==DOWNLOAD && gottaDownload() )
365
        {
366
        mRunning = true;
367
        success = network(constructDownloadURL());
368
        }
369
      if( mMode==SUBMIT )
370
        {
371
        mRunning = true;
372

    
373
        if( RubikScores.getInstance().thereAreUnsubmittedRecords() )
374
          {
375
          success = network(constructSubmitURL());
376
          }
377
        }
378
      }
379
    catch( Exception e )
380
      {
381
      mReceiver.message("Exception downloading records: "+e.getMessage() );
382
      }
383

    
384
    if( mRunning )
385
      {
386
      success = fillValues();
387
      mRunning = false;
388
      }
389

    
390
    if( success )
391
      {
392
      mReceiver.receive(mCountry, mName, mTime);
393

    
394
      if( mMode==SUBMIT )
395
        {
396
        RubikScores.getInstance().successfulSubmit();
397
        }
398
      }
399
    }
400

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

    
403
  private RubikScoresDownloader()
404
    {
405

    
406
    }
407

    
408
///////////////////////////////////////////////////////////////////////////////////////////////////
409
// PUBLIC API
410
///////////////////////////////////////////////////////////////////////////////////////////////////
411

    
412
  public static void onPause()
413
    {
414
    mRunning = false;
415
    }
416

    
417
///////////////////////////////////////////////////////////////////////////////////////////////////
418

    
419
  public static RubikScoresDownloader getInstance()
420
    {
421
    if( mThis==null )
422
      {
423
      mThis = new RubikScoresDownloader();
424
      }
425

    
426
    return mThis;
427
    }
428

    
429
///////////////////////////////////////////////////////////////////////////////////////////////////
430

    
431
  public void download(Receiver receiver, FragmentActivity act)
432
    {
433
    mReceiver = receiver;
434
    mMode     = DOWNLOAD;
435
    mVersion  = act.getString(R.string.app_version);
436

    
437
    Thread networkThrd = new Thread(this);
438
    networkThrd.start();
439
    }
440

    
441
///////////////////////////////////////////////////////////////////////////////////////////////////
442

    
443
  public void submit(Receiver receiver, FragmentActivity act)
444
    {
445
    mReceiver = receiver;
446
    mMode     = SUBMIT;
447
    mVersion  = act.getString(R.string.app_version);
448

    
449
    Thread networkThrd = new Thread(this);
450
    networkThrd.start();
451
    }
452
}
(2-2/2)