Project

General

Profile

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

magiccube / src / main / java / org / distorted / scores / RubikScoresDownloader.java @ 8e3898c8

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.support.v4.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

    
32
import static org.distorted.objects.RubikObjectList.MAX_LEVEL;
33

    
34
///////////////////////////////////////////////////////////////////////////////////////////////////
35

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

    
45
  public static final int MAX_PLACES = 10;
46

    
47
  private static final int DOWNLOAD   = 0;
48
  private static final int SUBMIT     = 1;
49
  private static final int IDLE       = 2;
50

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

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

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

    
97
  private static int[][] mPlaces = new int[mTotal][MAX_LEVEL];
98
  private static RubikScoresDownloader mThis;
99

    
100
///////////////////////////////////////////////////////////////////////////////////////////////////
101
// TODO
102

    
103
  private static int computeHash(String name, String veri, String country, String lvllist,
104
                                 String objlist, String timelist, int runnings)
105
    {
106
    int length, hash = 0;
107

    
108
    length = name.length();
109
    for(int i=0; i<length; i++) hash += i*name.charAt(i);
110
    length = veri.length();
111
    for(int i=0; i<length; i++) hash += i*veri.charAt(i);
112
    length = country.length();
113
    for(int i=0; i<length; i++) hash += i*country.charAt(i);
114
    length = lvllist.length();
115
    for(int i=0; i<length; i++) hash += i*lvllist.charAt(i);
116
    length = objlist.length();
117
    for(int i=0; i<length; i++) hash += i*objlist.charAt(i);
118
    length = timelist.length();
119
    for(int i=0; i<length; i++) hash += i*timelist.charAt(i);
120

    
121
    hash *= runnings;
122
    hash %= 541;
123

    
124
    return hash<0 ? -hash: hash;
125
    }
126

    
127
///////////////////////////////////////////////////////////////////////////////////////////////////
128

    
129
  private boolean fillValues()
130
    {
131
    int begin=-1 ,end, len = mScores.length();
132
    String row;
133

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

    
145
    for(int i=0; i<mTotal; i++)
146
      for(int j=0; j<MAX_LEVEL; j++)
147
        {
148
        mPlaces[i][j] = 0;
149
        }
150

    
151
    while( begin<len )
152
      {
153
      end = mScores.indexOf('\n', begin+1);
154
      if( end<0 ) end = len;
155

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

    
166
      begin = end;
167
      }
168

    
169
    return true;
170
    }
171

    
172
///////////////////////////////////////////////////////////////////////////////////////////////////
173

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

    
182
    if( s5>s4 && s4>s3 && s3>s2 && s2>s1 && s1>0 )
