PageRenderTime 66ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/src/jd/captcha/JAntiCaptcha.java

https://bitbucket.org/jorgenio/jdownloader
Java | 2022 lines | 1479 code | 249 blank | 294 comment | 391 complexity | c7b1cfed3d209b39158660b898c3aa15 MD5 | raw file
Possible License(s): GPL-2.0, AGPL-1.0, MPL-2.0-no-copyleft-exception, Apache-2.0, BSD-3-Clause, LGPL-2.1, LGPL-2.0, GPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. // jDownloader - Downloadmanager
  2. // Copyright (C) 2008 JD-Team support@jdownloader.org
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. package jd.captcha;
  17. import java.awt.Color;
  18. import java.awt.Graphics;
  19. import java.awt.GridBagLayout;
  20. import java.awt.GridLayout;
  21. import java.awt.Image;
  22. import java.awt.event.ActionEvent;
  23. import java.awt.event.ActionListener;
  24. import java.awt.image.BufferedImage;
  25. import java.io.File;
  26. import java.io.FileFilter;
  27. import java.io.IOException;
  28. import java.lang.reflect.Method;
  29. import java.util.ArrayList;
  30. import java.util.Collections;
  31. import java.util.Comparator;
  32. import java.util.ListIterator;
  33. import java.util.Vector;
  34. import java.util.logging.Logger;
  35. import javax.imageio.ImageIO;
  36. import javax.swing.ImageIcon;
  37. import javax.swing.JButton;
  38. import javax.swing.JCheckBox;
  39. import javax.swing.JDialog;
  40. import javax.swing.JFrame;
  41. import javax.swing.JLabel;
  42. import javax.swing.JOptionPane;
  43. import javax.swing.JPanel;
  44. import javax.swing.JScrollPane;
  45. import javax.swing.JTextArea;
  46. import jd.captcha.configuration.JACScript;
  47. import jd.captcha.gui.BasicWindow;
  48. import jd.captcha.gui.ImageComponent;
  49. import jd.captcha.gui.ScrollPaneWindow;
  50. import jd.captcha.pixelgrid.Captcha;
  51. import jd.captcha.pixelgrid.Letter;
  52. import jd.captcha.utils.Utilities;
  53. import jd.controlling.JDLogger;
  54. import jd.gui.userio.DummyFrame;
  55. import jd.http.Browser;
  56. import jd.nutils.Executer;
  57. import jd.nutils.JDHash;
  58. import jd.nutils.io.JDIO;
  59. import jd.utils.JDUtilities;
  60. import org.appwork.utils.Regex;
  61. import org.appwork.utils.os.CrossSystem;
  62. import org.w3c.dom.Document;
  63. import org.w3c.dom.Element;
  64. import org.w3c.dom.NamedNodeMap;
  65. import org.w3c.dom.Node;
  66. import org.w3c.dom.NodeList;
  67. /**
  68. * Diese Klasse stellt alle public Methoden zur captcha Erkennung zur Verfügung.
  69. * Sie verküpft Letter und captcha Klassen. Gleichzeitig dient sie als
  70. * Parameter-Dump.
  71. *
  72. * @author JD-Team
  73. */
  74. public class JAntiCaptcha {
  75. /**
  76. * Logger
  77. */
  78. private static Logger logger = Utilities.getLogger();
  79. /**
  80. * Testet die Angegebene Methode. Dabei werden analysebilder erstellt.
  81. *
  82. * @param file
  83. */
  84. public static void testMethod(File file) {
  85. int checkCaptchas = 20;
  86. String code;
  87. String inputCode;
  88. int totalLetters = 0;
  89. int correctLetters = 0;
  90. File captchaFile;
  91. Image img;
  92. String methodName = file.getName();
  93. File captchaDir = new File(file.getAbsolutePath() + "/captchas");
  94. if (Utilities.isLoggerActive()) {
  95. logger.info("Test Method: " + methodName);
  96. }
  97. new JAntiCaptcha(methodName);
  98. File[] entries = captchaDir.listFiles(new FileFilter() {
  99. public boolean accept(File pathname) {
  100. // if(Utilities.isLoggerActive())logger.info(pathname.getName(
  101. // ));
  102. if (pathname.getName().endsWith(".jpg") || pathname.getName().endsWith(".png") || pathname.getName().endsWith(".gif")) {
  103. return true;
  104. } else {
  105. return false;
  106. }
  107. }
  108. });
  109. ScrollPaneWindow w = new ScrollPaneWindow();
  110. w.setTitle(" Test Captchas: " + file.getAbsolutePath());
  111. w.resizeWindow(100);
  112. if (Utilities.isLoggerActive()) {
  113. logger.info("Found Testcaptchas: " + entries.length);
  114. }
  115. int testNum = Math.min(checkCaptchas, entries.length);
  116. if (Utilities.isLoggerActive()) {
  117. logger.info("Test " + testNum + " Captchas");
  118. }
  119. int i = 0;
  120. for (i = 0; i < testNum; i++) {
  121. captchaFile = entries[(int) (Math.random() * entries.length)];
  122. logger.info("JJJJJJJJ" + captchaFile);
  123. img = Utilities.loadImage(captchaFile);
  124. w.setText(0, i, captchaFile.getName());
  125. w.setImage(1, i, img);
  126. w.repack();
  127. JAntiCaptcha jac = new JAntiCaptcha(methodName);
  128. // BasicWindow.showImage(img);
  129. Captcha cap = jac.createCaptcha(img);
  130. if (cap == null) {
  131. if (Utilities.isLoggerActive()) {
  132. logger.severe("Captcha Bild konnte nicht eingelesen werden");
  133. }
  134. continue;
  135. }
  136. w.setImage(2, i, cap.getImage());
  137. // BasicWindow.showImage(cap.getImageWithGaps(2));
  138. code = jac.checkCaptcha(captchaFile, cap);
  139. w.setImage(3, i, cap.getImage());
  140. w.setText(4, i, "JAC:" + code);
  141. w.repack();
  142. inputCode = JOptionPane.showInputDialog("Bitte Captcha Code eingeben", code);
  143. w.setText(5, i, "User:" + inputCode);
  144. w.repack();
  145. if (code == null) {
  146. code = "";
  147. }
  148. if (inputCode == null) {
  149. inputCode = "";
  150. }
  151. code = code.toLowerCase();
  152. inputCode = inputCode.toLowerCase();
  153. for (int x = 0; x < inputCode.length(); x++) {
  154. totalLetters++;
  155. if (inputCode.length() == code.length() && inputCode.charAt(x) == code.charAt(x)) {
  156. correctLetters++;
  157. }
  158. }
  159. if (Utilities.isLoggerActive()) {
  160. logger.info("Erkennung: " + correctLetters + "/" + totalLetters + " = " + Utilities.getPercent(correctLetters, totalLetters) + "%");
  161. }
  162. }
  163. w.setText(0, i + 1, "Erkennung: " + Utilities.getPercent(correctLetters, totalLetters) + "%");
  164. w.setText(4, i + 1, "Richtig: " + correctLetters);
  165. w.setText(5, i + 1, "Falsch: " + (totalLetters - correctLetters));
  166. JOptionPane.showMessageDialog(new JFrame(), "Erkennung: " + correctLetters + "/" + totalLetters + " = " + Utilities.getPercent(correctLetters, totalLetters) + "%");
  167. }
  168. /**
  169. * Führt einen Testlauf mit den übergebenen Methoden durch
  170. *
  171. * @param methods
  172. */
  173. public static void testMethods(File[] methods) {
  174. for (File element : methods) {
  175. JAntiCaptcha.testMethod(element);
  176. }
  177. }
  178. /**
  179. * Fenster die eigentlich nur zur Entwicklung sind um Basic GUI Elemente zu
  180. * haben
  181. */
  182. private BasicWindow bw2;
  183. private BasicWindow bw3;
  184. private JDialog f;
  185. /**
  186. * Bildtyp. Falls dieser von jpg unterschiedlich ist, muss zuerst
  187. * konvertiert werden.
  188. */
  189. private String imageType;
  190. /**
  191. * jas Script Instanz. Sie verarbneitet das JACScript und speichert die
  192. * Parameter
  193. */
  194. public JACScript jas;
  195. /**
  196. * Vector mit den Buchstaben aus der MTHO File
  197. */
  198. public ArrayList<Letter> letterDB;
  199. private int[][] letterMap = null;
  200. /**
  201. * Anzahl der Buchstaben im Captcha. Wird aus der jacinfo.xml gelesen
  202. */
  203. private int letterNum;
  204. /**
  205. * ordnername der methode
  206. */
  207. private String methodDirName;
  208. private boolean showDebugGui = false;
  209. private Vector<ScrollPaneWindow> spw = new Vector<ScrollPaneWindow>();
  210. private Captcha workingCaptcha;
  211. private boolean extern;
  212. public boolean isExtern() {
  213. return extern;
  214. }
  215. private String command;
  216. private String dstFile;
  217. private String srcFile;
  218. private Image sourceImage;
  219. public JAntiCaptcha(String methodName) {
  220. JACMethod method = JACMethod.forServiceName(methodName);
  221. if (method == null) {
  222. logger.severe("no such method found! " + methodName);
  223. return;
  224. }
  225. methodDirName = method.getFileName();
  226. getJACInfo();
  227. jas = new JACScript(this, methodDirName);
  228. long time = System.currentTimeMillis();
  229. loadMTHFile();
  230. time = System.currentTimeMillis() - time;
  231. System.out.println(time);
  232. if (Utilities.isLoggerActive()) {
  233. logger.fine("letter DB loaded: Buchstaben: " + letterDB.size());
  234. }
  235. }
  236. /**
  237. * prüft den übergebenen Captcha und gibt den Code als String zurück. Das
  238. * lettersarray des Catchas wird dabei bearbeitet. Es werden decoedvalue,
  239. * avlityvalue und parent gesetzt WICHTIG: Nach dem Decoden eines Captcha
  240. * herrscht Verwirrung. Es stehen unterschiedliche Methoden zur Verfügung um
  241. * an bestimmte Informationen zu kommen: captcha.getDecodedLetters() gibt
  242. * Die letter aus der datenbank zurück. Deren werte sind nicht fest. Auf den
  243. * Wert von getvalityvalue und getValityPercent kann man sich absolut nicht
  244. * verlassen. Einzig getDecodedValue() lässt sich zuverlässig auslesen
  245. * captcha.getLetters() gibt die Wirklichen Letter des captchas zurück. Hier
  246. * lassen sich alle wichtigen Infos abfragen. z.B. ValityValue,
  247. * ValityPercent, Decodedvalue, etc. Wer immer das hier liest sollte auf
  248. * keinen fall den fehler machen und sich auf Wert aus dem getdecodedLetters
  249. * array verlassen
  250. *
  251. * @param captcha
  252. * Captcha instanz
  253. * @return CaptchaCode
  254. */
  255. public String checkCaptcha(File file, Captcha captcha) {
  256. if (extern) return callExtern();
  257. workingCaptcha = captcha;
  258. // Führe prepare aus
  259. jas.executePrepareCommands(file, captcha);
  260. Letter[] letters = captcha.getLetters(getLetterNum());
  261. if (letters == null) {
  262. captcha.setValityPercent(100.0);
  263. if (Utilities.isLoggerActive()) {
  264. logger.severe("Captcha konnte nicht erkannt werden!");
  265. }
  266. return null;
  267. }
  268. String ret = "";
  269. double correct = 0;
  270. LetterComperator akt;
  271. // Scannen
  272. Vector<LetterComperator> newLettersVector = new Vector<LetterComperator>();
  273. for (int i = 0; i < letters.length; i++) {
  274. letters[i].setId(i);
  275. if (letters[i].detected != null) {
  276. akt = letters[i].detected;
  277. } else {
  278. akt = getLetter(letters[i]);
  279. }
  280. akt.getA().setId(i);
  281. newLettersVector.add(akt);
  282. }
  283. if (letters.length > getLetterNum()) {
  284. // sortieren
  285. Collections.sort(newLettersVector, new Comparator<LetterComperator>() {
  286. public int compare(LetterComperator obj1, LetterComperator obj2) {
  287. if (obj1.getValityPercent() < obj2.getValityPercent()) { return -1; }
  288. if (obj1.getValityPercent() > obj2.getValityPercent()) { return 1; }
  289. return 0;
  290. }
  291. });
  292. // schlechte entfernen
  293. if (Utilities.isLoggerActive()) {
  294. logger.info(getLetterNum() + "");
  295. }
  296. if (!jas.getBoolean("autoLetterNum")) {
  297. for (int i = newLettersVector.size() - 1; i >= getLetterNum(); i--) {
  298. newLettersVector.remove(i);
  299. }
  300. }
  301. // Wieder in die richtige reihenfolge sortieren
  302. Collections.sort(newLettersVector, new Comparator<LetterComperator>() {
  303. public int compare(LetterComperator obj1, LetterComperator obj2) {
  304. if (obj1.getA().getId() < obj2.getA().getId()) { return -1; }
  305. if (obj1.getA().getId() > obj2.getA().getId()) { return 1; }
  306. return 0;
  307. }
  308. });
  309. }
  310. if (getJas().getString("useLettercomparatorFilter") != null && getJas().getString("useLettercomparatorFilter").length() > 0) {
  311. String[] ref = getJas().getString("useLettercomparatorFilter").split("\\.");
  312. if (ref.length != 2) {
  313. captcha.setValityPercent(100.0);
  314. if (Utilities.isLoggerActive()) {
  315. logger.severe("useLettercomparatorFilter should have the format Class.Method");
  316. }
  317. return null;
  318. }
  319. String cl = ref[0];
  320. String methodname = ref[1];
  321. Class<?> newClass;
  322. try {
  323. newClass = Class.forName("jd.captcha.specials." + cl);
  324. Class<?>[] parameterTypes = new Class[] { newLettersVector.getClass(), this.getClass() };
  325. Method method = newClass.getMethod(methodname, parameterTypes);
  326. Object[] arguments = new Object[] { newLettersVector, this };
  327. Object instance = null;
  328. method.invoke(instance, arguments);
  329. } catch (Exception e) {
  330. if (Utilities.isLoggerActive()) {
  331. logger.severe("Fehler in useLettercomparatorFilter:" + e.getLocalizedMessage() + " / " + getJas().getString("useLettercomparatorFilter"));
  332. }
  333. JDLogger.exception(e);
  334. }
  335. }
  336. for (int i = 0; i < newLettersVector.size(); i++) {
  337. akt = newLettersVector.get(i);
  338. if (akt == null || akt.getValityPercent() >= 100.0) {
  339. ret += "-";
  340. correct += 100.0;
  341. } else {
  342. ret += akt.getDecodedValue();
  343. akt.getA().setId(i);
  344. correct += akt.getValityPercent();
  345. }
  346. // if(Utilities.isLoggerActive())logger.finer("Validty: " +
  347. // correct);
  348. }
  349. if (newLettersVector.size() == 0) {
  350. captcha.setValityPercent(100.0);
  351. return null;
  352. }
  353. captcha.setLetterComperators(newLettersVector.toArray(new LetterComperator[] {}));
  354. if (Utilities.isLoggerActive()) {
  355. logger.finer("Vality: " + (int) (correct / newLettersVector.size()));
  356. }
  357. captcha.setValityPercent(correct / newLettersVector.size());
  358. return ret;
  359. }
  360. /**
  361. * Exportiert die aktelle Datenbank als PNG einzelbilder
  362. */
  363. public void exportDB() {
  364. File path = Utilities.directoryChooser();
  365. File file;
  366. BufferedImage img;
  367. int i = 0;
  368. for (Letter letter : letterDB) {
  369. img = letter.getFullImage();
  370. file = new File(path + "/letterDB/" + i++ + "_" + letter.getDecodedValue() + ".png");
  371. file.mkdirs();
  372. try {
  373. logger.info("Write Db: " + file);
  374. ImageIO.write(img, "png", file);
  375. } catch (IOException e) {
  376. JDLogger.exception(e);
  377. }
  378. }
  379. }
  380. private BufferedImage toBufferedImage(Image i) {
  381. if (i instanceof BufferedImage) { return (BufferedImage) i; }
  382. Image img;
  383. img = new ImageIcon(i).getImage();
  384. BufferedImage b;
  385. b = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
  386. Graphics g = b.createGraphics();
  387. g.drawImage(img, 0, 0, null);
  388. g.dispose();
  389. return b;
  390. }
  391. private String callExtern() {
  392. try {
  393. File file = JDUtilities.getResourceFile(this.srcFile);
  394. file.getParentFile().mkdirs();
  395. String ext = CrossSystem.getFileExtension(file.getName());
  396. ImageIO.write(toBufferedImage(this.sourceImage), ext, file);
  397. } catch (Exception e) {
  398. JDLogger.exception(e);
  399. return null;
  400. }
  401. Executer exec = new Executer(JDUtilities.getResourceFile(this.command).getAbsolutePath());
  402. exec.setRunin(JDUtilities.getResourceFile(this.command).getParent());
  403. exec.setWaitTimeout(30);
  404. exec.start();
  405. exec.waitTimeout();
  406. // String ret = exec.getOutputStream() + " \r\n " +
  407. // exec.getErrorStream();
  408. String res = JDIO.readFileToString(JDUtilities.getResourceFile(this.dstFile));
  409. if (res == null) return null;
  410. return res.trim();
  411. }
  412. /**
  413. * Gibt den erkannten CaptchaText zurück
  414. *
  415. * @param captchafile
  416. * Pfad zum Bild
  417. * @return CaptchaCode
  418. */
  419. public String checkCaptcha(File captchafile) {
  420. if (Utilities.isLoggerActive()) {
  421. logger.finer("check " + captchafile);
  422. }
  423. Image captchaImage = Utilities.loadImage(captchafile);
  424. Captcha captcha = createCaptcha(captchaImage);
  425. if (captcha != null) captcha.setCaptchaFile(captchafile);
  426. // captcha.printCaptcha();
  427. return checkCaptcha(captchafile, captcha);
  428. }
  429. /**
  430. * Factory Methode zur Captcha erstellung
  431. *
  432. * @param captchaImage
  433. * Image instanz
  434. * @return captcha
  435. */
  436. public Captcha createCaptcha(Image captchaImage) {
  437. this.sourceImage = captchaImage;
  438. if (extern) return null;
  439. if (captchaImage.getWidth(null) <= 0 || captchaImage.getHeight(null) <= 0) {
  440. if (Utilities.isLoggerActive()) {
  441. logger.severe("Image Dimensionen zu klein. Image hat keinen Inahlt. Pfad/Url prüfen!");
  442. }
  443. return null;
  444. }
  445. Captcha ret = Captcha.getCaptcha(captchaImage, this);
  446. if (ret == null) { return null; }
  447. ret.setOwner(this);
  448. return ret;
  449. }
  450. /**
  451. * Aus gründen der geschwindigkeit wird die MTH XMl in einen vector
  452. * umgewandelt
  453. */
  454. private void createLetterDBFormMTH(Document mth) {
  455. letterDB = new ArrayList<Letter>();
  456. long start1 = System.currentTimeMillis();
  457. try {
  458. if (mth == null || mth.getFirstChild() == null) { return; }
  459. NodeList nl = mth.getFirstChild().getChildNodes();
  460. Letter tmp;
  461. for (int i = 0; i < nl.getLength(); i++) {
  462. // Get child node
  463. Node childNode = nl.item(i);
  464. if (childNode.getNodeName().equals("letter")) {
  465. NamedNodeMap att = childNode.getAttributes();
  466. tmp = new Letter();
  467. tmp.setOwner(this);
  468. String id = JDUtilities.getAttribute(childNode, "id");
  469. if (!tmp.setTextGrid(childNode.getTextContent())) {
  470. logger.severe("Error in Letters DB line: " + i + ":" + childNode.getTextContent() + " id:" + id);
  471. continue;
  472. }
  473. if (id != null) {
  474. tmp.setId(Integer.parseInt(id));
  475. }
  476. tmp.setSourcehash(att.getNamedItem("captchaHash").getNodeValue());
  477. tmp.setDecodedValue(att.getNamedItem("value").getNodeValue());
  478. tmp.setBadDetections(Integer.parseInt(JDUtilities.getAttribute(childNode, "bad")));
  479. tmp.setGoodDetections(Integer.parseInt(JDUtilities.getAttribute(childNode, "good")));
  480. letterDB.add(tmp);
  481. } else if (childNode.getNodeName().equals("map")) {
  482. if (Utilities.isLoggerActive()) {
  483. logger.fine("Parse LetterMap");
  484. }
  485. long start2 = System.currentTimeMillis();
  486. String[] map = childNode.getTextContent().split("\\|");
  487. letterMap = new int[map.length][map.length];
  488. for (int x = 0; x < map.length; x++) {
  489. String[] row = map[x].split("\\,");
  490. for (int y = 0; y < map.length; y++) {
  491. letterMap[x][y] = Integer.parseInt(row[y]);
  492. }
  493. }
  494. if (Utilities.isLoggerActive()) {
  495. logger.fine("LetterMap Parsing time: " + (System.currentTimeMillis() - start2));
  496. }
  497. }
  498. }
  499. } catch (Exception e) {
  500. JDLogger.exception(e);
  501. if (Utilities.isLoggerActive()) {
  502. logger.severe("Fehler bein lesen der MTH Datei!!. Methode kann nicht funktionieren!");
  503. }
  504. }
  505. if (Utilities.isLoggerActive()) {
  506. logger.fine("Mth Parsing time: " + (System.currentTimeMillis() - start1));
  507. }
  508. }
  509. /**
  510. * Diese methode trainiert einen captcha
  511. *
  512. * @param captchafile
  513. * File zum Bild
  514. * @param letterNum
  515. * Anzahl der Buchstaben im captcha
  516. * @return int -1: Übersprungen Sonst: anzahl der richtig erkanten Letter
  517. */
  518. private Document createXMLFromLetterDB() {
  519. Document xml = JDUtilities.parseXmlString("<jDownloader></jDownloader>", false);
  520. if (letterMap != null) {
  521. Element element = xml.createElement("map");
  522. xml.getFirstChild().appendChild(element);
  523. element.appendChild(xml.createTextNode(getLetterMapString()));
  524. }
  525. int i = 0;
  526. for (Letter letter : letterDB) {
  527. Element element = xml.createElement("letter");
  528. xml.getFirstChild().appendChild(element);
  529. element.appendChild(xml.createTextNode(letter.getPixelString()));
  530. element.setAttribute("id", i++ + "");
  531. element.setAttribute("value", letter.getDecodedValue());
  532. element.setAttribute("captchaHash", letter.getSourcehash());
  533. element.setAttribute("good", letter.getGoodDetections() + "");
  534. element.setAttribute("bad", letter.getBadDetections() + "");
  535. }
  536. return xml;
  537. }
  538. private void destroyScrollPaneWindows() {
  539. while (spw.size() > 0) {
  540. spw.remove(0).destroy();
  541. }
  542. }
  543. /**
  544. * Zeigt die Momentane Library an. Buchstaben können gelöscht werden
  545. */
  546. public void displayLibrary() {
  547. if (letterDB == null || letterDB.size() == 0) { return; }
  548. // final BasicWindow w = BasicWindow.getWindow("Library: " +
  549. // letterDB.size() + " Datensätze", 400, 300);
  550. final JFrame w = new JFrame();
  551. // w.setLayout(new GridBagLayout());
  552. sortLetterDB();
  553. JPanel p = new JPanel(new GridLayout(letterDB.size() + 1, 3));
  554. w.add(new JScrollPane(p));
  555. final Letter[] list = new Letter[letterDB.size()];
  556. int y = 0;
  557. int i = 0;
  558. ListIterator<Letter> iter = letterDB.listIterator(letterDB.size());
  559. final ArrayList<Integer> rem = new ArrayList<Integer>();
  560. while (iter.hasPrevious()) {
  561. final Letter tmp = iter.previous();
  562. list[i] = tmp;
  563. JLabel lbl = null;
  564. if ((tmp.getGoodDetections() == 0 && tmp.getBadDetections() > 3) || ((double) tmp.getBadDetections() / (double) tmp.getGoodDetections() >= 3)) {
  565. lbl = new JLabel("<html><p><font color=\"#ff0000\" " + "size=\"3\">" + tmp.getId() + ": " + tmp.getDecodedValue() + "(" + tmp.getGoodDetections() + "/" + tmp.getBadDetections() + ") Size: " + tmp.toPixelObject(0.85).getSize() + "</font> </p>" + "</html>");
  566. } else {
  567. lbl = new JLabel(tmp.getId() + ": " + tmp.getDecodedValue() + "(" + tmp.getGoodDetections() + "/" + tmp.getBadDetections() + ") Size: " + tmp.toPixelObject(0.85).getSize());
  568. }
  569. ImageComponent img = new ImageComponent(tmp.getImage());
  570. final JCheckBox bt = new JCheckBox("DELETE");
  571. final int ii = i;
  572. bt.addActionListener(new ActionListener() {
  573. public Integer id = ii;
  574. public void actionPerformed(ActionEvent arg) {
  575. JCheckBox src = ((JCheckBox) arg.getSource());
  576. if (src.getText().equals("DELETE")) {
  577. rem.add(id);
  578. } else {
  579. rem.remove(id);
  580. }
  581. }
  582. });
  583. p.add(lbl);
  584. p.add(img);
  585. p.add(bt);
  586. i++;
  587. y++;
  588. // if (y > 20) {
  589. // y = 0;
  590. // x += 6;
  591. // }
  592. }
  593. JButton b = new JButton("Invoke");
  594. p.add(b);
  595. b.addActionListener(new ActionListener() {
  596. public void actionPerformed(ActionEvent e) {
  597. // System.out.println(rem + "");
  598. ArrayList<Letter> list = new ArrayList<Letter>();
  599. int s = letterDB.size();
  600. for (Integer i : rem) {
  601. try {
  602. Letter let = letterDB.get(s - 1 - i);
  603. list.add(let);
  604. } catch (Exception ew) {
  605. JDLogger.exception(ew);
  606. }
  607. }
  608. for (Letter letter : list) {
  609. removeLetterFromLibrary(letter);
  610. }
  611. saveMTHFile();
  612. displayLibrary();
  613. }
  614. });
  615. w.pack();
  616. w.setVisible(true);
  617. }
  618. public String getCodeFromFileName(String name) {
  619. return new Regex(name, "captcha_(.*?)_code(.*?)\\.(.*?)").getMatch(1);
  620. }
  621. /**
  622. * Liest den captchaornder aus
  623. *
  624. * @param path
  625. * @return File Array
  626. */
  627. public File[] getImages(String path) {
  628. File dir = new File(path);
  629. if (dir == null || !dir.exists()) {
  630. if (Utilities.isLoggerActive()) {
  631. logger.severe("Image dir nicht gefunden " + path);
  632. }
  633. }
  634. logger.info(dir + "");
  635. File[] entries = dir.listFiles(new FileFilter() {
  636. public boolean accept(File pathname) {
  637. if (Utilities.isLoggerActive()) {
  638. logger.info(pathname.getName());
  639. }
  640. if (pathname.getName().endsWith(".bmp") || pathname.getName().endsWith(".jpg") || pathname.getName().endsWith(".png") || pathname.getName().endsWith(".gif")) {
  641. return true;
  642. } else {
  643. return false;
  644. }
  645. }
  646. });
  647. return entries;
  648. }
  649. /**
  650. * @return the imageType
  651. */
  652. public String getImageType() {
  653. return imageType;
  654. }
  655. /**
  656. * Die Methode parsed die jacinfo.xml
  657. */
  658. private void getJACInfo() {
  659. File f = getResourceFile("jacinfo.xml");
  660. if (!f.exists()) {
  661. if (Utilities.isLoggerActive()) {
  662. logger.severe("jacinfo.xml is missing2");
  663. }
  664. return;
  665. }
  666. Document doc = JDUtilities.parseXmlString(JDIO.readFileToString(f), false);
  667. if (doc == null) {
  668. if (Utilities.isLoggerActive()) {
  669. logger.severe("jacinfo.xml is missing2");
  670. }
  671. return;
  672. }
  673. NodeList nl = doc.getFirstChild().getChildNodes();
  674. for (int i = 0; i < nl.getLength(); i++) {
  675. // Get child node
  676. Node childNode = nl.item(i);
  677. if (childNode.getNodeName().equals("method")) {
  678. try {
  679. this.extern = JDUtilities.getAttribute(childNode, "type").equalsIgnoreCase("extern");
  680. } catch (Exception e) {
  681. }
  682. } else if (childNode.getNodeName().equals("command")) {
  683. this.srcFile = JDUtilities.getAttribute(childNode, "src");
  684. this.dstFile = JDUtilities.getAttribute(childNode, "dst");
  685. this.command = JDUtilities.getAttribute(childNode, "cmd");
  686. } else if (childNode.getNodeName().equals("format")) {
  687. try {
  688. setLetterNum(Integer.parseInt(JDUtilities.getAttribute(childNode, "letterNum")));
  689. } catch (Exception e) {
  690. }
  691. setImageType(JDUtilities.getAttribute(childNode, "type"));
  692. }
  693. }
  694. }
  695. /**
  696. * @return JACscript Instanz
  697. */
  698. public JACScript getJas() {
  699. return jas;
  700. }
  701. /**
  702. * Vergleicht a und b und gibt eine Vergleichszahl zurück. a und b werden
  703. * gegeneinander verschoben und b wird über die Parameter gedreht. Praktisch
  704. * heißt das, dass derjenige Treffer als gut eingestuft wird, bei dem der
  705. * Datenbank Datensatz möglichst optimal überdeckt wird.
  706. *
  707. * @param a
  708. * Original Letter
  709. * @param B
  710. * Vergleichsletter
  711. * @return int 0(super)-0xffffff (ganz übel)
  712. */
  713. public LetterComperator getLetter(Letter letter) {
  714. if (jas.getDouble("quickScanValityLimit") <= 0) {
  715. logger.info("quickscan disabled");
  716. return getLetterExtended(letter);
  717. }
  718. logger.info("Work on Letter:" + letter);
  719. // long startTime = Utilities.getTimer();
  720. LetterComperator res = null;
  721. double lastPercent = 100.0;
  722. int bvX, bvY;
  723. try {
  724. if (letterDB == null) {
  725. if (Utilities.isLoggerActive()) {
  726. logger.severe("letterDB nicht vorhanden");
  727. }
  728. return null;
  729. }
  730. LetterComperator lc;
  731. ScrollPaneWindow w = null;
  732. if (isShowDebugGui()) {
  733. w = new ScrollPaneWindow();
  734. w.setTitle(" Letter " + letter.getId());
  735. }
  736. bvX = jas.getInteger("borderVarianceX");
  737. bvY = jas.getInteger("borderVarianceY");
  738. int line = 0;
  739. lc = new LetterComperator(letter, null);
  740. lc.setScanVariance(0, 0);
  741. lc.setOwner(this);
  742. res = lc;
  743. int tt = 0;
  744. logger.info("Do quickscan");
  745. Method preValueFilterMethod = null;
  746. Class<?>[] preValueFilterParameterTypes = null;
  747. Object[] preValueFilterArguments = new Object[] { null, this };
  748. if (jas.getString("preValueFilter").length() > 0) {
  749. String[] ref = jas.getString("preValueFilter").split("\\.");
  750. if (ref.length != 2) {
  751. if (Utilities.isLoggerActive()) {
  752. logger.severe("preValueFilter should have the format Class.Method");
  753. }
  754. return null;
  755. }
  756. String cl = ref[0];
  757. String methodname = ref[1];
  758. Class<?> newClass;
  759. try {
  760. newClass = Class.forName("jd.captcha.specials." + cl);
  761. preValueFilterParameterTypes = new Class[] { LetterComperator.class, this.getClass() };
  762. preValueFilterMethod = newClass.getMethod(methodname, preValueFilterParameterTypes);
  763. } catch (Exception e) {
  764. JDLogger.exception(e);
  765. }
  766. }
  767. Method postValueFilterMethod = null;
  768. Class<?>[] postValueFilterParameterTypes = null;
  769. Object[] postValueFilterArguments = new Object[] { null, this };
  770. if (jas.getString("postValueFilter").length() > 0) {
  771. String[] ref = jas.getString("postValueFilter").split("\\.");
  772. if (ref.length != 2) {
  773. if (Utilities.isLoggerActive()) {
  774. logger.severe("postValueFilter should have the format Class.Method");
  775. }
  776. return null;
  777. }
  778. String cl = ref[0];
  779. String methodname = ref[1];
  780. Class<?> newClass;
  781. try {
  782. newClass = Class.forName("jd.captcha.specials." + cl);
  783. postValueFilterParameterTypes = new Class[] { LetterComperator.class, this.getClass() };
  784. postValueFilterMethod = newClass.getMethod(methodname, postValueFilterParameterTypes);
  785. } catch (Exception e) {
  786. JDLogger.exception(e);
  787. }
  788. }
  789. for (Letter tmp : letterDB) {
  790. if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
  791. if (Math.abs(tmp.getHeight() - letter.getHeight()) > bvY || Math.abs(tmp.getWidth() - letter.getWidth()) > bvX) {
  792. continue;
  793. }
  794. lc = new LetterComperator(letter, tmp);
  795. // commented out only experimental
  796. // lc.setScanVariance(0, 0);
  797. lc.setOwner(this);
  798. if (preValueFilterMethod != null) {
  799. preValueFilterArguments[0] = tmp;
  800. preValueFilterArguments[1] = lc;
  801. if (!((Boolean) preValueFilterMethod.invoke(null, preValueFilterArguments))) {
  802. continue;
  803. }
  804. }
  805. lc.run();
  806. tt++;
  807. if (isShowDebugGui()) {
  808. w.setText(0, line, "0° Quick " + tt);
  809. w.setImage(1, line, lc.getA().getImage(2));
  810. w.setText(2, line, lc.getA().getDim());
  811. w.setImage(3, line, lc.getB().getImage(2));
  812. w.setText(4, line, lc.getB().getDim());
  813. w.setImage(5, line, lc.getIntersectionLetter().getImage(2));
  814. w.setText(6, line, lc.getIntersectionLetter().getDim());
  815. w.setText(7, line, lc);
  816. line++;
  817. }
  818. postValueFilterArguments[0] = lc;
  819. if (postValueFilterMethod == null || (Boolean) postValueFilterMethod.invoke(null, postValueFilterArguments)) {
  820. if (res == null || lc.getValityPercent() < res.getValityPercent()) {
  821. if (res != null && res.getValityPercent() < lastPercent) {
  822. lastPercent = res.getValityPercent();
  823. }
  824. res = lc;
  825. if (jas.getDouble("LetterSearchLimitPerfectPercent") >= lc.getValityPercent()) {
  826. if (Utilities.isLoggerActive()) {
  827. logger.finer(" Perfect Match: " + res.getB().getDecodedValue() + res.getValityPercent() + " good:" + tmp.getGoodDetections() + " bad: " + tmp.getBadDetections() + " - " + res);
  828. }
  829. res.setDetectionType(LetterComperator.QUICKSCANPERFECTMATCH);
  830. res.setReliability(lastPercent - res.getValityPercent());
  831. return res;
  832. }
  833. // if(Utilities.isLoggerActive())logger.finer("dim "
  834. // +
  835. // lc.getA().getDim() + "|" + lc.getB().getDim() + " New
  836. // Best value: " + lc.getDecodedValue() + " "
  837. // +lc.getValityPercent() + " good:" +
  838. // tmp.getGoodDetections() + " bad: " +
  839. // tmp.getBadDetections() + " - " + lc);
  840. } else if (res != null) {
  841. if (lc.getValityPercent() < lastPercent) {
  842. lastPercent = lc.getValityPercent();
  843. }
  844. }
  845. }
  846. }
  847. } catch (Exception e) {
  848. JDLogger.exception(e);
  849. }
  850. if (res != null && res.getB() != null) {
  851. if (Utilities.isLoggerActive()) {
  852. logger.finer(" Normal Match: " + res.getB().getDecodedValue() + " " + res.getValityPercent() + " good:" + res.getB().getGoodDetections() + " bad: " + res.getB().getBadDetections());
  853. }
  854. // if (Utilities.isLoggerActive()) logger.fine("Letter erkannt
  855. // in: " + (Utilities.getTimer() - startTime) + " ms");
  856. res.setReliability(lastPercent - res.getValityPercent());
  857. if (res.getReliability() >= jas.getDouble("quickScanReliabilityLimit") && res.getValityPercent() < jas.getDouble("quickScanValityLimit")) {
  858. res.setDetectionType(LetterComperator.QUICKSCANMATCH);
  859. logger.info("Qickscan found " + res.getValityPercent() + "<" + jas.getDouble("quickScanValityLimit"));
  860. return res;
  861. } else {
  862. if (Utilities.isLoggerActive()) {
  863. logger.warning("Letter nicht ausreichend erkannt. Try Extended " + res.getReliability() + " - " + jas.getDouble("quickScanReliabilityLimit") + " /" + res.getValityPercent() + "-" + jas.getDouble("quickScanValityLimit"));
  864. }
  865. return getLetterExtended(letter);
  866. }
  867. } else {
  868. if (Utilities.isLoggerActive()) {
  869. logger.warning("Letter nicht erkannt. Try Extended");
  870. }
  871. return getLetterExtended(letter);
  872. }
  873. }
  874. /**
  875. * Sucht in der MTH ANch dem besten übereinstimmenem letter
  876. *
  877. * @param letter
  878. * (refferenz)
  879. * @return Letter. Beste Übereinstimmung
  880. */
  881. private LetterComperator getLetterExtended(Letter letter) {
  882. // long startTime = Utilities.getTimer();
  883. LetterComperator res = null;
  884. logger.info("Extended SCAN");
  885. double lastPercent = 100.0;
  886. JTextArea tf = null;
  887. try {
  888. if (letterDB == null) {
  889. if (Utilities.isLoggerActive()) {
  890. logger.severe("letterDB nicht vorhanden");
  891. }
  892. return null;
  893. }
  894. Letter tmp;
  895. int leftAngle = jas.getInteger("scanAngleLeft");
  896. int rightAngle = jas.getInteger("scanAngleRight");
  897. if (leftAngle > rightAngle) {
  898. int temp = leftAngle;
  899. leftAngle = rightAngle;
  900. rightAngle = temp;
  901. if (Utilities.isLoggerActive()) {
  902. logger.warning("param.scanAngleLeft>paramscanAngleRight");
  903. }
  904. }
  905. int steps = Math.max(1, jas.getInteger("scanAngleSteps"));
  906. boolean turnDB = jas.getBoolean("turnDB");
  907. int angle;
  908. Letter orgLetter = letter;
  909. LetterComperator lc;
  910. ScrollPaneWindow w = null;
  911. if (isShowDebugGui()) {
  912. w = new ScrollPaneWindow();
  913. w.setTitle(" Letter " + letter.getId());
  914. }
  915. int line = 0;
  916. lc = new LetterComperator(letter, null);
  917. lc.setOwner(this);
  918. res = lc;
  919. Method preValueFilterMethod = null;
  920. Class<?>[] preValueFilterParameterTypes = null;
  921. Object[] preValueFilterArguments = new Object[] { null, this };
  922. if (jas.getString("preValueFilter").length() > 0) {
  923. String[] ref = jas.getString("preValueFilter").split("\\.");
  924. if (ref.length != 2) {
  925. if (Utilities.isLoggerActive()) {
  926. logger.severe("preValueFilter should have the format Class.Method");
  927. }
  928. return null;
  929. }
  930. String cl = ref[0];
  931. String methodname = ref[1];
  932. Class<?> newClass;
  933. try {
  934. newClass = Class.forName("jd.captcha.specials." + cl);
  935. preValueFilterParameterTypes = new Class[] { LetterComperator.class, this.getClass() };
  936. preValueFilterMethod = newClass.getMethod(methodname, preValueFilterParameterTypes);
  937. } catch (Exception e) {
  938. JDLogger.exception(e);
  939. }
  940. }
  941. Method postValueFilterMethod = null;
  942. Class<?>[] postValueFilterParameterTypes = null;
  943. Object[] postValueFilterArguments = new Object[] { null, this };
  944. if (jas.getString("postValueFilter").length() > 0) {
  945. String[] ref = jas.getString("postValueFilter").split("\\.");
  946. if (ref.length != 2) {
  947. if (Utilities.isLoggerActive()) {
  948. logger.severe("postValueFilter should have the format Class.Method");
  949. }
  950. return null;
  951. }
  952. String cl = ref[0];
  953. String methodname = ref[1];
  954. Class<?> newClass;
  955. try {
  956. newClass = Class.forName("jd.captcha.specials." + cl);
  957. postValueFilterParameterTypes = new Class[] { LetterComperator.class, this.getClass() };
  958. postValueFilterMethod = newClass.getMethod(methodname, postValueFilterParameterTypes);
  959. } catch (Exception e) {
  960. JDLogger.exception(e);
  961. }
  962. }
  963. for (angle = Utilities.getJumperStart(leftAngle, rightAngle); Utilities.checkJumper(angle, leftAngle, rightAngle); angle = Utilities.nextJump(angle, leftAngle, rightAngle, steps)) {
  964. if (turnDB) {
  965. letter = orgLetter;
  966. } else {
  967. letter = orgLetter.turn(angle);
  968. }
  969. // if(Utilities.isLoggerActive())logger.finer(" Angle " +
  970. // angle + " : " + letter.getDim());
  971. int tt = 0;
  972. for (Letter ltr : letterDB) {
  973. if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
  974. if (turnDB) {
  975. tmp = ltr.turn(angle);
  976. } else {
  977. tmp = ltr;
  978. }
  979. if (Math.abs(tmp.getHeight() - letter.getHeight()) > jas.getInteger("borderVarianceY") || Math.abs(tmp.getWidth() - letter.getWidth()) > jas.getInteger("borderVarianceX")) {
  980. continue;
  981. }
  982. lc = new LetterComperator(letter, tmp);
  983. lc.setOwner(this);
  984. if (preValueFilterMethod != null) {
  985. preValueFilterArguments[0] = lc;
  986. preValueFilterArguments[1] = this;
  987. if (!((Boolean) preValueFilterMethod.invoke(null, preValueFilterArguments))) {
  988. continue;
  989. }
  990. }
  991. lc.run();
  992. // if(Utilities.isLoggerActive())logger.info("Duration:
  993. // "+(Utilities.getTimer()-timer) +"
  994. // Loops: "+lc.loopCounter);
  995. tt++;
  996. if (isShowDebugGui()) {
  997. w.setText(0, line, angle + "° " + tt);
  998. w.setImage(1, line, lc.getA().getImage(2));
  999. w.setText(2, line, lc.getA().getDim());
  1000. w.setImage(3, line, lc.getB().getImage(2));
  1001. w.setText(4, line, lc.getB().getDim());
  1002. w.setImage(5, line, lc.getIntersectionLetter().getImage(2));
  1003. w.setText(6, line, lc.getIntersectionLetter().getDim());
  1004. w.setComponent(7, line, tf = new JTextArea());
  1005. tf.setText(lc.toString());
  1006. if (lc.getPreValityPercent() > jas.getInteger("preScanFilter") && jas.getInteger("preScanFilter") > 0) {
  1007. tf.setBackground(Color.LIGHT_GRAY);
  1008. }
  1009. line++;
  1010. }
  1011. postValueFilterArguments[0] = lc;
  1012. if (postValueFilterMethod == null || (Boolean) postValueFilterMethod.invoke(null, postValueFilterArguments)) {
  1013. if (res == null || lc.getValityPercent() < res.getValityPercent()) {
  1014. if (res != null && res.getValityPercent() < lastPercent) {
  1015. lastPercent = res.getValityPercent();
  1016. }
  1017. res = lc;
  1018. if (jas.getDouble("LetterSearchLimitPerfectPercent") >= lc.getValityPercent()) {
  1019. res.setDetectionType(LetterComperator.PERFECTMATCH);
  1020. res.setReliability(lastPercent - res.getValityPercent());
  1021. if (Utilities.isLoggerActive()) {
  1022. logger.finer(" Perfect Match: " + res.getB().getDecodedValue() + " " + res.getValityPercent() + " good:" + tmp.getGoodDetections() + " bad: " + tmp.getBadDetections() + " - " + res);
  1023. }
  1024. if (isShowDebugGui()) {
  1025. tf.setBackground(Color.GREEN);
  1026. }
  1027. return res;
  1028. }
  1029. if (isShowDebugGui()) {
  1030. tf.setBackground(Color.BLUE);
  1031. }
  1032. if (Utilities.isLoggerActive()) {
  1033. logger.finer("Angle " + angle + "dim " + lc.getA().getDim() + "|" + lc.getB().getDim() + " New Best value: " + lc.getDecodedValue() + " " + lc.getValityPercent() + " good:" + tmp.getGoodDetections() + " bad: " + tmp.getBadDetections() + " - " + lc);
  1034. }
  1035. } else if (res != null) {
  1036. // if (Utilities.isLoggerActive()&&
  1037. // lc.getDecodedValue().equalsIgnoreCase("G"))
  1038. // logger.finer("Angle " + angle + "dim " +
  1039. // lc.getA().getDim() + "|" + lc.getB().getDim() + "
  1040. // value: " + lc.getDecodedValue() + " " +
  1041. // lc.getValityPercent() + " good:" +
  1042. // tmp.getGoodDetections() + " bad: " +
  1043. // tmp.getBadDetections() + " - " + lc);
  1044. if (lc.getValityPercent() < lastPercent) {
  1045. lastPercent = lc.getValityPercent();
  1046. }
  1047. }
  1048. }
  1049. }
  1050. // if(Utilities.isLoggerActive())logger.info("Full Angle scan
  1051. // in
  1052. // "+(Utilities.getTimer()-startTime2));
  1053. }
  1054. // w.refreshUI();
  1055. } catch (Exception e) {
  1056. JDLogger.exception(e);
  1057. }
  1058. if (res != null && res.getB() != null) {
  1059. if (Utilities.isLoggerActive()) {
  1060. logger.finer(" Normal Match: " + res.getB().getDecodedValue() + " " + res.getValityPercent() + " good:" + res.getB().getGoodDetections() + " bad: " + res.getB().getBadDetections());
  1061. }
  1062. res.setReliability(lastPercent - res.getValityPercent());
  1063. } else {
  1064. if (getJas().getInteger("preScanEmergencyFilter") > getJas().getInteger("preScanFilter")) {
  1065. logger.warning("nicht erkannt. Verwende erweiterte Emergencydatenbank");
  1066. int psf = getJas().getInteger("preScanFilter");
  1067. getJas().set("preScanFilter", getJas().getInteger("preScanEmergencyFilter"));
  1068. LetterComperator ret = getLetterExtended(letter);
  1069. getJas().set("preScanFilter", psf);
  1070. return ret;
  1071. }
  1072. if (Utilities.isLoggerActive()) {
  1073. logger.severe("Letter entgültig nicht erkannt");
  1074. }
  1075. if (isShowDebugGui() && tf != null) {
  1076. tf.setBackground(Color.RED);
  1077. }
  1078. }
  1079. return res;
  1080. }
  1081. /**
  1082. * @return gibt die Lettermap als String zurück
  1083. */
  1084. private String getLetterMapString() {
  1085. StringBuilder ret = new StringBuilder();
  1086. int i = 0;
  1087. for (int x = 0; x < letterMap.length; x++) {
  1088. ret.append("|");
  1089. i++;
  1090. for (int y = 0; y < letterMap[0].length; y++) {
  1091. ret.append(letterMap[x][y]);
  1092. i++;
  1093. ret.append(",");
  1094. i++;
  1095. }
  1096. ret.deleteCharAt(ret.length() - 1);
  1097. if (Utilities.isLoggerActive()) {

Large files files are truncated, but you can click here to view the full file