@Override
 public void handle(Activity activity, CancellableTask task, Callback callback) {
   CloudflareUIHandler.handleCloudflare(
       this,
       (HttpChanModule) MainApplication.getInstance().getChanModule(chanName),
       activity,
       task,
       callback);
 }
예제 #2
0
 @Override
 public void run() {
   synchronized (serializeLock) {
     File file = fileCache.create(filename);
     Output output = null;
     try {
       output =
           isHoneycomb()
               ? new KryoOutputHC(new FileOutputStream(file))
               : new Output(new FileOutputStream(file));
       kryo.writeObject(output, obj);
     } catch (Exception e) {
       Logger.e(TAG, e);
     } catch (OutOfMemoryError oom) {
       MainApplication.freeMemory();
       Logger.e(TAG, oom);
     } finally {
       IOUtils.closeQuietly(output);
     }
     fileCache.put(file);
   }
 }
예제 #3
0
  private <T> T deserialize(File file, Class<T> type) {
    if (file == null || !file.exists()) {
      return null;
    }

    synchronized (serializeLock) {
      Input input = null;
      try {
        input = new Input(new FileInputStream(file));
        return kryo.readObject(input, type);
      } catch (Exception e) {
        Logger.e(TAG, e);
      } catch (OutOfMemoryError oom) {
        MainApplication.freeMemory();
        Logger.e(TAG, oom);
      } finally {
        IOUtils.closeQuietly(input);
      }
    }

    return null;
  }
  @Override
  public void handle(final Activity activity, final CancellableTask task, final Callback callback) {
    try {
      final HttpClient httpClient =
          MainApplication.getInstance().getChanModule(chanName).getHttpClient();
      final String usingURL = scheme + RECAPTCHA_FALLBACK_URL + publicKey;
      Header[] customHeaders = new Header[] {new BasicHeader(HttpHeaders.REFERER, usingURL)};
      String htmlChallenge =
          HttpStreamer.getInstance()
              .getStringFromUrl(
                  usingURL,
                  HttpRequestModel.builder().setGET().setCustomHeaders(customHeaders).build(),
                  httpClient,
                  null,
                  task,
                  false);

      Matcher challengeMatcher =
          Pattern.compile("name=\"c\" value=\"([\\w-]+)").matcher(htmlChallenge);
      if (challengeMatcher.find()) {
        final String challenge = challengeMatcher.group(1);
        HttpResponseModel responseModel =
            HttpStreamer.getInstance()
                .getFromUrl(
                    scheme + RECAPTCHA_IMAGE_URL + challenge + "&k=" + publicKey,
                    HttpRequestModel.builder().setGET().build(),
                    httpClient,
                    null,
                    task);
        try {
          InputStream imageStream = responseModel.stream;
          final Bitmap challengeBitmap = BitmapFactory.decodeStream(imageStream);

          final String message;
          Matcher messageMatcher =
              Pattern.compile("imageselect-message(?:.*?)>(.*?)</div>").matcher(htmlChallenge);
          if (messageMatcher.find()) message = messageMatcher.group(1).replaceAll("<[^>]*>", "");
          else message = null;

          final Bitmap candidateBitmap;
          Matcher candidateMatcher =
              Pattern.compile(
                      "fbc-imageselect-candidates(?:.*?)src=\"data:image/(?:.*?);base64,([^\"]*)\"")
                  .matcher(htmlChallenge);
          if (candidateMatcher.find()) {
            Bitmap bmp = null;
            try {
              byte[] imgData = Base64.decode(candidateMatcher.group(1), Base64.DEFAULT);
              bmp = BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
            } catch (Exception e) {
            }
            candidateBitmap = bmp;
          } else candidateBitmap = null;

          activity.runOnUiThread(
              new Runnable() {
                final int maxX = 3;
                final int maxY = 3;
                final boolean[] isSelected = new boolean[maxX * maxY];

                @SuppressLint("InlinedApi")
                @Override
                public void run() {
                  LinearLayout rootLayout = new LinearLayout(activity);
                  rootLayout.setOrientation(LinearLayout.VERTICAL);

                  if (candidateBitmap != null) {
                    ImageView candidateView = new ImageView(activity);
                    candidateView.setImageBitmap(candidateBitmap);
                    int picSize =
                        (int) (activity.getResources().getDisplayMetrics().density * 50 + 0.5f);
                    candidateView.setLayoutParams(new LinearLayout.LayoutParams(picSize, picSize));
                    candidateView.setScaleType(ImageView.ScaleType.FIT_XY);
                    rootLayout.addView(candidateView);
                  }

                  if (message != null) {
                    TextView textView = new TextView(activity);
                    textView.setText(message);
                    textView.setTextAppearance(activity, android.R.style.TextAppearance);
                    textView.setLayoutParams(
                        new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.MATCH_PARENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT));
                    rootLayout.addView(textView);
                  }

                  FrameLayout frame = new FrameLayout(activity);
                  frame.setLayoutParams(
                      new LinearLayout.LayoutParams(
                          LinearLayout.LayoutParams.MATCH_PARENT,
                          LinearLayout.LayoutParams.WRAP_CONTENT));

                  final ImageView imageView = new ImageView(activity);
                  imageView.setLayoutParams(
                      new FrameLayout.LayoutParams(
                          FrameLayout.LayoutParams.MATCH_PARENT,
                          FrameLayout.LayoutParams.MATCH_PARENT));
                  imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                  imageView.setImageBitmap(challengeBitmap);
                  frame.addView(imageView);

                  final LinearLayout selector = new LinearLayout(activity);
                  selector.setLayoutParams(
                      new FrameLayout.LayoutParams(
                          FrameLayout.LayoutParams.MATCH_PARENT,
                          FrameLayout.LayoutParams.MATCH_PARENT));
                  AppearanceUtils.callWhenLoaded(
                      imageView,
                      new Runnable() {
                        @Override
                        public void run() {
                          selector.setLayoutParams(
                              new FrameLayout.LayoutParams(
                                  imageView.getWidth(), imageView.getHeight()));
                        }
                      });
                  selector.setOrientation(LinearLayout.VERTICAL);
                  selector.setWeightSum(maxY);
                  for (int y = 0; y < maxY; ++y) {
                    LinearLayout subSelector = new LinearLayout(activity);
                    subSelector.setLayoutParams(
                        new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f));
                    subSelector.setOrientation(LinearLayout.HORIZONTAL);
                    subSelector.setWeightSum(maxX);
                    for (int x = 0; x < maxX; ++x) {
                      FrameLayout switcher = new FrameLayout(activity);
                      switcher.setLayoutParams(
                          new LinearLayout.LayoutParams(
                              0, LinearLayout.LayoutParams.MATCH_PARENT, 1f));
                      switcher.setTag(new int[] {x, y});
                      switcher.setOnClickListener(
                          new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                              int[] coord = (int[]) v.getTag();
                              int index = coord[1] * maxX + coord[0];
                              isSelected[index] = !isSelected[index];
                              v.setBackgroundColor(
                                  isSelected[index]
                                      ? Color.argb(128, 0, 255, 0)
                                      : Color.TRANSPARENT);
                            }
                          });
                      subSelector.addView(switcher);
                    }
                    selector.addView(subSelector);
                  }

                  frame.addView(selector);
                  rootLayout.addView(frame);

                  Button checkButton = new Button(activity);
                  checkButton.setLayoutParams(
                      new LinearLayout.LayoutParams(
                          LinearLayout.LayoutParams.MATCH_PARENT,
                          LinearLayout.LayoutParams.WRAP_CONTENT));
                  checkButton.setText(android.R.string.ok);
                  rootLayout.addView(checkButton);

                  ScrollView dlgView = new ScrollView(activity);
                  dlgView.addView(rootLayout);

                  final Dialog dialog = new Dialog(activity);
                  dialog.setTitle("Recaptcha");
                  dialog.setContentView(dlgView);
                  dialog.setCanceledOnTouchOutside(false);
                  dialog.setOnCancelListener(
                      new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                          if (!task.isCancelled()) {
                            callback.onError("Cancelled");
                          }
                        }
                      });
                  dialog
                      .getWindow()
                      .setLayout(
                          ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                  dialog.show();

                  checkButton.setOnClickListener(
                      new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                          dialog.dismiss();
                          if (task.isCancelled()) return;
                          PriorityThreadFactory.LOW_PRIORITY_FACTORY
                              .newThread(
                                  new Runnable() {
                                    @Override
                                    public void run() {
                                      try {
                                        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                                        pairs.add(new BasicNameValuePair("c", challenge));
                                        for (int i = 0; i < isSelected.length; ++i)
                                          if (isSelected[i])
                                            pairs.add(
                                                new BasicNameValuePair(
                                                    "response", Integer.toString(i)));

                                        HttpRequestModel request =
                                            HttpRequestModel.builder()
                                                .setPOST(
                                                    new UrlEncodedFormEntityHC4(pairs, "UTF-8"))
                                                .setCustomHeaders(
                                                    new Header[] {
                                                      new BasicHeader(HttpHeaders.REFERER, usingURL)
                                                    })
                                                .build();
                                        String response =
                                            HttpStreamer.getInstance()
                                                .getStringFromUrl(
                                                    usingURL,
                                                    request,
                                                    httpClient,
                                                    null,
                                                    task,
                                                    false);
                                        String hash = "";
                                        Matcher matcher =
                                            Pattern.compile(
                                                    "fbc-verification-token(?:.*?)<textarea[^>]*>([^<]*)<",
                                                    Pattern.DOTALL)
                                                .matcher(response);
                                        if (matcher.find()) hash = matcher.group(1);

                                        if (hash.length() > 0) {
                                          Recaptcha2solved.push(publicKey, hash);
                                          activity.runOnUiThread(
                                              new Runnable() {
                                                @Override
                                                public void run() {
                                                  callback.onSuccess();
                                                }
                                              });
                                        } else {
                                          throw new RecaptchaException(
                                              "incorrect answer (hash is empty)");
                                        }
                                      } catch (final Exception e) {
                                        Logger.e(TAG, e);
                                        if (task.isCancelled()) return;
                                        handle(activity, task, callback);
                                      }
                                    }
                                  })
                              .start();
                        }
                      });
                }
              });
        } finally {
          responseModel.release();
        }
      } else throw new Exception("can't parse recaptcha challenge answer");
    } catch (final Exception e) {
      Logger.e(TAG, e);
      if (!task.isCancelled()) {
        activity.runOnUiThread(
            new Runnable() {
              @Override
              public void run() {
                callback.onError(e.getMessage() != null ? e.getMessage() : e.toString());
              }
            });
      }
    }
  }
  /**
   * Called when the activity is first created. Configura todos os parametros de entrada e das
   * VIEWS..
   */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    setTheme(MainApplication.getInstance().settings.getTheme());
    super.onCreate(savedInstanceState);
    setResult(RESULT_CANCELED, getIntent());

    setTitle(R.string.filedialog_title);
    setContentView(R.layout.filedialog_main);
    myPath = (TextView) findViewById(R.id.path);
    mFileName = (EditText) findViewById(R.id.filedialog_EditTextFile);

    inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

    selectButton = (Button) findViewById(R.id.filedialog_ButtonSelect);
    selectButton.setEnabled(false);
    selectButton.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            if (selectedFile != null) {
              getIntent().putExtra(RESULT_PATH, selectedFile.getPath());
              setResult(RESULT_OK, getIntent());
              finish();
            }
          }
        });

    final Button newButton = (Button) findViewById(R.id.filedialog_ButtonNew);
    newButton.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            setCreateVisible(v);

            mFileName.setText("");
            mFileName.requestFocus();
          }
        });

    selectionMode = getIntent().getIntExtra(SELECTION_MODE, SELECTION_MODE_CREATE);

    formatFilter = getIntent().getStringArrayExtra(FORMAT_FILTER);

    canSelectDir = getIntent().getBooleanExtra(CAN_SELECT_DIR, false);

    if (selectionMode == SELECTION_MODE_OPEN) {
      newButton.setEnabled(false);
    }

    layoutSelect = (LinearLayout) findViewById(R.id.filedialog_LinearLayoutSelect);
    layoutCreate = (LinearLayout) findViewById(R.id.filedialog_LinearLayoutCreate);
    layoutCreate.setVisibility(View.GONE);

    final Button cancelButton = (Button) findViewById(R.id.filedialog_ButtonCancel);
    cancelButton.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            setSelectVisible(v);
          }
        });
    final Button createButton = (Button) findViewById(R.id.filedialog_ButtonCreate);
    createButton.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            if (mFileName.getText().length() > 0) {
              getIntent().putExtra(RESULT_PATH, currentPath + "/" + mFileName.getText());
              setResult(RESULT_OK, getIntent());
              finish();
            }
          }
        });

    String startPath = getIntent().getStringExtra(START_PATH);
    startPath = startPath != null ? startPath : ROOT;
    if (canSelectDir) {
      File file = new File(startPath);
      selectedFile = file;
      selectButton.setEnabled(true);
    }
    getDir(startPath);
  }