Esempio n. 1
0
  /**
   * Check if the user has been logged in when he retrieved the data.
   *
   * @param page
   * @return <code>true</code> if user is logged in, <code>false</code> otherwise
   */
  public static boolean getLoginStatus(final String page) {
    if (StringUtils.isBlank(page)) {
      Log.e("Login.checkLogin: No page given");
      return false;
    }

    setActualStatus(cgeoapplication.getInstance().getString(R.string.init_login_popup_ok));

    // on every page except login page
    setActualLoginStatus(BaseUtils.matches(page, GCConstants.PATTERN_LOGIN_NAME));
    if (isActualLoginStatus()) {
      setActualUserName(BaseUtils.getMatch(page, GCConstants.PATTERN_LOGIN_NAME, true, "???"));
      setActualCachesFound(
          Integer.parseInt(
              BaseUtils.getMatch(page, GCConstants.PATTERN_CACHES_FOUND, true, "0")
                  .replaceAll("[,.]", "")));
      Settings.setMemberStatus(
          BaseUtils.getMatch(page, GCConstants.PATTERN_MEMBER_STATUS, true, null));
      if (page.contains(GCConstants.MEMBER_STATUS_RENEW)) {
        Settings.setMemberStatus(GCConstants.MEMBER_STATUS_PM);
      }
      return true;
    }

    // login page
    setActualLoginStatus(BaseUtils.matches(page, GCConstants.PATTERN_LOGIN_NAME_LOGIN_PAGE));
    if (isActualLoginStatus()) {
      setActualUserName(Settings.getUsername());
      // number of caches found is not part of this page
      return true;
    }

    setActualStatus(cgeoapplication.getInstance().getString(R.string.init_login_popup_failed));
    return false;
  }
Esempio n. 2
0
  public static BitmapDrawable downloadAvatarAndGetMemberStatus() {
    try {
      final String profile =
          BaseUtils.replaceWhitespace(
              Network.getResponseData(Network.getRequest("http://www.geocaching.com/my/")));

      Settings.setMemberStatus(
          BaseUtils.getMatch(profile, GCConstants.PATTERN_MEMBER_STATUS, true, null));
      if (profile.contains(GCConstants.MEMBER_STATUS_RENEW)) {
        Settings.setMemberStatus(GCConstants.MEMBER_STATUS_PM);
      }

      setActualCachesFound(
          Integer.parseInt(
              BaseUtils.getMatch(profile, GCConstants.PATTERN_CACHES_FOUND, true, "-1")
                  .replaceAll("[,.]", "")));

      final String avatarURL =
          BaseUtils.getMatch(profile, GCConstants.PATTERN_AVATAR_IMAGE_PROFILE_PAGE, false, null);
      if (null != avatarURL) {
        final HtmlImage imgGetter = new HtmlImage("", false, 0, false);
        return imgGetter.getDrawable(avatarURL);
      }
      // No match? There may be no avatar set by user.
      Log.d("No avatar set for user");
    } catch (Exception e) {
      Log.w("Error when retrieving user avatar", e);
    }
    return null;
  }
Esempio n. 3
0
    public ExportOptionsDialog(final List<cgCache> caches, final Activity activity) {
      super(activity);

      View layout = activity.getLayoutInflater().inflate(R.layout.gpx_export_dialog, null);
      setView(layout);

      final TextView text = (TextView) layout.findViewById(R.id.info);
      text.setText(getString(R.string.export_gpx_info, Settings.getGpxExportDir()));

      final CheckBox shareOption = (CheckBox) layout.findViewById(R.id.share);

      shareOption.setChecked(Settings.getShareAfterExport());

      shareOption.setOnClickListener(
          new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              Settings.setShareAfterExport(shareOption.isChecked());
            }
          });

      layout
          .findViewById(R.id.export)
          .setOnClickListener(
              new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                  dismiss();
                  new ExportTask(caches, activity).execute((Void) null);
                }
              });
    }
 @Override
 protected void tearDown() throws Exception {
   cgeoapplication.getInstance().dropList(listId);
   cgeoapplication.getInstance().removeList(listId);
   deleteDirectory(tempDir);
   Settings.setStoreOfflineMaps(importCacheStaticMaps);
   Settings.setStoreOfflineWpMaps(importWpStaticMaps);
   super.tearDown();
 }
