Project

General

Profile

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

magiccube / src / main / java / org / distorted / network / RubikNetwork.java @ 46be3ddf

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