Project

General

Profile

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

magiccube / src / main / java / org / distorted / network / RubikNetwork.java @ ffe7e55d

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