Esempio n. 5
0
 @Override
 public OAuthLevel getSupportedAuthLevel() {
   // TODO the tokens must be available connector specific
   if (StringUtils.isNotBlank(Settings.getOCDETokenPublic())
       && StringUtils.isNotBlank(Settings.getOCDETokenSecret())) {
     return OAuthLevel.Level3;
   }
   return OAuthLevel.Level1;
 }
Esempio n. 6
0
 /*
  * (non-Javadoc)
  *
  * @see cgeo.geocaching.test.mock.MockedCache#isOwn()
  */
 @Override
 public boolean isOwn() {
   if ("Tom03".equals(Settings.getUsername())) {
     return true;
   }
   return super.isOwn();
 }
  public FilterUserInterface(final IAbstractActivity activity) {
    this.activity = activity;
    this.res = cgeoapplication.getInstance().getResources();

    registry = new ArrayList<FactoryEntry>();
    if (Settings.getCacheType() == CacheType.ALL) {
      register(R.string.caches_filter_type, TypeFilter.Factory.class);
    }
    register(R.string.caches_filter_size, SizeFilter.Factory.class);
    register(R.string.cache_terrain, TerrainFilter.Factory.class);
    register(R.string.cache_difficulty, DifficultyFilter.Factory.class);
    register(R.string.cache_attributes, AttributeFilter.Factory.class);
    register(R.string.cache_status, StateFilter.Factory.class);
    register(R.string.caches_filter_track, TrackablesFilter.class);
    register(R.string.caches_filter_modified, ModifiedFilter.class);

    // sort by localized names
    Collections.sort(
        registry,
        new Comparator<FactoryEntry>() {

          @Override
          public int compare(FactoryEntry lhs, FactoryEntry rhs) {
            return lhs.name.compareToIgnoreCase(rhs.name);
          }
        });

    // reset shall be last
    register(R.string.caches_filter_clear, null);
  }
Esempio n. 8
0
  private static String getDistance(Geopoint position, Geopoint target) {
    final float kilometers = position.distanceTo(target);

    if (Settings.isUseMetricUnits()) {
      return getDistance(
          kilometers,
          (int) (kilometers * 1000.0),
          5.0f,
          1.0f,
          50,
          R.plurals.tts_kilometers,
          R.string.tts_one_kilometer,
          R.plurals.tts_meters,
          R.string.tts_one_meter);
    }
    return getDistance(
        kilometers / IConversion.MILES_TO_KILOMETER,
        (int) (kilometers * 1000.0 * IConversion.METERS_TO_FEET),
        3.0f,
        0.2f,
        300,
        R.plurals.tts_miles,
        R.string.tts_one_mile,
        R.plurals.tts_feet,
        R.string.tts_one_foot);
  }
  @Override
  protected void setUp() throws Exception {
    super.setUp();

    tempDir = new File(System.getProperty("java.io.tmpdir"), "cgeogpxesTest");
    tempDir.mkdir();

    // workaround to get storage initialized
    cgeoapplication.getInstance().getAllHistoricCachesCount();
    listId = cgeoapplication.getInstance().createList("cgeogpxesTest");

    importCacheStaticMaps = Settings.isStoreOfflineMaps();
    Settings.setStoreOfflineMaps(true);
    importWpStaticMaps = Settings.isStoreOfflineWpMaps();
    Settings.setStoreOfflineWpMaps(true);
  }
