예제 #1
0
 /** Get user session & session token from the Live Map. Needed for following requests */
 public static String[] getMapTokens() {
   final HttpResponse response = Network.getRequest(GCConstants.URL_LIVE_MAP);
   final String data = Network.getResponseData(response);
   final String userSession = BaseUtils.getMatch(data, GCConstants.PATTERN_USERSESSION, "");
   final String sessionToken = BaseUtils.getMatch(data, GCConstants.PATTERN_SESSIONTOKEN, "");
   return new String[] {userSession, sessionToken};
 }
예제 #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;
  }
예제 #3
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;
  }
예제 #4
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;
  }
예제 #5
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);
    }
  }
예제 #6
0
  public static String readCachePage(final String geocode) {
    try {
      final InputStream is =
          MockedCache.class.getResourceAsStream("/cgeo/geocaching/test/mock/" + geocode + ".html");
      final BufferedReader br = new BufferedReader(new InputStreamReader(is), 150000);

      final StringBuffer buffer = new StringBuffer();
      String line = null;

      while ((line = br.readLine()) != null) {
        buffer.append(line).append('\n');
      }

      br.close();
      return BaseUtils.replaceWhitespace(buffer.toString());
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
예제 #7
0
 /**
  * Searches for the pattern p in the data. If the pattern is not found defaultValue is returned
  *
  * @param data Data to search in
  * @param p Pattern to search for
  * @param defaultValue Value to return if the pattern is not found
  * @return defaultValue or the first group if the pattern matches (trimmed)
  */
 public static String getMatch(final String data, final Pattern p, final String defaultValue) {
   return BaseUtils.getMatch(data, p, true, 1, defaultValue, false);
 }
예제 #8
0
 protected MockedCache(final Geopoint coords) {
   this.coords = coords;
   this.data = MockedCache.readCachePage(getGeocode());
   // for mocked caches the user logged in is the user who saved the html file(s)
   this.mockedDataUser = BaseUtils.getMatch(data, GCConstants.PATTERN_USERLOGGEDIN, true, "");
 }
예제 #9
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;
    }
예제 #10
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
  }