Project

General

Profile

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

magiccube / src / main / java / org / distorted / scores / RubikScoresDownloader.java @ 17f9a695

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.magic.R;
25
import org.distorted.object.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.uistate.RubikStatePlay.MAX_SCRAMBLE;
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 serverError(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_SCRAMBLE][MAX_PLACES];
94
  private static String[][][] mName    = new String[mTotal][MAX_SCRAMBLE][MAX_PLACES];
95
  private static  float[][][] mTime    = new  float[mTotal][MAX_SCRAMBLE][MAX_PLACES];
96

    
97
  private static int[][] mPlaces = new int[mTotal][MAX_SCRAMBLE];
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
    return 0;
107
    }
108

    
109
///////////////////////////////////////////////////////////////////////////////////////////////////
110

    
111
  private boolean fillValues()
112
    {
113
    int begin=-1 ,end, len = mScores.length();
114
    String row;
115

    
116
    for(int i=0; i<mTotal; i++)
117
      for(int j=0; j<MAX_SCRAMBLE; j++)
118
        {
119
        mPlaces[i][j] = 0;
120
        }
121

    
122
    while( begin<len )
123
      {
124
      end = mScores.indexOf('\n', begin+1);
125
      if( end<0 ) end = len;
126

    
127
      try
128
        {
129
        row = mScores.substring(begin+1,end);
130

    
131
        if( row.length()==1 )
132
          {
133
          mReceiver.serverError(row);
134
          return false;
135
          }
136
        else
137
          {
138
          fillRow(row);
139
          }
140
        }
141
      catch(Exception ex)
142
        {
143
        // faulty row - ignore
144
        }
145

    
146
      begin = end;
147
      }
148

    
149
    return true;
150
    }
151

    
152
///////////////////////////////////////////////////////////////////////////////////////////////////
153

    
154
  private void fillRow(String row)
155
    {
156
    int s1 = row.indexOf(' ');
157
    int s2 = row.indexOf(' ',s1+1);
158
    int s3 = row.indexOf(' ',s2+1);
159
    int s4 = row.indexOf(' ',s3+1);
160
    int s5 = row.length();
161

    
162
    if( s5>s4 && s4>s3 && s3>s2 && s2>s1 && s1>0 )
163
      {
164
      int object = RubikObjectList.unpackObjectFromString( row.substring(0,s1) );
165

    
166
      if( object>=0 && object<mTotal )
167
        {
168
        int level      = Integer.parseInt( row.substring(s1+1,s2) );
169
        String name    = row.substring(s2+1, s3);
170
        int time       = Integer.parseInt( row.substring(s3+1,s4) );
171
        String country = row.substring(s4+1, s5);
172

    
173
        if(level>0 && level<=MAX_SCRAMBLE)
174
          {
175
          int p = mPlaces[object][level];
176
          mPlaces[object][level]++;
177

    
178
          mCountry[object][level-1][p] = country;
179
          mName   [object][level-1][p] = name;
180
          mTime   [object][level-1][p] = ((float)(time/100))/10.0f;
181
          }
182
        }
183
      }
184
    }
185

    
186
///////////////////////////////////////////////////////////////////////////////////////////////////
187

    
188
  private String URLencode(String s)
189
    {
190
    StringBuilder sbuf = new StringBuilder();
191
    int len = s.length();
192

    
193
    for (int i = 0; i < len; i++)
194
      {
195
      int ch = s.charAt(i);
196

    
197
           if ('A' <= ch && ch <= 'Z') sbuf.append((char)ch);
198
      else if ('a' <= ch && ch <= 'z') sbuf.append((char)ch);
199
      else if ('0' <= ch && ch <= '9') sbuf.append((char)ch);
200
      else if (ch == ' '             ) sbuf.append('+');
201
      else if (ch == '-' || ch == '_'
202
            || ch == '.' || ch == '!'
203
            || ch == '~' || ch == '*'
204
            || ch == '\'' || ch == '('
205
            || ch == ')'             ) sbuf.append((char)ch);
206
      else if (ch <= 0x007f)           sbuf.append(hex[ch]);
207
      else if (ch <= 0x07FF)
208
        {
209
        sbuf.append(hex[0xc0 | (ch >> 6)]);
210
        sbuf.append(hex[0x80 | (ch & 0x3F)]);
211
        }
212
      else
213
        {
214
        sbuf.append(hex[0xe0 | (ch >> 12)]);
215
        sbuf.append(hex[0x80 | ((ch >> 6) & 0x3F)]);
216
        sbuf.append(hex[0x80 | (ch & 0x3F)]);
217
        }
218
      }
219

    
220
    return sbuf.toString();
221
    }
222

    
223
///////////////////////////////////////////////////////////////////////////////////////////////////
224

    
225
  private boolean network(String url)