Esempio n. 10
0
 @Override
 protected void onPostExecute(Boolean result) {
   if (null != activity) {
     progress.dismiss();
     if (result) {
       ActivityMixin.showToast(
           activity,
           getName()
               + ' '
               + getString(R.string.export_exportedto)
               + ": "
               + exportFile.toString());
       if (Settings.getShareAfterExport()) {
         Intent shareIntent = new Intent();
         shareIntent.setAction(Intent.ACTION_SEND);
         shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(exportFile));
         shareIntent.setType("application/xml");
         activity.startActivity(
             Intent.createChooser(shareIntent, getString(R.string.export_gpx_to)));
       }
     } else {
       ActivityMixin.showToast(activity, getString(R.string.export_failed));
     }
   }
 }
  @Override
  public void setMapSource() {

    switch (MapsforgeMapProvider.getMapsforgeSource(Settings.getMapSource())) {
      case MapsforgeMapProvider.CYCLEMAP:
        setMapViewMode(MapViewMode.OPENCYCLEMAP_TILE_DOWNLOAD);
        break;
      case MapsforgeMapProvider.OFFLINE:
        if (MapDatabase.isValidMapFile(Settings.getMapFile())) {
          setMapViewMode(MapViewMode.CANVAS_RENDERER);
          super.setMapFile(Settings.getMapFile());
        } else {
          setMapViewMode(MapViewMode.MAPNIK_TILE_DOWNLOAD);
        }
        break;
      default:
        setMapViewMode(MapViewMode.MAPNIK_TILE_DOWNLOAD);
    }
  }
Esempio n. 12
0
 // Make method non-static so that Settings is initialized
 @SuppressWarnings("static-method")
 public void testSpeed() {
   assertEquals("?", Units.getDistanceFromKilometers(null));
   final boolean savedMetrics = Settings.isUseMetricUnits();
   try {
     Settings.setUseMetricUnits(true);
     assertSpeed("123 km/h", 122.782f);
     assertSpeed("123 km/h", 123.456f);
     assertSpeed("12.3 km/h", 12.3456f);
     assertSpeed("1.23 km/h", 1.23456f);
     assertSpeed("123 m/h", 0.123456f);
     Settings.setUseMetricUnits(false);
     assertSpeed("76.7 mph", 123.456f);
     assertSpeed("7.67 mph", 12.3456f);
     assertSpeed("0.77 mph", 1.23456f);
   } finally {
     Settings.setUseMetricUnits(savedMetrics);
   }
 }
Esempio n. 13
0
 private static void assertDistance(final String expected, final float distance) {
   final String actual = Units.getDistanceFromKilometers(distance);
   if (!StringUtils.equals(expected, actual.replace(',', '.'))) { // make 1.2 the same as 1,2
     fail(
         "getHumanDistance("
             + distance
             + ") [metric: "
             + (Settings.isUseMetricUnits() ? "yes" : "no")
             + "] fails to match "
             + expected
             + ": "
             + actual);
   }
 }
Esempio n. 14
0
  public static StatusCode logout() {
    HttpResponse logoutResponse =
        Network.getRequest(
            "https://www.geocaching.com/login/default.aspx?RESET=Y&redir=http%3a%2f%2fwww.geocaching.com%2fdefault.aspx%3f");
    String logoutData = Network.getResponseData(logoutResponse);
    if (logoutResponse != null
        && logoutResponse.getStatusLine().getStatusCode() == 503
        && BaseUtils.matches(logoutData, GCConstants.PATTERN_MAINTENANCE)) {
      return StatusCode.MAINTENANCE;
    }

    Cookies.clearCookies();
    Settings.setCookieStore(null);
    return StatusCode.NO_ERROR;
  }
