Project

General

Profile

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

magiccube / src / main / java / org / distorted / network / RubikNetwork.java @ 63dd19c4

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 6a083c6a Leszek Koltunski
package org.distorted.network;
21 fdec60a3 Leszek Koltunski
22 1d643a0e Leszek Koltunski
import java.io.BufferedReader;
23 3f7a4363 Leszek Koltunski
import java.io.InputStream;
24 1d643a0e Leszek Koltunski
import java.io.InputStreamReader;
25 3f7a4363 Leszek Koltunski
import java.net.HttpURLConnection;
26
import java.net.URL;
27
import java.net.UnknownHostException;
28
import java.security.MessageDigest;
29
import java.security.NoSuchAlgorithmException;
30
31 6a083c6a Leszek Koltunski
import android.app.Activity;
32 1780dcb0 Leszek Koltunski
import android.content.pm.PackageInfo;
33
import android.content.pm.PackageManager;
34
35 6a083c6a Leszek Koltunski
import androidx.appcompat.app.AppCompatActivity;
36 66e777b0 Leszek Koltunski
import androidx.fragment.app.FragmentActivity;
37 4895fff6 Leszek Koltunski
38 6a083c6a Leszek Koltunski
import org.distorted.library.main.DistortedLibrary;
39 fcf7320f Leszek Koltunski
import org.distorted.objectlib.json.JsonWriter;
40 a7d8c3cd Leszek Koltunski
import org.distorted.objects.RubikObjectList;
41 36e2cbdd Leszek Koltunski
42 d433b50e Leszek Koltunski
import static org.distorted.objects.RubikObjectList.MAX_LEVEL;
43 211b48f2 Leszek Koltunski
44 fdec60a3 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
45
46 6a083c6a Leszek Koltunski
public class RubikNetwork implements Runnable
47 fdec60a3 Leszek Koltunski
  {
48 211b48f2 Leszek Koltunski
  public interface Receiver
49 b8b38548 Leszek Koltunski
    {
50 1c90c64a Leszek Koltunski
    void receive(String[][][] country, String[][][] name, float[][][] time);
51 4895fff6 Leszek Koltunski
    void message(String mess);
52 4c0cd600 Leszek Koltunski
    void error(String error);
53 b8b38548 Leszek Koltunski
    }
54
55 63dd19c4 Leszek Koltunski
  public interface Updatee
56
    {
57
    void receiveUpdate(RubikUpdates update);
58
    void errorUpdate();
59
    }
60
61 286d73ae Leszek Koltunski
  public static final int MAX_PLACES = 10;
62 d8aa4ba8 Leszek Koltunski
63 b8b38548 Leszek Koltunski
  private static final int DOWNLOAD   = 0;
64
  private static final int SUBMIT     = 1;
65 6a083c6a Leszek Koltunski
  private static final int DEBUG      = 2;
66 1fa125c2 Leszek Koltunski
  private static final int SUSPICIOUS = 3;
67
  private static final int IDLE       = 4;
68 b8b38548 Leszek Koltunski
69 14f14138 Leszek Koltunski
  private static final int REND_ADRENO= 0;
70
  private static final int REND_MALI  = 1;
71
  private static final int REND_POWER = 2;
72
  private static final int REND_OTHER = 3;
73 9d4c38eb Leszek Koltunski
74 63dd19c4 Leszek Koltunski
  private static final int DEBUG_NOT_YET = 0;
75
  private static final int DEBUG_RUNNING = 1;
76
  private static final int DEBUG_SUCCESS = 2;
77
  private static final int DEBUG_FAILURE = 3;
78
79 36e2cbdd Leszek Koltunski
  private final String[] hex = {
80
    "%00", "%01", "%02", "%03", "%04", "%05", "%06", "%07",
81
    "%08", "%09", "%0a", "%0b", "%0c", "%0d", "%0e", "%0f",
82
    "%10", "%11", "%12", "%13", "%14", "%15", "%16", "%17",
83
    "%18", "%19", "%1a", "%1b", "%1c", "%1d", "%1e", "%1f",
84
    "%20", "%21", "%22", "%23", "%24", "%25", "%26", "%27",
85
    "%28", "%29", "%2a", "%2b", "%2c", "%2d", "%2e", "%2f",
86
    "%30", "%31", "%32", "%33", "%34", "%35", "%36", "%37",
87
    "%38", "%39", "%3a", "%3b", "%3c", "%3d", "%3e", "%3f",
88
    "%40", "%41", "%42", "%43", "%44", "%45", "%46", "%47",
89
    "%48", "%49", "%4a", "%4b", "%4c", "%4d", "%4e", "%4f",
90
    "%50", "%51", "%52", "%53", "%54", "%55", "%56", "%57",
91
    "%58", "%59", "%5a", "%5b", "%5c", "%5d", "%5e", "%5f",
92
    "%60", "%61", "%62", "%63", "%64", "%65", "%66", "%67",
93
    "%68", "%69", "%6a", "%6b", "%6c", "%6d", "%6e", "%6f",
94
    "%70", "%71", "%72", "%73", "%74", "%75", "%76", "%77",
95
    "%78", "%79", "%7a", "%7b", "%7c", "%7d", "%7e", "%7f",
96
    "%80", "%81", "%82", "%83", "%84", "%85", "%86", "%87",
97
    "%88", "%89", "%8a", "%8b", "%8c", "%8d", "%8e", "%8f",
98
    "%90", "%91", "%92", "%93", "%94", "%95", "%96", "%97",
99
    "%98", "%99", "%9a", "%9b", "%9c", "%9d", "%9e", "%9f",
100
    "%a0", "%a1", "%a2", "%a3", "%a4", "%a5", "%a6", "%a7",
101
    "%a8", "%a9", "%aa", "%ab", "%ac", "%ad", "%ae", "%af",
102
    "%b0", "%b1", "%b2", "%b3", "%b4", "%b5", "%b6", "%b7",
103
    "%b8", "%b9", "%ba", "%bb", "%bc", "%bd", "%be", "%bf",
104
    "%c0", "%c1", "%c2", "%c3", "%c4", "%c5", "%c6", "%c7",
105
    "%c8", "%c9", "%ca", "%cb", "%cc", "%cd", "%ce", "%cf",
106
    "%d0", "%d1", "%d2", "%d3", "%d4", "%d5", "%d6", "%d7",
107
    "%d8", "%d9", "%da", "%db", "%dc", "%dd", "%de", "%df",
108
    "%e0", "%e1", "%e2", "%e3", "%e4", "%e5", "%e6", "%e7",
109
    "%e8", "%e9", "%ea", "%eb", "%ec", "%ed", "%ee", "%ef",
110
    "%f0", "%f1", "%f2", "%f3", "%f4", "%f5", "%f6", "%f7",
111
    "%f8", "%f9", "%fa", "%fb", "%fc", "%fd", "%fe", "%ff"
112
    };
113
114 a36b9dca Leszek Koltunski
  private static String[][][] mCountry;
115
  private static String[][][] mName;
116
  private static float[][][] mTime;
117
  private static int[][] mPlaces;
118 688f7712 Leszek Koltunski
119 6a083c6a Leszek Koltunski
  private static RubikNetwork mThis;
120 688f7712 Leszek Koltunski
  private static String mScores = "";
121 b8b38548 Leszek Koltunski
  private static boolean mRunning = false;
122
  private static int mMode = IDLE;
123
  private static Receiver mReceiver;
124 63dd19c4 Leszek Koltunski
  private static Updatee mUpdatee;
125 4895fff6 Leszek Koltunski
  private static String mVersion;
126 63dd19c4 Leszek Koltunski
  private static String mSuspicious;
127 a7d8c3cd Leszek Koltunski
  private static int mNumObjects;
128 fcf7320f Leszek Koltunski
  private static RubikUpdates mUpdates;
129 63dd19c4 Leszek Koltunski
  private static int mDebugState;
130 b8b38548 Leszek Koltunski
131 a36b9dca Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
132
133
  private static void initializeStatics()
134
    {
135 a7d8c3cd Leszek Koltunski
    int newNum = RubikObjectList.getNumObjects();
136
137
    if( mCountry==null || newNum!=mNumObjects ) mCountry = new String[newNum][MAX_LEVEL][MAX_PLACES];
138
    if( mName==null    || newNum!=mNumObjects ) mName    = new String[newNum][MAX_LEVEL][MAX_PLACES];
139
    if( mTime==null    || newNum!=mNumObjects ) mTime    = new  float[newNum][MAX_LEVEL][MAX_PLACES];
140 fcf7320f Leszek Koltunski
    if( mPlaces==null  || newNum!=mNumObjects ) mPlaces  = new    int[newNum][MAX_LEVEL];
141
142
    if( mUpdates==null ) mUpdates = new RubikUpdates();
143 a7d8c3cd Leszek Koltunski
144
    mNumObjects = newNum;
145 a36b9dca Leszek Koltunski
    }
146
147 4895fff6 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
148
149 86cbdab1 Leszek Koltunski
  private static String computeHash(String stringToHash, byte[] salt)
150 4895fff6 Leszek Koltunski
    {
151 86cbdab1 Leszek Koltunski
    String generatedPassword;
152
153
    try
154
      {
155
      MessageDigest md = MessageDigest.getInstance("MD5");
156
      md.update(salt);
157
      byte[] bytes = md.digest(stringToHash.getBytes());
158
      StringBuilder sb = new StringBuilder();
159
160
      for (byte aByte : bytes)
161
        {
162
        sb.append(Integer.toString((aByte & 0xff) + 0x100, 16).substring(1));
163
        }
164
165
      generatedPassword = sb.toString();
166
      }
167
    catch (NoSuchAlgorithmException e)
168
      {
169
      return "NoSuchAlgorithm";
170
      }
171
172
    return generatedPassword;
173 4895fff6 Leszek Koltunski
    }
174
175
///////////////////////////////////////////////////////////////////////////////////////////////////
176
177 fcf7320f Leszek Koltunski
  private boolean fillValuesNormal()
178 f3e12931 Leszek Koltunski
    {
179 d8aa4ba8 Leszek Koltunski
    int begin=-1 ,end, len = mScores.length();
180 17f9a695 Leszek Koltunski
    String row;
181 f3e12931 Leszek Koltunski
182 4c0cd600 Leszek Koltunski
    if( len==0 )
183
      {
184 dd016102 Leszek Koltunski
      if( mReceiver!=null ) mReceiver.error("1");
185 4c0cd600 Leszek Koltunski
      return false;
186
      }
187 90fd47b0 Leszek Koltunski
    else if( len<=2 )
188 4c0cd600 Leszek Koltunski
      {
189 dd016102 Leszek Koltunski
      if( mReceiver!=null ) mReceiver.error(mScores);
190 4c0cd600 Leszek Koltunski
      return false;
191
      }
192
193 a7d8c3cd Leszek Koltunski
    for(int i=0; i<mNumObjects; i++)
194 85b09df4 Leszek Koltunski
      for(int j=0; j<MAX_LEVEL; j++)
195 329c0aeb Leszek Koltunski
        {
196
        mPlaces[i][j] = 0;
197
        }
198
199 d8aa4ba8 Leszek Koltunski
    while( begin<len )
200
      {
201
      end = mScores.indexOf('\n', begin+1);
202
      if( end<0 ) end = len;
203 286d73ae Leszek Koltunski
204
      try
205
        {
206 17f9a695 Leszek Koltunski
        row = mScores.substring(begin+1,end);
207 4c0cd600 Leszek Koltunski
        fillRow(row);
208 286d73ae Leszek Koltunski
        }
209
      catch(Exception ex)
210
        {
211
        // faulty row - ignore
212
        }
213
214 d8aa4ba8 Leszek Koltunski
      begin = end;
215
      }
216 17f9a695 Leszek Koltunski
217
    return true;
218 f3e12931 Leszek Koltunski
    }
219
220
///////////////////////////////////////////////////////////////////////////////////////////////////
221
222 d8aa4ba8 Leszek Koltunski
  private void fillRow(String row)
223 f3e12931 Leszek Koltunski
    {
224 d8aa4ba8 Leszek Koltunski
    int s1 = row.indexOf(' ');
225
    int s2 = row.indexOf(' ',s1+1);
226
    int s3 = row.indexOf(' ',s2+1);
227
    int s4 = row.indexOf(' ',s3+1);
228 286d73ae Leszek Koltunski
    int s5 = row.length();
229 d8aa4ba8 Leszek Koltunski
230
    if( s5>s4 && s4>s3 && s3>s2 && s2>s1 && s1>0 )
231
      {
232 a7d8c3cd Leszek Koltunski
      int object = RubikObjectList.getOrdinal( row.substring(0,s1) );
233 b8b38548 Leszek Koltunski
234 a7d8c3cd Leszek Koltunski
      if( object>=0 && object<mNumObjects )
235 d8aa4ba8 Leszek Koltunski
        {
236 8e3898c8 Leszek Koltunski
        int level      = Integer.parseInt( row.substring(s1+1,s2) );
237 286d73ae Leszek Koltunski
        String name    = row.substring(s2+1, s3);
238
        int time       = Integer.parseInt( row.substring(s3+1,s4) );
239
        String country = row.substring(s4+1, s5);
240 d8aa4ba8 Leszek Koltunski
241 c8249cf6 Leszek Koltunski
        if( country.equals("do") ) country = "dm"; // see RubikScores.setCountry()
242
243 8e3898c8 Leszek Koltunski
        if(level>=0 && level<MAX_LEVEL)
244 d8aa4ba8 Leszek Koltunski
          {
245 8e3898c8 Leszek Koltunski
          int p = mPlaces[object][level];
246
          mPlaces[object][level]++;
247 329c0aeb Leszek Koltunski
248 8e3898c8 Leszek Koltunski
          mCountry[object][level][p] = country;
249
          mName   [object][level][p] = name;
250 79e752b3 Leszek Koltunski
          mTime   [object][level][p] = ((float)(time/10))/100.0f;
251 d8aa4ba8 Leszek Koltunski
          }
252
        }
253
      }
254 874c37b1 Leszek Koltunski
    else
255
      {
256 5d50e7a7 Leszek Koltunski
      tryDoCommand(row);
257
      }
258
    }
259
260
///////////////////////////////////////////////////////////////////////////////////////////////////
261
262
  private void tryDoCommand(String row)
263
    {
264
    if( row.startsWith("comm") )
265
      {
266
      int colon = row.indexOf(':');
267
268
      if( colon>0 )
269 874c37b1 Leszek Koltunski
        {
270 5d50e7a7 Leszek Koltunski
        String commandNumber = row.substring(4,colon);
271
        int number;
272
273
        try
274
          {
275
          number = Integer.parseInt(commandNumber);
276
          }
277
        catch(NumberFormatException ex)
278
          {
279
          number=0;
280
          }
281 874c37b1 Leszek Koltunski
282 5d50e7a7 Leszek Koltunski
        if(number==1)
283 874c37b1 Leszek Koltunski
          {
284
          String country = row.substring(colon+1);
285
          RubikScores scores = RubikScores.getInstance();
286
          scores.setCountry(country);
287
          }
288
        }
289
      }
290 f3e12931 Leszek Koltunski
    }
291
292 9d4c38eb Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
293
294
  private int getRendererType(String renderer)
295
    {
296
    if( renderer.contains("Adreno")  ) return REND_ADRENO;
297
    if( renderer.contains("Mali")    ) return REND_MALI;
298
    if( renderer.contains("PowerVR") ) return REND_POWER;
299
300
    return REND_OTHER;
301
    }
302
303
///////////////////////////////////////////////////////////////////////////////////////////////////
304
305
  private String parseRenderer(final int type, String renderer)
306
    {
307
    if( type==REND_ADRENO || type==REND_POWER )
308
      {
309
      int lastSpace = renderer.lastIndexOf(' ');
310
      String ret = renderer.substring(lastSpace+1);
311
      return URLencode(ret);
312
      }
313
314
    if( type==REND_MALI )
315
      {
316
      int firstHyphen = renderer.indexOf('-');
317
      String ret = renderer.substring(firstHyphen+1);
318
      return URLencode(ret);
319
      }
320
321
    return "other";
322
    }
323
324
///////////////////////////////////////////////////////////////////////////////////////////////////
325
326
  private String parseVersion(final int type, String version)
327
    {
328
    switch(type)
329
      {
330
      case REND_ADRENO: int aMonkey = version.indexOf('@');
331
                        int aDot = version.indexOf('.', aMonkey);
332
                        String ret1 = aDot>=3 ? version.substring(aDot-3,aDot) : "";
333
                        return URLencode(ret1);
334
      case REND_MALI  : int mV1 = version.indexOf("v1");
335
                        int mHyphen = version.indexOf('-', mV1);
336
                        String ret2 = mHyphen>mV1+3 && mV1>=0 ? version.substring(mV1+3,mHyphen) : "";
337
                        return URLencode(ret2);
338
      case REND_POWER : int pMonkey = version.indexOf('@');
339
                        int pSpace  = version.lastIndexOf(' ');
340
                        String ret3 = pSpace>=0 && pMonkey>pSpace+1 ? version.substring(pSpace+1,pMonkey) : "";
341
                        return URLencode(ret3);
342
      default         : return "";
343
      }
344
    }
345
346 36e2cbdd Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
347
348
  private String URLencode(String s)
349
    {
350
    StringBuilder sbuf = new StringBuilder();
351
    int len = s.length();
352
353
    for (int i = 0; i < len; i++)
354
      {
355
      int ch = s.charAt(i);
356
357
           if ('A' <= ch && ch <= 'Z') sbuf.append((char)ch);
358
      else if ('a' <= ch && ch <= 'z') sbuf.append((char)ch);
359
      else if ('0' <= ch && ch <= '9') sbuf.append((char)ch);
360
      else if (ch == ' '             ) sbuf.append('+');
361
      else if (ch == '-' || ch == '_'
362
            || ch == '.' || ch == '!'
363
            || ch == '~' || ch == '*'
364
            || ch == '\'' || ch == '('
365
            || ch == ')'             ) sbuf.append((char)ch);
366
      else if (ch <= 0x007f)           sbuf.append(hex[ch]);
367
      else if (ch <= 0x07FF)
368
        {
369
        sbuf.append(hex[0xc0 | (ch >> 6)]);
370
        sbuf.append(hex[0x80 | (ch & 0x3F)]);
371
        }
372
      else
373
        {
374
        sbuf.append(hex[0xe0 | (ch >> 12)]);
375
        sbuf.append(hex[0x80 | ((ch >> 6) & 0x3F)]);
376
        sbuf.append(hex[0x80 | (ch & 0x3F)]);
377
        }
378
      }
379
380
    return sbuf.toString();
381
    }
382
383 6a083c6a Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
384
385
  private void sendDebug()
386
    {
387
    String url = constructDebugURL();
388
389
    try
390
      {
391
      java.net.URL connectURL = new URL(url);
392
      HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
393
394
      conn.setDoInput(true);
395
      conn.setDoOutput(true);
396
      conn.setUseCaches(false);
397
      conn.setRequestMethod("GET");
398
      conn.connect();
399
      conn.getOutputStream().flush();
400 fcf7320f Leszek Koltunski
401
      InputStream is = conn.getInputStream();
402
      BufferedReader r = new BufferedReader(new InputStreamReader(is));
403
      StringBuilder answer = new StringBuilder();
404
405
      for (String line; (line = r.readLine()) != null; )
406
        {
407
        answer.append(line).append('\n');
408
        }
409
410
      String updates = answer.toString();
411
      mUpdates.parse(updates);
412 63dd19c4 Leszek Koltunski
      if( mUpdatee!=null ) mUpdatee.receiveUpdate(mUpdates);
413
      mDebugState = DEBUG_SUCCESS;
414 6a083c6a Leszek Koltunski
      }
415
    catch( final Exception e )
416
      {
417 63dd19c4 Leszek Koltunski
      if( mUpdatee!=null ) mUpdatee.errorUpdate();
418
      mDebugState = DEBUG_FAILURE;
419 6a083c6a Leszek Koltunski
      }
420
    }
421
422 1fa125c2 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
423
424
  private void sendSuspicious()
425
    {
426
    String url = constructSuspiciousURL();
427
428
    try
429
      {
430
      java.net.URL connectURL = new URL(url);
431
      HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
432
433
      conn.setDoInput(true);
434
      conn.setDoOutput(true);
435
      conn.setUseCaches(false);
436
      conn.setRequestMethod("GET");
437
      conn.connect();
438
      conn.getOutputStream().flush();
439
      conn.getInputStream();
440
      }
441
    catch( final Exception e )
442
      {
443
      // ignore
444
      }
445
    }
446
447 f3e12931 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
448
449 4895fff6 Leszek Koltunski
  private boolean network(String url)
450 f3e12931 Leszek Koltunski
    {
451 36e2cbdd Leszek Koltunski
    try
452
      {
453 4895fff6 Leszek Koltunski
      java.net.URL connectURL = new URL(url);
454 36e2cbdd Leszek Koltunski
      HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
455
456
      conn.setDoInput(true);
457
      conn.setDoOutput(true);
458
      conn.setUseCaches(false);
459
      conn.setRequestMethod("GET");
460
      conn.connect();
461
      conn.getOutputStream().flush();
462
463 1d643a0e Leszek Koltunski
      InputStream is = conn.getInputStream();
464
      BufferedReader r = new BufferedReader(new InputStreamReader(is));
465
      StringBuilder total = new StringBuilder();
466
467
      for (String line; (line = r.readLine()) != null; )
468 36e2cbdd Leszek Koltunski
        {
469 1d643a0e Leszek Koltunski
        total.append(line).append('\n');
470 36e2cbdd Leszek Koltunski
        }
471 1d643a0e Leszek Koltunski
472
      mScores = total.toString();
473 36e2cbdd Leszek Koltunski
      }
474 cc5ec229 Leszek Koltunski
    catch( final UnknownHostException e )
475
      {
476 dd016102 Leszek Koltunski
      if( mReceiver!=null ) mReceiver.message("No access to Internet");
477 cc5ec229 Leszek Koltunski
      return false;
478
      }
479
    catch( final SecurityException e )
480
      {
481 dd016102 Leszek Koltunski
      if( mReceiver!=null ) mReceiver.message("Application not authorized to connect to the Internet");
482 cc5ec229 Leszek Koltunski
      return false;
483
      }
484
    catch( final Exception e )
485 36e2cbdd Leszek Koltunski
      {
486 dd016102 Leszek Koltunski
      if( mReceiver!=null ) mReceiver.message(e.getMessage());
487 a675474f Leszek Koltunski
      return false;
488 36e2cbdd Leszek Koltunski
      }
489
490 329c0aeb Leszek Koltunski
    if( mScores.length()==0 )
491
      {
492 dd016102 Leszek Koltunski
      if( mReceiver!=null ) mReceiver.message("Failed to download scores");
493 329c0aeb Leszek Koltunski
      return false;
494
      }
495
496 a675474f Leszek Koltunski
    return true;
497 b8b38548 Leszek Koltunski
    }
498 d8aa4ba8 Leszek Koltunski
499 1fa125c2 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
500
501
  private String constructSuspiciousURL()
502
    {
503
    RubikScores scores = RubikScores.getInstance();
504
    int deviceID= scores.getDeviceID();
505 63dd19c4 Leszek Koltunski
    String suspicious = URLencode(mSuspicious);
506 1fa125c2 Leszek Koltunski
507
    String url="https://distorted.org/magic/cgi-bin/suspicious.cgi";
508 63dd19c4 Leszek Koltunski
    url += "?i="+deviceID+"&d="+suspicious;
509 1fa125c2 Leszek Koltunski
510
    return url;
511
    }
512
513 6a083c6a Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
514
515
  private String constructDebugURL()
516
    {
517
    RubikScores scores = RubikScores.getInstance();
518
    String name = URLencode(scores.getName());
519
    int numRuns = scores.getNumRuns();
520
    int numPlay = scores.getNumPlays();
521
    String country = scores.getCountry();
522
    String renderer = DistortedLibrary.getDriverRenderer();
523
    String version  = DistortedLibrary.getDriverVersion();
524 fcf7320f Leszek Koltunski
    int objectAPI   = JsonWriter.VERSION_OBJECT_MAJOR;
525
    int tutorialAPI = JsonWriter.VERSION_EXTRAS_MAJOR;
526 6a083c6a Leszek Koltunski
527
    renderer = URLencode(renderer);
528
    version  = URLencode(version);
529
530 fcf7320f Leszek Koltunski
    String url="https://distorted.org/magic/cgi-bin/debugs-new.cgi";
531
    url += "?n="+name+"&r="+numRuns+"&p="+numPlay+"&c="+country+"&e="+mVersion+"d";
532
    url += "&d="+renderer+"&v="+version+"&a="+objectAPI+"&b="+tutorialAPI;
533 6a083c6a Leszek Koltunski
534
    return url;
535
    }
536
537 17f9a695 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
538
539
  private String constructDownloadURL()
540
    {
541
    RubikScores scores = RubikScores.getInstance();
542
    String name = URLencode(scores.getName());
543
    int numRuns = scores.getNumRuns();
544
    int numPlay = scores.getNumPlays();
545 874c37b1 Leszek Koltunski
    String country = scores.getCountry();
546 17f9a695 Leszek Koltunski
547
    String url="https://distorted.org/magic/cgi-bin/download.cgi";
548 11d68e9c Leszek Koltunski
    url += "?n="+name+"&r="+numRuns+"&p="+numPlay+"&c="+country+"&e="+mVersion;
549 17f9a695 Leszek Koltunski
550
    return url;
551
    }
552
553
///////////////////////////////////////////////////////////////////////////////////////////////////
554
555
  private String constructSubmitURL()
556
    {
557
    RubikScores scores = RubikScores.getInstance();
558
    String name = URLencode(scores.getName());
559 11d68e9c Leszek Koltunski
    String veri = scores.isVerified() ? "1" : "";
560 17f9a695 Leszek Koltunski
    int numRuns = scores.getNumRuns();
561
    int numPlay = scores.getNumPlays();
562
    int deviceID= scores.getDeviceID();
563 6570171b Leszek Koltunski
    String reclist = scores.getRecordList("&o=","&l=","&t=");
564 17f9a695 Leszek Koltunski
    String country = scores.getCountry();
565 86cbdab1 Leszek Koltunski
    long epoch = System.currentTimeMillis();
566 9e171f43 Leszek Koltunski
    String salt = "cuboid";
567 17f9a695 Leszek Koltunski
568 9d4c38eb Leszek Koltunski
    String renderer = DistortedLibrary.getDriverRenderer();
569
    String version  = DistortedLibrary.getDriverVersion();
570
571
    int type = getRendererType(renderer);
572
    renderer = parseRenderer(type,renderer);
573
    version  = parseVersion(type,version);
574
575 86cbdab1 Leszek Koltunski
    String url1="https://distorted.org/magic/cgi-bin/submit.cgi";
576 11d68e9c Leszek Koltunski
    String url2 = "n="+name+"&v="+veri+"&r="+numRuns+"&p="+numPlay+"&i="+deviceID+"&e="+mVersion;
577
    url2 += "&d="+renderer+"&s="+version+reclist+"&c="+country+"&f="+epoch;
578 9e171f43 Leszek Koltunski
    String hash = computeHash( url2, salt.getBytes() );
579 17f9a695 Leszek Koltunski
580 b3ee0e78 Leszek Koltunski
    return url1 + "?" + url2 + "&h=" + hash;
581 17f9a695 Leszek Koltunski
    }
582
583 d8aa4ba8 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
584
585
  private boolean gottaDownload()
586 b8b38548 Leszek Koltunski
    {
587 d8aa4ba8 Leszek Koltunski
    return ((mScores.length()==0) && !mRunning);
588 f3e12931 Leszek Koltunski
    }
589 b8b38548 Leszek Koltunski
590 d8aa4ba8 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
591
592 4f9f99a2 Leszek Koltunski
  @Override
593 d8aa4ba8 Leszek Koltunski
  public void run()
594
    {
595 6a083c6a Leszek Koltunski
    boolean receiveValues=true;
596 a675474f Leszek Koltunski
597 a36b9dca Leszek Koltunski
    initializeStatics();
598
599 17f9a695 Leszek Koltunski
    try
600 d8aa4ba8 Leszek Koltunski
      {
601 17f9a695 Leszek Koltunski
      if( mMode==DOWNLOAD && gottaDownload() )
602 d8aa4ba8 Leszek Koltunski
        {
603 17f9a695 Leszek Koltunski
        mRunning = true;
604 6a083c6a Leszek Koltunski
        receiveValues = network(constructDownloadURL());
605 d8aa4ba8 Leszek Koltunski
        }
606 17f9a695 Leszek Koltunski
      if( mMode==SUBMIT )
607 4895fff6 Leszek Koltunski
        {
608 17f9a695 Leszek Koltunski
        mRunning = true;
609 1fa125c2 Leszek Koltunski
        RubikScores scores = RubikScores.getInstance();
610 4895fff6 Leszek Koltunski
611 1fa125c2 Leszek Koltunski
        if( scores.thereAreUnsubmittedRecords() )
612 17f9a695 Leszek Koltunski
          {
613 6a083c6a Leszek Koltunski
          receiveValues = network(constructSubmitURL());
614 17f9a695 Leszek Koltunski
          }
615
        }
616 6a083c6a Leszek Koltunski
      if( mMode==DEBUG )
617
        {
618
        sendDebug();
619
        receiveValues = false;
620
        mRunning = false;
621
        }
622 1fa125c2 Leszek Koltunski
      if( mMode==SUSPICIOUS )
623
        {
624
        sendSuspicious();
625
        receiveValues = false;
626
        mRunning = false;
627
        }
628 d8aa4ba8 Leszek Koltunski
      }
629 17f9a695 Leszek Koltunski
    catch( Exception e )
630 d8aa4ba8 Leszek Koltunski
      {
631 6a083c6a Leszek Koltunski
      if( mReceiver!=null ) mReceiver.message("Exception downloading records: "+e.getMessage() );
632 4895fff6 Leszek Koltunski
      }
633 286d73ae Leszek Koltunski
634 17f9a695 Leszek Koltunski
    if( mRunning )
635
      {
636 fcf7320f Leszek Koltunski
      receiveValues = fillValuesNormal();
637 17f9a695 Leszek Koltunski
      mRunning = false;
638
      }
639 a675474f Leszek Koltunski
640 6a083c6a Leszek Koltunski
    if( receiveValues )
641 a675474f Leszek Koltunski
      {
642 6a083c6a Leszek Koltunski
      if( mReceiver!=null ) mReceiver.receive(mCountry, mName, mTime);
643 17f9a695 Leszek Koltunski
644
      if( mMode==SUBMIT )
645
        {
646
        RubikScores.getInstance().successfulSubmit();
647
        }
648 a675474f Leszek Koltunski
      }
649 d8aa4ba8 Leszek Koltunski
    }
650 4f9f99a2 Leszek Koltunski
651 bc511ea5 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
652
653 6a083c6a Leszek Koltunski
  private RubikNetwork()
654 bc511ea5 Leszek Koltunski
    {
655
656
    }
657
658 4f9f99a2 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
659
// PUBLIC API
660
///////////////////////////////////////////////////////////////////////////////////////////////////
661
662
  public static void onPause()
663
    {
664
    mRunning = false;
665
    }
666
667 bc511ea5 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
668
669 6a083c6a Leszek Koltunski
  public static RubikNetwork getInstance()
670 bc511ea5 Leszek Koltunski
    {
671
    if( mThis==null )
672
      {
673 6a083c6a Leszek Koltunski
      mThis = new RubikNetwork();
674 bc511ea5 Leszek Koltunski
      }
675
676
    return mThis;
677
    }
678
679 4f9f99a2 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
680
681 6a083c6a Leszek Koltunski
  private void start(Receiver receiver, Activity act, int mode)
682 4f9f99a2 Leszek Koltunski
    {
683
    mReceiver = receiver;
684 1780dcb0 Leszek Koltunski
    mMode     = mode;
685
686
    try
687
      {
688
      PackageInfo pInfo = act.getPackageManager().getPackageInfo( act.getPackageName(), 0);
689
      mVersion = pInfo.versionName;
690
      }
691
    catch (PackageManager.NameNotFoundException e)
692
      {
693 6570171b Leszek Koltunski
      mVersion = "0.9.2";
694 1780dcb0 Leszek Koltunski
      }
695 6f8e5dfc Leszek Koltunski
696 4f9f99a2 Leszek Koltunski
    Thread networkThrd = new Thread(this);
697
    networkThrd.start();
698
    }
699 bc511ea5 Leszek Koltunski
700
///////////////////////////////////////////////////////////////////////////////////////////////////
701
702 1780dcb0 Leszek Koltunski
  public void download(Receiver receiver, FragmentActivity act)
703 bc511ea5 Leszek Koltunski
    {
704 1780dcb0 Leszek Koltunski
    start(receiver, act, DOWNLOAD);
705
    }
706 bc511ea5 Leszek Koltunski
707 1780dcb0 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
708
709
  public void submit(Receiver receiver, FragmentActivity act)
710
    {
711
    start(receiver, act, SUBMIT);
712 bc511ea5 Leszek Koltunski
    }
713 6a083c6a Leszek Koltunski
714
///////////////////////////////////////////////////////////////////////////////////////////////////
715
716
  public void debug(AppCompatActivity act)
717
    {
718 63dd19c4 Leszek Koltunski
    mDebugState = DEBUG_RUNNING;
719 6a083c6a Leszek Koltunski
    start(null, act, DEBUG);
720
    }
721 1fa125c2 Leszek Koltunski
722
///////////////////////////////////////////////////////////////////////////////////////////////////
723
724 63dd19c4 Leszek Koltunski
  public void suspicious(AppCompatActivity act, String suspicious)
725 1fa125c2 Leszek Koltunski
    {
726 63dd19c4 Leszek Koltunski
    mSuspicious = suspicious;
727 1fa125c2 Leszek Koltunski
    start(null, act, SUSPICIOUS);
728
    }
729 63dd19c4 Leszek Koltunski
730
///////////////////////////////////////////////////////////////////////////////////////////////////
731
// Yes it can happen that the second Updatee registers before we sent an update to the first one
732
// and, as a result, the update never gets sent to the first one. This is not a problem (now, when
733
// there are only two updatees - the RubikStatePlay and the UpdateDialog)
734
//
735
// Yes, there is also a remote possibility that the two threads executing this function and executing
736
// the sendDebug() get swapped exactly in unlucky moment and the update never gets to the updatee.
737
// We don't care about such remote possibility, then the app simply would signal that there are no
738
// updates available.
739
740
  public void signUpForUpdates(Updatee updatee)
741
    {
742
         if( mDebugState==DEBUG_SUCCESS ) updatee.receiveUpdate(mUpdates);
743
    else if( mDebugState==DEBUG_FAILURE ) updatee.errorUpdate();
744
    else mUpdatee = updatee;
745
    }
746 b8b38548 Leszek Koltunski
}