226
    {
227
    android.util.Log.e("down", "url: "+url);
228

    
229
    try
230
      {
231
      java.net.URL connectURL = new URL(url);
232
      HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
233

    
234
      conn.setDoInput(true);
235
      conn.setDoOutput(true);
236
      conn.setUseCaches(false);
237
      conn.setRequestMethod("GET");
238
      conn.connect();
239
      conn.getOutputStream().flush();
240

    
241
      try( InputStream is = conn.getInputStream() )
242
        {
243
        int ch;
244
        StringBuilder sb = new StringBuilder();
245
        while( ( ch = is.read() ) != -1 )
246
          {
247
          sb.append( (char)ch );
248
          }
249
        mScores = sb.toString();
250
        }
251
      catch( final Exception e)
252
        {
253
        mReceiver.message("Failed to get an answer from the High Scores server");
254
        return false;
255
        }
256
      }
257
    catch( final UnknownHostException e )
258
      {
259
      mReceiver.message("No access to Internet");
260
      return false;
261
      }
262
    catch( final SecurityException e )
263
      {
264
      mReceiver.message("Application not authorized to connect to the Internet");
265
      return false;
266
      }
267
    catch( final Exception e )
268
      {
269
      mReceiver.message(e.getMessage());
270
      return false;
271
      }
272

    
273
    if( mScores.length()==0 )
274
      {
275
      mReceiver.message("Failed to download scores");
276
      return false;
277
      }
278

    
279
    return true;
280
    }
281

    
282
///////////////////////////////////////////////////////////////////////////////////////////////////
283

    
284
  private String constructDownloadURL()
285
    {
286
    RubikScores scores = RubikScores.getInstance();
287
    String name = URLencode(scores.getName());
288
    String veri = scores.isVerified() ? name : "";
289
    int numRuns = scores.getNumRuns();
290
    int numPlay = scores.getNumPlays();
291

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

    
296
    return url;
297
    }
298

    
299
///////////////////////////////////////////////////////////////////////////////////////////////////
300

    
301
  private String constructSubmitURL()
302
    {
303
    RubikScores scores = RubikScores.getInstance();
304
    String name = URLencode(scores.getName());
305
    String veri = scores.isVerified() ? name : "";
306
    int numRuns = scores.getNumRuns();
307
    int numPlay = scores.getNumPlays();
308
    int deviceID= scores.getDeviceID();
309
    String objlist = scores.getUnsubmittedObjlist();
310
    String lvllist = scores.getUnsubmittedLevellist();
311
    String timlist = scores.getUnsubmittedTimelist();
312
    String country = scores.getCountry();
313
    int hash = computeHash(name,veri,country,lvllist,objlist,timlist,numRuns);
314

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

    
320
    return url;
321
    }
322

    
323
///////////////////////////////////////////////////////////////////////////////////////////////////
324

    
325
  private boolean gottaDownload()
326
    {
327
    return ((mScores.length()==0) && !mRunning);
328
    }
329

    
330
///////////////////////////////////////////////////////////////////////////////////////////////////
331

    
332
  @Override
333
  public void run()
334
    {
335
    boolean success=true;
336

    
337
    try
338
      {
339
      if( mMode==DOWNLOAD && gottaDownload() )
340
        {
341
        mRunning = true;
342
        success = network(constructDownloadURL());
343
        }
344
      if( mMode==SUBMIT )
345
        {
346
        mRunning = true;
347

    
348
        if( RubikScores.getInstance().thereAreUnsubmittedRecords() )
349
          {
350
          success = network(constructSubmitURL());
351
          }
352
        }
353
      }
354
    catch( Exception e )
355
      {
356
      mReceiver.message("Exception downloading records: "+e.getMessage() );
357
      }
358

    
359
    if( mRunning )
360
      {
361
      success = fillValues();
362
      mRunning = false;
363
      }
364

    
365
    if( success )
366
      {
367
      mReceiver.receive(mCountry, mName, mTime);
368

    
369
      if( mMode==SUBMIT )
370
        {
371
        RubikScores.getInstance().successfulSubmit();
372
        }
373
      }
374
    }
375

    
376
///////////////////////////////////////////////////////////////////////////////////////////////////
377

    
378
  private RubikScoresDownloader()
379
    {
380

    
381
    }
382

    
383
///////////////////////////////////////////////////////////////////////////////////////////////////
384
// PUBLIC API
385
///////////////////////////////////////////////////////////////////////////////////////////////////
386

    
387
  public static void onPause()
388
    {
389
    mRunning = false;
390
    }
391

    
392
///////////////////////////////////////////////////////////////////////////////////////////////////
393

    
394
  public static RubikScoresDownloader getInstance()
395
    {
396
    if( mThis==null )
397
      {
398
      mThis = new RubikScoresDownloader();
399
      }
400

    
401
    return mThis;
402
    }
403

    
404
///////////////////////////////////////////////////////////////////////////////////////////////////
405

    
406
  public void download(Receiver receiver, FragmentActivity act)
407
    {
408
    mReceiver = receiver;
409
    mMode     = DOWNLOAD;
410
    mVersion  = act.getString(R.string.app_version);
411

    
412
    Thread networkThrd = new Thread(this);
413
    networkThrd.start();
414
    }
415

    
416
///////////////////////////////////////////////////////////////////////////////////////////////////
417

    
418
  public void submit(Receiver receiver, FragmentActivity act)
419
    {
420
    mReceiver = receiver;
421
    mMode     = SUBMIT;
422
    mVersion  = act.getString(R.string.app_version);
423

    
424
    Thread networkThrd = new Thread(this);
425
    networkThrd.start();
426
    }
427
}
(2-2/2)