Esempio n. 15
0
 // Make method non-static so that Settings is initialized
 @SuppressWarnings("static-method")
 public void testElevation() {
   final boolean savedMetrics = Settings.isUseMetricUnits();
   try {
     Settings.setUseMetricUnits(true);
     assertElevation("↥ 123 m", 122.782f);
     assertElevation("↥ 123 m", 123.456f);
     assertElevation("↥ 12 m", 12.3456f);
     assertElevation("↥ 1 m", 1.23456f);
     assertElevation("↥ 2 m", 1.6f);
     assertElevation("↥ 0 m", 0.123456f);
     assertElevation("↧ 123 m", -122.782f);
     assertElevation("↧ 123 m", -123.456f);
     assertElevation("↧ 12 m", -12.3456f);
     assertElevation("↧ 1 m", -1.23456f);
     assertElevation("↧ 2 m", -1.6f);
     assertElevation("↧ 0 m", -0.123456f);
     Settings.setUseMetricUnits(false);
     assertElevation("↥ 405 ft", 123.456f);
     assertElevation("↥ 41 ft", 12.3456f);
   } finally {
     Settings.setUseMetricUnits(savedMetrics);
   }
 }
Esempio n. 16
0
  /** Detect user date settings on geocaching.com */
  public static void detectGcCustomDate() {

    final String result =
        Network.getResponseData(
            Network.getRequest("http://www.geocaching.com/account/ManagePreferences.aspx"));

    if (null == result) {
      Log.w("Login.detectGcCustomDate: result is null");
      return;
    }

    String customDate = BaseUtils.getMatch(result, GCConstants.PATTERN_CUSTOMDATE, true, null);
    if (null != customDate) {
      Settings.setGcCustomDate(customDate);
    }
  }
Esempio n. 17
0
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
      // Ignore first call, which comes from onCreate()
      if (currentFormat != null) {

        // Start new format with an acceptable value: either the current one
        // entered by the user, else our current coordinates, else (0,0).
        if (!calc(false)) {
          if (geo != null && geo.getCoords() != null) {
            gp = geo.getCoords();
          } else {
            gp = new Geopoint(0.0, 0.0);
          }
        }
      }

      currentFormat = coordInputFormatEnum.fromInt(pos);
      Settings.setCoordInputFormat(currentFormat);
      updateGUI();
    }
