Project

General

Profile

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

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

1 fdec60a3 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
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 f0e87514 Leszek Koltunski
package org.distorted.scores;
21 fdec60a3 Leszek Koltunski
22 4895fff6 Leszek Koltunski
import android.support.v4.app.FragmentActivity;
23
24
import org.distorted.magic.R;
25 4888e97c Leszek Koltunski
import org.distorted.object.RubikObjectList;
26
27 36e2cbdd Leszek Koltunski
import java.io.InputStream;
28
import java.net.HttpURLConnection;
29
import java.net.URL;
30 cc5ec229 Leszek Koltunski
import java.net.UnknownHostException;
31 36e2cbdd Leszek Koltunski
32 7aff6aa7 Leszek Koltunski
import static org.distorted.uistate.RubikStatePlay.MAX_SCRAMBLE;
33 211b48f2 Leszek Koltunski
34 fdec60a3 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
35
36 211b48f2 Leszek Koltunski
public class RubikScoresDownloader implements Runnable
37 fdec60a3 Leszek Koltunski
  {
38 211b48f2 Leszek Koltunski
  public interface Receiver
39 b8b38548 Leszek Koltunski
    {
40 1c90c64a Leszek Koltunski
    void receive(String[][][] country, String[][][] name, float[][][] time);
41 4895fff6 Leszek Koltunski
    void message(String mess);
42 17f9a695 Leszek Koltunski
    void serverError(String error);
43 b8b38548 Leszek Koltunski
    }
44
45 286d73ae Leszek Koltunski
  public static final int MAX_PLACES = 10;
46 d8aa4ba8 Leszek Koltunski
47 b8b38548 Leszek Koltunski
  private static final int DOWNLOAD   = 0;
48
  private static final int SUBMIT     = 1;
49
  private static final int IDLE       = 2;
50
51 36e2cbdd Leszek Koltunski
  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 b8b38548 Leszek Koltunski
  private static boolean mRunning = false;
87
  private static int mMode = IDLE;
88
  private static Receiver mReceiver;
89 4895fff6 Leszek Koltunski
  private static String mVersion;
90 b8b38548 Leszek Koltunski
91 4888e97c Leszek Koltunski
  private static int mTotal = RubikObjectList.getTotal();
92 f3e12931 Leszek Koltunski
  private static String mScores = "";
93 4888e97c Leszek Koltunski
  private static String[][][] mCountry = new String[mTotal][MAX_SCRAMBLE][MAX_PLACES];
94
  private static String[][][] mName    = new String[mTotal][MAX_SCRAMBLE][MAX_PLACES];
95 1c90c64a Leszek Koltunski
  private static  float[][][] mTime    = new  float[mTotal][MAX_SCRAMBLE][MAX_PLACES];
96 f3e12931 Leszek Koltunski
97 4888e97c Leszek Koltunski
  private static int[][] mPlaces = new int[mTotal][MAX_SCRAMBLE];
98 bc511ea5 Leszek Koltunski
  private static RubikScoresDownloader mThis;
99 329c0aeb Leszek Koltunski
100 4895fff6 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
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 17f9a695 Leszek Koltunski
  private boolean fillValues()
112 f3e12931 Leszek Koltunski
    {
113 d8aa4ba8 Leszek Koltunski
    int begin=-1 ,end, len = mScores.length();
114 17f9a695 Leszek Koltunski
    String row;
115 f3e12931 Leszek Koltunski
116 4888e97c Leszek Koltunski
    for(int i=0; i<mTotal; i++)
117 329c0aeb Leszek Koltunski
      for(int j=0; j<MAX_SCRAMBLE; j++)
118
        {
119
        mPlaces[i][j] = 0;
120
        }
121
122 d8aa4ba8 Leszek Koltunski
    while( begin<len )
123
      {
124
      end = mScores.indexOf('\n', begin+1);
125
      if( end<0 ) end = len;
126 286d73ae Leszek Koltunski
127
      try
128
        {
129 17f9a695 Leszek Koltunski
        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 286d73ae Leszek Koltunski
        }
141
      catch(Exception ex)
142
        {
143
        // faulty row - ignore
144
        }
145
146 d8aa4ba8 Leszek Koltunski
      begin = end;
147
      }
148 17f9a695 Leszek Koltunski
149
    return true;
150 f3e12931 Leszek Koltunski
    }
151
152
///////////////////////////////////////////////////////////////////////////////////////////////////
153
154 d8aa4ba8 Leszek Koltunski
  private void fillRow(String row)
155 f3e12931 Leszek Koltunski
    {
156 d8aa4ba8 Leszek Koltunski
    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 286d73ae Leszek Koltunski
    int s5 = row.length();
161 d8aa4ba8 Leszek Koltunski
162
    if( s5>s4 && s4>s3 && s3>s2 && s2>s1 && s1>0 )
163
      {
164 286d73ae Leszek Koltunski
      int object = RubikObjectList.unpackObjectFromString( row.substring(0,s1) );
165 b8b38548 Leszek Koltunski
166 286d73ae Leszek Koltunski
      if( object>=0 && object<mTotal )
167 d8aa4ba8 Leszek Koltunski
        {
168 4888e97c Leszek Koltunski
        int level      = Integer.parseInt( row.substring(s1+1,s2) );
169 286d73ae Leszek Koltunski
        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 d8aa4ba8 Leszek Koltunski
173 286d73ae Leszek Koltunski
        if(level>0 && level<=MAX_SCRAMBLE)
174 d8aa4ba8 Leszek Koltunski
          {
175 286d73ae Leszek Koltunski
          int p = mPlaces[object][level];
176
          mPlaces[object][level]++;
177 329c0aeb Leszek Koltunski
178 286d73ae Leszek Koltunski
          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 d8aa4ba8 Leszek Koltunski
          }
182
        }
183
      }
184 f3e12931 Leszek Koltunski
    }
185
186 36e2cbdd Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
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 f3e12931 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
224
225 4895fff6 Leszek Koltunski
  private boolean network(String url)
226 f3e12931 Leszek Koltunski
    {
227 4895fff6 Leszek Koltunski
    android.util.Log.e("down", "url: "+url);
228 36e2cbdd Leszek Koltunski
229
    try
230
      {
231 4895fff6 Leszek Koltunski
      java.net.URL connectURL = new URL(url);
232 36e2cbdd Leszek Koltunski
      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 a675474f Leszek Koltunski
      try( InputStream is = conn.getInputStream() )
242 36e2cbdd Leszek Koltunski
        {
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 cc5ec229 Leszek Koltunski
      catch( final Exception e)
252 36e2cbdd Leszek Koltunski
        {
253 4895fff6 Leszek Koltunski
        mReceiver.message("Failed to get an answer from the High Scores server");
254 a675474f Leszek Koltunski
        return false;
255 36e2cbdd Leszek Koltunski
        }
256
      }
257 cc5ec229 Leszek Koltunski
    catch( final UnknownHostException e )
258
      {
259 4895fff6 Leszek Koltunski
      mReceiver.message("No access to Internet");
260 cc5ec229 Leszek Koltunski
      return false;
261
      }
262
    catch( final SecurityException e )
263
      {
264 4895fff6 Leszek Koltunski
      mReceiver.message("Application not authorized to connect to the Internet");
265 cc5ec229 Leszek Koltunski
      return false;
266
      }
267
    catch( final Exception e )
268 36e2cbdd Leszek Koltunski
      {
269 4895fff6 Leszek Koltunski
      mReceiver.message(e.getMessage());
270 a675474f Leszek Koltunski
      return false;
271 36e2cbdd Leszek Koltunski
      }
272
273 329c0aeb Leszek Koltunski
    if( mScores.length()==0 )
274
      {
275 4895fff6 Leszek Koltunski
      mReceiver.message("Failed to download scores");
276 329c0aeb Leszek Koltunski
      return false;
277
      }
278
279 a675474f Leszek Koltunski
    return true;
280 b8b38548 Leszek Koltunski
    }
281 d8aa4ba8 Leszek Koltunski
282 17f9a695 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
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 d8aa4ba8 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
324
325
  private boolean gottaDownload()
326 b8b38548 Leszek Koltunski
    {
327 d8aa4ba8 Leszek Koltunski
    return ((mScores.length()==0) && !mRunning);
328 f3e12931 Leszek Koltunski
    }
329 b8b38548 Leszek Koltunski
330 d8aa4ba8 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
331
332 4f9f99a2 Leszek Koltunski
  @Override
333 d8aa4ba8 Leszek Koltunski
  public void run()
334
    {
335 a675474f Leszek Koltunski
    boolean success=true;
336
337 17f9a695 Leszek Koltunski
    try
338 d8aa4ba8 Leszek Koltunski
      {
339 17f9a695 Leszek Koltunski
      if( mMode==DOWNLOAD && gottaDownload() )
340 d8aa4ba8 Leszek Koltunski
        {
341 17f9a695 Leszek Koltunski
        mRunning = true;
342
        success = network(constructDownloadURL());
343 d8aa4ba8 Leszek Koltunski
        }
344 17f9a695 Leszek Koltunski
      if( mMode==SUBMIT )
345 4895fff6 Leszek Koltunski
        {
346 17f9a695 Leszek Koltunski
        mRunning = true;
347 4895fff6 Leszek Koltunski
348 17f9a695 Leszek Koltunski
        if( RubikScores.getInstance().thereAreUnsubmittedRecords() )
349
          {
350
          success = network(constructSubmitURL());
351
          }
352
        }
353 d8aa4ba8 Leszek Koltunski
      }
354 17f9a695 Leszek Koltunski
    catch( Exception e )
355 d8aa4ba8 Leszek Koltunski
      {
356 17f9a695 Leszek Koltunski
      mReceiver.message("Exception downloading records: "+e.getMessage() );
357 4895fff6 Leszek Koltunski
      }
358 286d73ae Leszek Koltunski
359 17f9a695 Leszek Koltunski
    if( mRunning )
360
      {
361
      success = fillValues();
362
      mRunning = false;
363
      }
364 a675474f Leszek Koltunski
365
    if( success )
366
      {
367 cc5ec229 Leszek Koltunski
      mReceiver.receive(mCountry, mName, mTime);
368 17f9a695 Leszek Koltunski
369
      if( mMode==SUBMIT )
370
        {
371
        RubikScores.getInstance().successfulSubmit();
372
        }
373 a675474f Leszek Koltunski
      }
374 d8aa4ba8 Leszek Koltunski
    }
375 4f9f99a2 Leszek Koltunski
376 bc511ea5 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
377
378
  private RubikScoresDownloader()
379
    {
380
381
    }
382
383 4f9f99a2 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
384
// PUBLIC API
385
///////////////////////////////////////////////////////////////////////////////////////////////////
386
387
  public static void onPause()
388
    {
389
    mRunning = false;
390
    }
391
392 bc511ea5 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
393
394
  public static RubikScoresDownloader getInstance()
395
    {
396
    if( mThis==null )
397
      {
398
      mThis = new RubikScoresDownloader();
399
      }
400
401
    return mThis;
402
    }
403
404 4f9f99a2 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
405
406 4895fff6 Leszek Koltunski
  public void download(Receiver receiver, FragmentActivity act)
407 4f9f99a2 Leszek Koltunski
    {
408
    mReceiver = receiver;
409 6f8e5dfc Leszek Koltunski
    mMode     = DOWNLOAD;
410 4895fff6 Leszek Koltunski
    mVersion  = act.getString(R.string.app_version);
411 6f8e5dfc Leszek Koltunski
412 4f9f99a2 Leszek Koltunski
    Thread networkThrd = new Thread(this);
413
    networkThrd.start();
414
    }
415 bc511ea5 Leszek Koltunski
416
///////////////////////////////////////////////////////////////////////////////////////////////////
417
418 4895fff6 Leszek Koltunski
  public void submit(Receiver receiver, FragmentActivity act)
419 bc511ea5 Leszek Koltunski
    {
420 4895fff6 Leszek Koltunski
    mReceiver = receiver;
421
    mMode     = SUBMIT;
422
    mVersion  = act.getString(R.string.app_version);
423 bc511ea5 Leszek Koltunski
424 4895fff6 Leszek Koltunski
    Thread networkThrd = new Thread(this);
425
    networkThrd.start();
426 bc511ea5 Leszek Koltunski
    }
427 b8b38548 Leszek Koltunski
}