183
      {
184
      int object = RubikObjectList.unpackObjectFromString( row.substring(0,s1) );
185

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

    
193
        if(level>=0 && level<MAX_LEVEL)
194
          {
195
          int p = mPlaces[object][level];
196
          mPlaces[object][level]++;
197

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

    
206
///////////////////////////////////////////////////////////////////////////////////////////////////
207

    
208
  private String URLencode(String s)
209
    {
210
    StringBuilder sbuf = new StringBuilder();
211
    int len = s.length();
212

    
213
    for (int i = 0; i < len; i++)
214
      {
215
      int ch = s.charAt(i);
216

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

    
240
    return sbuf.toString();
241
    }
242

    
243
///////////////////////////////////////////////////////////////////////////////////////////////////
244

    
245
  private boolean network(String url)
246
    {
247
    //android.util.Log.e("down", "url: "+url);
248

    
249
    try
250
      {
251
      java.net.URL connectURL = new URL(url);
252
      HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
253

    
254
      conn.setDoInput(true);
255
      conn.setDoOutput(true);
256
      conn.setUseCaches(false);
257
      conn.setRequestMethod("GET");
258
      conn.connect();
259
      conn.getOutputStream().flush();
260

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

    
293
    if( mScores.length()==0 )
294
      {
295
      mReceiver.message("Failed to download scores");
296
      return false;
297
      }
298

    
299
    return true;
300
    }
301

    
302
///////////////////////////////////////////////////////////////////////////////////////////////////
303

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

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

    
316
    return url;
317
    }
318

    
319
///////////////////////////////////////////////////////////////////////////////////////////////////
320

    
321
  private String constructSubmitURL()
322
    {
323
    RubikScores scores = RubikScores.getInstance();
324
    String name = URLencode(scores.getName());
325
    String veri = scores.isVerified() ? name : "";
326
    int numRuns = scores.getNumRuns();
327
    int numPlay = scores.getNumPlays();
328
    int deviceID= scores.getDeviceID();
329
    String objlist = scores.getUnsubmittedObjlist();
330
    String lvllist = scores.getUnsubmittedLevellist();
331
    String timlist = scores.getUnsubmittedTimelist();
332
    String country = scores.getCountry();
333
    int hash = computeHash(name,veri,country,lvllist,objlist,timlist,numRuns);
334

    
335
    String url="https://distorted.org/magic/cgi-bin/submit.cgi";
336
    url += "?n="+name+"&v="+veri+"&r="+numRuns+"&p="+numPlay+"&i="+deviceID+"&e="+mVersion+"d";
337
    url += "&o="+objlist+"&l="+lvllist+"&t="+timlist+"&c="+country+"&h="+hash;
338
    url += "&oo="+RubikObjectList.getObjectList()+"&min=0&max="+MAX_LEVEL+"&lo="+MAX_PLACES;
339

    
340
    return url;
341
    }
342

    
343
///////////////////////////////////////////////////////////////////////////////////////////////////
344

    
345
  private boolean gottaDownload()
346
    {
347
    return ((mScores.length()==0) && !mRunning);
348
    }
349

    
350
///////////////////////////////////////////////////////////////////////////////////////////////////
351

    
352
  @Override
353
  public void run()
354
    {
355
    boolean success=true;
356

    
357
    try
358
      {
359
      if( mMode==DOWNLOAD && gottaDownload() )
360
        {
361
        mRunning = true;
362
        success = network(constructDownloadURL());
363
        }
364
      if( mMode==SUBMIT )
365
        {
366
        mRunning = true;
367

    
368
        if( RubikScores.getInstance().thereAreUnsubmittedRecords() )
369
          {
370
          success = network(constructSubmitURL());
371
          }
372
        }
373
      }
374
    catch( Exception e )
375
      {
376
      mReceiver.message("Exception downloading records: "+e.getMessage() );
377
      }
378

    
379
    if( mRunning )
380
      {
381
      success = fillValues();
382
      mRunning = false;
383
      }
384

    
385
    if( success )
386
      {
387
      mReceiver.receive(mCountry, mName, mTime);
388

    
389
      if( mMode==SUBMIT )
390
        {
391
        RubikScores.getInstance().successfulSubmit();
392
        }
393
      }
394
    }
395

    
396
///////////////////////////////////////////////////////////////////////////////////////////////////
397

    
398
  private RubikScoresDownloader()
399
    {
400

    
401
    }
402

    
403
///////////////////////////////////////////////////////////////////////////////////////////////////
404
// PUBLIC API
405
///////////////////////////////////////////////////////////////////////////////////////////////////
406

    
407
  public static void onPause()
408
    {
409
    mRunning = false;
410
    }
411

    
412
///////////////////////////////////////////////////////////////////////////////////////////////////
413

    
414
  public static RubikScoresDownloader getInstance()
415
    {
416
    if( mThis==null )
417
      {
418
      mThis = new RubikScoresDownloader();
419
      }
420

    
421
    return mThis;
422
    }
423

    
424
///////////////////////////////////////////////////////////////////////////////////////////////////
425

    
426
  public void download(Receiver receiver, FragmentActivity act)
427
    {
428
    mReceiver = receiver;
429
    mMode     = DOWNLOAD;
430
    mVersion  = act.getString(R.string.app_version);
431

    
432
    Thread networkThrd = new Thread(this);
433
    networkThrd.start();
434
    }
435

    
436
///////////////////////////////////////////////////////////////////////////////////////////////////
437

    
438
  public void submit(Receiver receiver, FragmentActivity act)
439
    {
440
    mReceiver = receiver;
441
    mMode     = SUBMIT;
442
    mVersion  = act.getString(R.string.app_version);
443

    
444
    Thread networkThrd = new Thread(this);
445
    networkThrd.start();
446
    }
447
}
(2-2/2)