Esempio n. 18
0
    @Override
    protected Boolean doInBackground(Void... params) {
      // quick check for being able to write the GPX file
      if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        return false;
      }

      try {
        final File exportLocation = new File(Settings.getGpxExportDir());
        exportLocation.mkdirs();

        final SimpleDateFormat fileNameDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        exportFile =
            new File(
                Settings.getGpxExportDir()
                    + File.separatorChar
                    + "export_"
                    + fileNameDateFormat.format(new Date())
                    + ".gpx");

        gpx = new BufferedWriter(new FileWriter(exportFile));

        gpx.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        gpx.write(
            "<gpx version=\"1.0\" creator=\"c:geo - http://www.cgeo.org\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://www.topografix.com/GPX/1/0\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.groundspeak.com/cache/1/0/1 http://www.groundspeak.com/cache/1/0/1/cache.xsd\">");

        for (int i = 0; i < caches.size(); i++) {
          // reload the cache. otherwise logs, attributes and other detailed information is not
          // available
          final cgCache cache =
              cgeoapplication
                  .getInstance()
                  .loadCache(caches.get(i).getGeocode(), LoadFlags.LOAD_ALL_DB_ONLY);

          gpx.write("<wpt ");
          gpx.write("lat=\"");
          gpx.write(Double.toString(cache.getCoords().getLatitude()));
          gpx.write("\" ");
          gpx.write("lon=\"");
          gpx.write(Double.toString(cache.getCoords().getLongitude()));
          gpx.write("\">");

          final Date hiddenDate = cache.getHiddenDate();
          if (hiddenDate != null) {
            gpx.write("<time>");
            gpx.write(StringEscapeUtils.escapeXml(dateFormatZ.format(hiddenDate)));
            gpx.write("</time>");
          }

          gpx.write("<name>");
          gpx.write(StringEscapeUtils.escapeXml(cache.getGeocode()));
          gpx.write("</name>");

          gpx.write("<desc>");
          gpx.write(StringEscapeUtils.escapeXml(cache.getName()));
          gpx.write("</desc>");

          gpx.write("<url>");
          gpx.write(cache.getUrl());
          gpx.write("</url>");

          gpx.write("<urlname>");
          gpx.write(StringEscapeUtils.escapeXml(cache.getName()));
          gpx.write("</urlname>");

          gpx.write("<sym>");
          gpx.write(cache.isFound() ? "Geocache Found" : "Geocache");
          gpx.write("</sym>");

          gpx.write("<type>");
          gpx.write(StringEscapeUtils.escapeXml("Geocache|" + cache.getType().pattern));
          gpx.write("</type>");

          gpx.write("<groundspeak:cache ");
          gpx.write("id=\"");
          gpx.write(cache.getCacheId());
          gpx.write("\" available=\"");
          gpx.write(!cache.isDisabled() ? "True" : "False");
          gpx.write("\" archived=\"");
          gpx.write(cache.isArchived() ? "True" : "False");
          gpx.write("\" ");
          gpx.write("xmlns:groundspeak=\"http://www.groundspeak.com/cache/1/0/1\">");

          gpx.write("<groundspeak:name>");
          gpx.write(StringEscapeUtils.escapeXml(cache.getName()));
          gpx.write("</groundspeak:name>");

          gpx.write("<groundspeak:placed_by>");
          gpx.write(StringEscapeUtils.escapeXml(cache.getOwnerDisplayName()));
          gpx.write("</groundspeak:placed_by>");

          gpx.write("<groundspeak:owner>");
          gpx.write(StringEscapeUtils.escapeXml(cache.getOwnerUserId()));
          gpx.write("</groundspeak:owner>");

          gpx.write("<groundspeak:type>");
          gpx.write(StringEscapeUtils.escapeXml(cache.getType().pattern));
          gpx.write("</groundspeak:type>");

          gpx.write("<groundspeak:container>");
          gpx.write(StringEscapeUtils.escapeXml(cache.getSize().id));
          gpx.write("</groundspeak:container>");

          writeAttributes(cache);

          gpx.write("<groundspeak:difficulty>");
          gpx.write(Float.toString(cache.getDifficulty()));
          gpx.write("</groundspeak:difficulty>");

          gpx.write("<groundspeak:terrain>");
          gpx.write(Float.toString(cache.getTerrain()));
          gpx.write("</groundspeak:terrain>");

          gpx.write("<groundspeak:country>");
          gpx.write(StringEscapeUtils.escapeXml(cache.getLocation()));
          gpx.write("</groundspeak:country>");

          gpx.write(
              "<groundspeak:state></groundspeak:state>"); // c:geo cannot manage 2 separate fields,
                                                          // so we export as country

          gpx.write("<groundspeak:short_description html=\"");
          gpx.write(BaseUtils.containsHtml(cache.getShortDescription()) ? "True" : "False");
          gpx.write("\">");
          gpx.write(StringEscapeUtils.escapeXml(cache.getShortDescription()));
          gpx.write("</groundspeak:short_description>");

          gpx.write("<groundspeak:long_description html=\"");
          gpx.write(BaseUtils.containsHtml(cache.getDescription()) ? "True" : "False");
          gpx.write("\">");
          gpx.write(StringEscapeUtils.escapeXml(cache.getDescription()));
          gpx.write("</groundspeak:long_description>");

          gpx.write("<groundspeak:encoded_hints>");
          gpx.write(StringEscapeUtils.escapeXml(cache.getHint()));
          gpx.write("</groundspeak:encoded_hints>");

          writeLogs(cache);

          gpx.write("</groundspeak:cache>");

          gpx.write("</wpt>");

          writeWaypoints(cache);

          publishProgress(i + 1);
        }

        gpx.write("</gpx>");

        gpx.close();
      } catch (Exception e) {
        Log.e("GpxExport.ExportTask export", e);

        if (gpx != null) {
          try {
            gpx.close();
          } catch (IOException ee) {
          }
        }

        // delete partial gpx file on error
        if (exportFile.exists()) {
          exportFile.delete();
        }

        return false;
      }

      return true;
    }
Esempio n. 19
0
 @Override
 public boolean isActivated() {
   return Settings.isOCConnectorActive();
 }
Esempio n. 20
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    try {
      requestWindowFeature(Window.FEATURE_NO_TITLE);
      getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    } catch (Exception e) {
      // nothing
    }

    setContentView(R.layout.coordinatesinput_dialog);

    final Spinner spinner = (Spinner) findViewById(R.id.spinnerCoordinateFormats);
    final ArrayAdapter<CharSequence> adapter =
        ArrayAdapter.createFromResource(
            context, R.array.waypoint_coordinate_formats, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setSelection(Settings.getCoordInputFormat().ordinal());
    spinner.setOnItemSelectedListener(new CoordinateFormatListener());

    bLat = (Button) findViewById(R.id.ButtonLat);
    eLat = (EditText) findViewById(R.id.latitude);
    eLatDeg = (EditText) findViewById(R.id.EditTextLatDeg);
    eLatMin = (EditText) findViewById(R.id.EditTextLatMin);
    eLatSec = (EditText) findViewById(R.id.EditTextLatSec);
    eLatSub = (EditText) findViewById(R.id.EditTextLatSecFrac);
    tLatSep1 = (TextView) findViewById(R.id.LatSeparator1);
    tLatSep2 = (TextView) findViewById(R.id.LatSeparator2);
    tLatSep3 = (TextView) findViewById(R.id.LatSeparator3);

    bLon = (Button) findViewById(R.id.ButtonLon);
    eLon = (EditText) findViewById(R.id.longitude);
    eLonDeg = (EditText) findViewById(R.id.EditTextLonDeg);
    eLonMin = (EditText) findViewById(R.id.EditTextLonMin);
    eLonSec = (EditText) findViewById(R.id.EditTextLonSec);
    eLonSub = (EditText) findViewById(R.id.EditTextLonSecFrac);
    tLonSep1 = (TextView) findViewById(R.id.LonSeparator1);
    tLonSep2 = (TextView) findViewById(R.id.LonSeparator2);
    tLonSep3 = (TextView) findViewById(R.id.LonSeparator3);

    eLatDeg.addTextChangedListener(new TextChanged(eLatDeg));
    eLatMin.addTextChangedListener(new TextChanged(eLatMin));
    eLatSec.addTextChangedListener(new TextChanged(eLatSec));
    eLatSub.addTextChangedListener(new TextChanged(eLatSub));
    eLonDeg.addTextChangedListener(new TextChanged(eLonDeg));
    eLonMin.addTextChangedListener(new TextChanged(eLonMin));
    eLonSec.addTextChangedListener(new TextChanged(eLonSec));
    eLonSub.addTextChangedListener(new TextChanged(eLonSub));

    Compatibility.disableSuggestions(eLatDeg);
    Compatibility.disableSuggestions(eLatMin);
    Compatibility.disableSuggestions(eLatSec);
    Compatibility.disableSuggestions(eLatSub);
    Compatibility.disableSuggestions(eLonDeg);
    Compatibility.disableSuggestions(eLonMin);
    Compatibility.disableSuggestions(eLonSec);
    Compatibility.disableSuggestions(eLonSub);

    bLat.setOnClickListener(new ButtonClickListener());
    bLon.setOnClickListener(new ButtonClickListener());

    final Button buttonCurrent = (Button) findViewById(R.id.current);
    buttonCurrent.setOnClickListener(new CurrentListener());
    final Button buttonCache = (Button) findViewById(R.id.cache);
    if (cache != null) {
      buttonCache.setOnClickListener(new CacheListener());
    } else {
      buttonCache.setVisibility(View.GONE);
    }
    final Button buttonDone = (Button) findViewById(R.id.done);
    buttonDone.setOnClickListener(new InputDoneListener());
  }
Esempio n. 21
0
  private static StatusCode login(boolean retry) {
    final ImmutablePair<String, String> login = Settings.getLogin();

    if (login == null || StringUtils.isEmpty(login.left) || StringUtils.isEmpty(login.right)) {
      Login.setActualStatus(cgeoapplication.getInstance().getString(R.string.err_login));
      Log.e("Login.login: No login information stored");
      return StatusCode.NO_LOGIN_INFO_STORED;
    }

    Login.setActualStatus(
        cgeoapplication.getInstance().getString(R.string.init_login_popup_working));
    HttpResponse loginResponse =
        Network.getRequest("https://www.geocaching.com/login/default.aspx");
    String loginData = Network.getResponseData(loginResponse);
    if (loginResponse != null
        && loginResponse.getStatusLine().getStatusCode() == 503
        && BaseUtils.matches(loginData, GCConstants.PATTERN_MAINTENANCE)) {
      return StatusCode.MAINTENANCE;
    }

    if (StringUtils.isBlank(loginData)) {
      Log.e("Login.login: Failed to retrieve login page (1st)");
      return StatusCode.CONNECTION_FAILED; // no loginpage
    }

    if (Login.getLoginStatus(loginData)) {
      Log.i(
          "Already logged in Geocaching.com as "
              + login.left
              + " ("
              + Settings.getMemberStatus()
              + ')');
      Login.switchToEnglish(loginData);
      return StatusCode.NO_ERROR; // logged in
    }

    Cookies.clearCookies();
    Settings.setCookieStore(null);

    final Parameters params =
        new Parameters(
            "__EVENTTARGET", "",
            "__EVENTARGUMENT", "",
            "ctl00$ContentBody$tbUsername", login.left,
            "ctl00$ContentBody$tbPassword", login.right,
            "ctl00$ContentBody$cbRememberMe", "on",
            "ctl00$ContentBody$btnSignIn", "Login");
    final String[] viewstates = Login.getViewstates(loginData);
    if (isEmpty(viewstates)) {
      Log.e("Login.login: Failed to find viewstates");
      return StatusCode.LOGIN_PARSE_ERROR; // no viewstates
    }
    Login.putViewstates(params, viewstates);

    loginResponse = Network.postRequest("https://www.geocaching.com/login/default.aspx", params);
    loginData = Network.getResponseData(loginResponse);

    if (StringUtils.isBlank(loginData)) {
      Log.e("Login.login: Failed to retrieve login page (2nd)");
      // FIXME: should it be CONNECTION_FAILED to match the first attempt?
      return StatusCode.COMMUNICATION_ERROR; // no login page
    }

    if (Login.getLoginStatus(loginData)) {
      Log.i(
          "Successfully logged in Geocaching.com as "
              + login.left
              + " ("
              + Settings.getMemberStatus()
              + ')');

      Login.switchToEnglish(loginData);
      Settings.setCookieStore(Cookies.dumpCookieStore());

      return StatusCode.NO_ERROR; // logged in
    }

    if (loginData.contains("Your username/password combination does not match.")) {
      Log.i(
          "Failed to log in Geocaching.com as "
              + login.left
              + " because of wrong username/password");
      return StatusCode.WRONG_LOGIN_DATA; // wrong login
    }

    Log.i("Failed to log in Geocaching.com as " + login.left + " for some unknown reason");
    if (retry) {
      Login.switchToEnglish(loginData);
      return login(false);
    }

    return StatusCode.UNKNOWN_ERROR; // can't login
  }
Esempio n. 22
0
 public static Date parseGcCustomDate(final String input) throws ParseException {
   return parseGcCustomDate(input, Settings.getGcCustomDate());
 }
 @Override
 public SearchResult runSearch() {
   return cgData.getBatchOfStoredCaches(searchCenter, Settings.getCacheType(), listId);
 }