@Override
 public boolean canSwallow(ConnectionBan ban) {
   if (ban instanceof EndPointConnectExceptionBan) {
     final EndPointConnectExceptionBan other = (EndPointConnectExceptionBan) ban;
     if (proxyEquals(getProxy(), other.getProxy())
         && getPort() == other.getPort()
         && StringUtils.equals(getHost(), other.getHost())
         && StringUtils.equals(getProtocol(), other.getProtocol())) {
       return true;
     }
   }
   return false;
 }
 @Override
 public boolean isProxyBannedByUrlOrPlugin(
     final HTTPProxy proxy,
     final URL url,
     final Plugin pluginFromThread,
     boolean ignoreConnectBans) {
   if (!ignoreConnectBans && proxyEquals(getProxy(), proxy)) {
     final boolean ret =
         getPort() == getPort(url)
             && StringUtils.containsIgnoreCase(getHost(), Browser.getHost(url))
             && StringUtils.equals(getProtocol(), url.getProtocol());
     return ret;
   }
   return false;
 }
 /* remove invalid entries...without hostmask or without logins */
 private CopyOnWriteArrayList<AuthenticationInfo> cleanup(List<AuthenticationInfo> input) {
   if (input == null || input.size() == 0) {
     return null;
   }
   CopyOnWriteArrayList<AuthenticationInfo> ret = new CopyOnWriteArrayList<AuthenticationInfo>();
   for (AuthenticationInfo item : input) {
     if (StringUtils.isEmpty(item.getHostmask())) {
       continue;
     }
     if (StringUtils.isEmpty(item.getPassword()) && StringUtils.isEmpty(item.getPassword())) {
       continue;
     }
     ret.add(item);
   }
   return ret;
 }
Пример #4
0
 public CachedAccount(String host, Account account, PluginForHost plugin) {
   this.account = account;
   if (account == null) {
     this.type = ACCOUNTTYPE.NONE;
   } else {
     if (StringUtils.equalsIgnoreCase(host, account.getHoster())) {
       this.type = ACCOUNTTYPE.ORIGINAL;
     } else {
       this.type = ACCOUNTTYPE.MULTI;
     }
   }
   this.plugin = plugin;
   this.host = host;
   StringBuilder sb = new StringBuilder();
   if (host != null) {
     sb.append("HOST").append(host);
   }
   if (account != null) {
     sb.append("ACC").append(account.hashCode());
   }
   sb.append("TYPE").append(type.name());
   if (plugin != null) {
     sb.append("PLUGIN").append(plugin.getLazyP().getHost());
   }
   hashCode = sb.toString().hashCode();
 }
 public static final HashSet<String> handleBase64Decode(final String b64) {
   if (b64 == null) {
     return null;
   }
   final HashSet<String> results = new HashSet<String>();
   String finallink = b64;
   int i = 0;
   // this covers nested encoding.
   while (i < 20 && finallink != null && !new Regex(finallink, "(?:ftp|https?)://.+").matches()) {
     i++;
     // cleanup crap after padding. this can break subsequent tries
     finallink = Encoding.Base64Decode(finallink.replaceFirst("(={1,2})[\\w\\+]+$", "$1"));
     // urldecode
     if (finallink != null && new Regex(finallink, "%[0-9A-Fa-f]{2}").matches()) {
       finallink = Encoding.urlDecode(finallink, false);
     }
     // whitespace cleanup
     finallink = StringUtils.trim(finallink);
   }
   // determine multi or single result?
   final String[] multi = new Regex(finallink, "(?:https?|ftp)://").getColumn(-1);
   if (multi != null && multi.length > 1) {
     // because links might not be separated or deliminated, its best to use htmlparser
     final String[] links = HTMLParser.getHttpLinks(finallink, "");
     if (links != null) {
       for (final String link : links) {
         results.add(link);
       }
     }
   } else {
     results.add(finallink);
   }
   return results;
 }
Пример #6
0
 public String getNewPackageName(String nameFactory, String oldPackageName, String host) {
   if (StringUtils.isEmpty(nameFactory)) {
     if (!StringUtils.isEmpty(oldPackageName)) {
       return oldPackageName;
     }
     return host;
   }
   if (!StringUtils.isEmpty(oldPackageName)) {
     nameFactory = nameFactory.replaceAll("\\{PACKAGENAME\\}", oldPackageName);
   } else {
     nameFactory =
         nameFactory.replaceAll(
             "\\{PACKAGENAME\\}", _JDT.T.LinkCollector_addCrawledLink_variouspackage());
   }
   nameFactory = nameFactory.replaceAll("\\{HOSTNAME\\}", host);
   return nameFactory;
 }
Пример #7
0
 public boolean stringEquals(String a, String b) {
   if (a == null) {
     a = "";
   }
   if (b == null) {
     b = "";
   }
   return StringUtils.equals(a, b);
 }
Пример #8
0
  private boolean checkPassword(String pw, boolean optimized) throws ExtractionException {
    logger.info("Check Password: " + pw);
    if (StringUtils.isEmpty(pw)) {
      return false;
    }

    fireEvent(ExtractionEvent.Type.PASSWORT_CRACKING);
    return extractor.findPassword(this, pw, optimized);
  }
 /**
  * set the download folder for this FilePackage
  * 
  * @param subFolder
  */
 public void setDownloadDirectory(String folder) {
     if (StringUtils.isEmpty(folder)) {
         folder = org.appwork.storage.config.JsonConfig.create(GeneralSettings.class).getDefaultDownloadFolder();
     } /*else if (!CrossSystem.isAbsolutePath(folder)) {
         Log.L.severe("FilePackage: setDownloadDirectory only allows absolute pathes! Using default one!");
         folder = org.appwork.storage.config.JsonConfig.create(GeneralSettings.class).getDefaultDownloadFolder();
     }*/
     downloadDirectory = folder;
 }
    public List<String> getList() {
        List<String> ret = new ArrayList<String>();
        for (String s : Regex.getLines(getText())) {
            if (StringUtils.isNotEmpty(s)) {
                ret.add(s.trim());
            }
        }
        return ret;

    }
Пример #11
0
 protected String getDateFormatString() {
   String custom = CFG_GUI.CFG.getDateTimeFormatDownloadListAddedDateColumn();
   if (StringUtils.isNotEmpty(custom)) {
     return custom;
   }
   DateFormat sd = SimpleDateFormat.getDateTimeInstance();
   if (sd instanceof SimpleDateFormat) {
     return ((SimpleDateFormat) sd).toPattern();
   }
   return _GUI.T.added_date_column_dateformat();
 }
Пример #12
0
 public void setCurrentActiveItem(Item item) {
   if (currentActiveItem == item) {
     return;
   }
   if (currentActiveItem != null
       && item != null
       && StringUtils.equals(currentActiveItem.getPath(), item.getPath())) {
     return;
   }
   this.currentActiveItem = item;
   fireEvent(ExtractionEvent.Type.ACTIVE_ITEM);
 }
  public void validate(Login login, String url) {

    if (StringUtils.isEmpty(url)) {
      return;
    }
    AuthenticationInfo.Type type = null;
    if (url.startsWith("ftp")) {
      type = Type.FTP;
    } else if (url.startsWith("http")) {
      type = Type.HTTP;
    } else {
      Log.L.info("Unknown Protocoll: " + url);
      return;
    }

    String urlHost = Browser.getHost(url, true);
    for (AuthenticationInfo info : list) {
      if (!info.isEnabled()) {
        continue;
      }
      String authHost = info.getHostmask();
      if (info.getType().equals(type) && !StringUtils.isEmpty(authHost)) {
        boolean contains = false;
        if (authHost.length() > urlHost.length()) {
          /* hostMask of AuthenticationInfo is longer */
          contains = authHost.contains(urlHost);
        } else {
          /* hostMask of urlHost is longer */
          contains = urlHost.contains(authHost);
        }
        if (contains) {
          if (StringUtils.equals(info.getUsername(), login.getUsername())
              && StringUtils.equals(info.getPassword(), login.getPassword())) {
            info.setLastValidated(System.currentTimeMillis());
          }
        }
      }
    }
  }
Пример #14
0
 public List<String> listPathes(boolean atTop, String... strings) {
   final List<DownloadPath> l = list();
   final LinkedHashSet<String> dupe = new LinkedHashSet<String>();
   if (atTop && strings != null) {
     for (String s : strings) {
       if (StringUtils.isNotEmpty(s)) {
         dupe.add(s);
       }
     }
   }
   for (DownloadPath p : l) {
     if (p != null && StringUtils.isNotEmpty(p.getName())) {
       dupe.add(p.getName());
     }
   }
   if (!atTop && strings != null) {
     for (String s : strings) {
       if (StringUtils.isNotEmpty(s)) {
         dupe.add(s);
       }
     }
   }
   return Lists.unique(dupe);
 }
Пример #15
0
  public static Icon getIcon(final String name, final ExtensionsFilterInterface extension) {
    Icon newIcon = null;
    final String ext = Files.getExtension(name);
    if (CrossSystem.isWindows() && ext != null) {
      try {
        newIcon = CrossSystem.getMime().getFileIcon(ext, 16, 16);

      } catch (Throwable e) {
        LogController.CL().log(e);
      }
    }
    if (newIcon == null) {
      String iconID = null;
      if (extension != null && extension.getIconID() != null) {
        iconID = extension.getIconID();
      }
      if (StringUtils.isEmpty(iconID)) {
        iconID = "file";
      }
      newIcon = NewTheme.I().getIcon(iconID, 16);
    }
    return newIcon;
  }
Пример #16
0
  @Override
  public ArrayList<DownloadLink> decryptIt(
      final CryptedLink param, final ProgressController progress) throws Exception {
    synchronized (LOCK) {
      PROGRESS = progress;
      final ArrayList<DownloadLink> decryptedLinks = new ArrayList<DownloadLink>();
      final String parameter = correctCryptedLink(param.toString());
      setBrowserExclusive();
      br.setFollowRedirects(true);
      br.getHeaders().put("User-Agent", UA);

      /* Handle Captcha and/or password */
      handleCaptchaAndPassword(parameter, param);
      if (!br.getURL().contains("relink.us/")) {
        try {
          validateLastChallengeResponse();
        } catch (final Throwable e) {
        }
        logger.info("Link offline: " + parameter);
        return decryptedLinks;
      }
      if (br.containsHTML("<title>404</title>")) {
        logger.info("Link offline: " + parameter);
        return decryptedLinks;
      }
      if (ALLFORM != null && ALLFORM.getRegex("password").matches()) {
        throw new DecrypterException(DecrypterException.PASSWORD);
      }
      if (ALLFORM != null && ALLFORM.getRegex("captcha").matches()) {
        throw new DecrypterException(DecrypterException.CAPTCHA);
      }

      final String page = br.toString();
      progress.setRange(0);
      final String title =
          br.getRegex("shrink\"><th>(Titel|Baslik|Title)</th><td>(.*?)</td></tr>").getMatch(1);
      FilePackage fp = null;
      if (title != null && title.trim().length() > 0) {
        fp = FilePackage.getInstance();
        fp.setName(title);
        fp.setProperty("ALLOW_MERGE", true);
      }

      /* use cnl2 button if available */
      String cnlUrl = "http://127\\.0\\.0\\.1:9666/flash/addcrypted2";
      if (br.containsHTML(cnlUrl)) {
        final Browser cnlbr = br.cloneBrowser();

        Form cnlForm = null;
        for (Form f : cnlbr.getForms()) {
          if (f.containsHTML(cnlUrl)) {
            cnlForm = f;
          }
        }
        if (cnlForm != null) {

          if (System.getProperty("jd.revision.jdownloaderrevision") != null) {
            String jk =
                cnlbr.getRegex("<input type=\"hidden\" name=\"jk\" value=\"([^\"]+)\"").getMatch(0);
            HashMap<String, String> infos = new HashMap<String, String>();
            infos.put(
                "crypted", Encoding.urlDecode(cnlForm.getInputField("crypted").getValue(), false));
            infos.put("jk", jk);
            String source = cnlForm.getInputField("source").getValue();
            if (StringUtils.isEmpty(source)) {
              source = parameter.toString();
            } else {
              source = Encoding.urlDecode(source, true);
            }
            infos.put("source", source);
            String json = JSonStorage.toString(infos);
            final DownloadLink dl =
                createDownloadlink(
                    "http://dummycnl.jdownloader.org/"
                        + HexFormatter.byteArrayToHex(json.getBytes("UTF-8")));
            if (fp != null) {
              fp.add(dl);
            }
            try {
              distribute(dl);
            } catch (final Throwable e) {
              /* does not exist in 09581 */
            }
            decryptedLinks.add(dl);
            return decryptedLinks;
          } else {
            String jk =
                cnlbr.getRegex("<input type=\"hidden\" name=\"jk\" value=\"([^\"]+)\"").getMatch(0);
            cnlForm.remove("jk");
            cnlForm.put("jk", (jk != null ? jk.replaceAll("\\+", "%2B") : "nothing"));
            try {
              cnlbr.submitForm(cnlForm);
              if (cnlbr.containsHTML("success")) {
                return decryptedLinks;
              }
              if (cnlbr.containsHTML("^failed")) {
                logger.warning(
                    "relink.us: CNL2 Postrequest was failed! Please upload now a logfile, contact our support and add this loglink to your bugreport!");
                logger.warning("relink.us: CNL2 Message: " + cnlbr.toString());
              }
            } catch (Throwable e) {
              logger.info("relink.us: ExternInterface(CNL2) is disabled!");
            }
          }
        }
      }
      if (!br.containsHTML("download.php\\?id=[a-f0-9]+") && !br.containsHTML("getFile\\(")) {
        return null;
      }
      if (!decryptContainer(page, parameter, "dlc", decryptedLinks)) {
        if (!decryptContainer(page, parameter, "ccf", decryptedLinks)) {
          decryptContainer(page, parameter, "rsdf", decryptedLinks);
        }
      }
      /* Webdecryption */
      if (decryptedLinks.isEmpty()) {
        decryptLinks(decryptedLinks, param);
        final String more_links[] =
            new Regex(
                    page,
                    Pattern.compile(
                        "<a href=\"(go\\.php\\?id=[a-zA-Z0-9]+\\&seite=\\d+)\">",
                        Pattern.CASE_INSENSITIVE))
                .getColumn(0);
        for (final String link : more_links) {
          br.getPage("http://relink.us/" + link);
          decryptLinks(decryptedLinks, param);
        }
      }
      if (decryptedLinks.isEmpty() && br.containsHTML(cnlUrl)) {
        throw new DecrypterException("CNL2 only, open this link in Browser");
      }
      try {
        validateLastChallengeResponse();
      } catch (final Throwable e) {
      }
      if (fp != null) {
        fp.addLinks(decryptedLinks);
      }
      return decryptedLinks;
    }
  }
  public List<Login> getSortedLoginsList(String url) {
    if (StringUtils.isEmpty(url)) {
      return null;
    }
    AuthenticationInfo.Type type = null;
    if (url.startsWith("ftp")) {
      type = Type.FTP;
    } else if (url.startsWith("http")) {
      type = Type.HTTP;
    } else {
      Log.L.info("Unknown Protocoll: " + url);
      return null;
    }
    final ArrayList<AuthenticationInfo> possibleInfos = new ArrayList<AuthenticationInfo>();

    String urlHost = Browser.getHost(url, true);
    for (AuthenticationInfo info : list) {
      if (!info.isEnabled()) {
        continue;
      }
      final String authHost = info.getHostmask();
      if (info.getType().equals(type) && !StringUtils.isEmpty(authHost)) {
        boolean contains = false;
        if (authHost.length() > urlHost.length()) {
          /* hostMask of AuthenticationInfo is longer */
          contains = authHost.contains(urlHost);
        } else {
          /* hostMask of urlHost is longer */
          contains = urlHost.contains(authHost);
        }
        if (contains) {
          possibleInfos.add(info);
        }
      }
    }
    try {
      Collections.sort(
          possibleInfos,
          new Comparator<AuthenticationInfo>() {

            @Override
            public int compare(AuthenticationInfo o1, AuthenticationInfo o2) {
              int ret = Integer.compare(o2.getHostmask().length(), o1.getHostmask().length());
              if (ret == 0) {
                ret = Long.compare(o2.getLastValidated(), o1.getLastValidated());
              }
              if (ret == 0) {
                ret = Long.compare(o2.getCreated(), o1.getCreated());
              }
              return ret;
            }
          });

    } catch (Throwable e) {
      logger.log(e);
    }
    final ArrayList<Login> ret = new ArrayList<Login>();
    for (AuthenticationInfo info : possibleInfos) {
      ret.add(new Login(info.getUsername(), info.getPassword()));
    }
    return ret;
  }
Пример #18
0
  public void actionPerformed(ActionEvent e) {
    final SelectionInfo<CrawledPackage, CrawledLink> finalSelecction = getSelection();
    final String newName;
    final String newDownloadFolder;
    if (isMergePackages() && finalSelecction.getPackageViews().size() > 1) {
      if (isAskForNewDownloadFolderAndPackageName()) {
        try {
          final NewPackageDialog d =
              new NewPackageDialog(finalSelecction) {
                @Override
                public String getDontShowAgainKey() {
                  return "ABSTRACTDIALOG_DONT_SHOW_AGAIN_"
                      + SplitPackagesByHost.this.getClass().getSimpleName();
                }
              };

          Dialog.getInstance().showDialog(d);

          newName = d.getName();
          newDownloadFolder = d.getDownloadFolder();
          if (StringUtils.isEmpty(newName)) {
            return;
          }
        } catch (Throwable ignore) {
          return;
        }
      } else {
        newName = "";
        newDownloadFolder = finalSelecction.getFirstPackage().getRawDownloadFolder();
      }
    } else {
      newName = null;
      newDownloadFolder = null;
    }
    LinkCollector.getInstance()
        .getQueue()
        .add(
            new QueueAction<Void, RuntimeException>() {

              @Override
              protected Void run() throws RuntimeException {
                final HashMap<CrawledPackage, HashMap<String, ArrayList<CrawledLink>>> splitMap =
                    new HashMap<CrawledPackage, HashMap<String, ArrayList<CrawledLink>>>();
                int insertAt = -1;
                switch (getLocation()) {
                  case BEFORE_SELECTION:
                    insertAt = Integer.MAX_VALUE;
                }
                for (AbstractNode child : finalSelecction.getChildren()) {
                  if (child instanceof CrawledLink) {
                    final CrawledLink cL = (CrawledLink) child;
                    final CrawledPackage parent = isMergePackages() ? null : cL.getParentNode();

                    HashMap<String, ArrayList<CrawledLink>> parentMap = splitMap.get(parent);
                    if (parentMap == null) {
                      parentMap = new HashMap<String, ArrayList<CrawledLink>>();
                      splitMap.put(parent, parentMap);
                    }
                    final String host = cL.getDomainInfo().getTld();
                    ArrayList<CrawledLink> hostList = parentMap.get(host);
                    if (hostList == null) {
                      hostList = new ArrayList<CrawledLink>();
                      parentMap.put(host, hostList);
                    }
                    hostList.add(cL);
                    switch (getLocation()) {
                      case AFTER_SELECTION:
                        insertAt =
                            Math.max(
                                insertAt,
                                LinkCollector.getInstance()
                                        .indexOf(((CrawledLink) child).getParentNode())
                                    + 1);
                        break;
                      case BEFORE_SELECTION:
                        insertAt =
                            Math.min(
                                insertAt,
                                LinkCollector.getInstance()
                                    .indexOf(((CrawledLink) child).getParentNode()));
                        break;
                      case END_OF_LIST:
                        insertAt = -1;
                        break;
                      case TOP_OF_LIST:
                        insertAt = 0;
                        break;
                    }
                  }
                }
                if (insertAt == Integer.MAX_VALUE) {
                  insertAt = 0;
                }
                final String nameFactory =
                    JsonConfig.create(LinkgrabberSettings.class)
                        .getSplitPackageNameFactoryPattern();
                final boolean merge =
                    JsonConfig.create(LinkgrabberSettings.class).isSplitPackageMergeEnabled();
                final HashMap<String, CrawledPackage> mergedPackages =
                    new HashMap<String, CrawledPackage>();
                final Iterator<Entry<CrawledPackage, HashMap<String, ArrayList<CrawledLink>>>> it =
                    splitMap.entrySet().iterator();
                while (it.hasNext()) {
                  final Entry<CrawledPackage, HashMap<String, ArrayList<CrawledLink>>> next =
                      it.next();
                  // sourcePackage may be null
                  final CrawledPackage sourcePackage = next.getKey();
                  final HashMap<String, ArrayList<CrawledLink>> items = next.getValue();
                  final Iterator<Entry<String, ArrayList<CrawledLink>>> it2 =
                      items.entrySet().iterator();
                  while (it2.hasNext()) {
                    final Entry<String, ArrayList<CrawledLink>> next2 = it2.next();
                    final String host = next2.getKey();
                    final String newPackageName =
                        getNewPackageName(
                            nameFactory,
                            sourcePackage == null ? newName : sourcePackage.getName(),
                            host);
                    final CrawledPackage newPkg;
                    if (merge) {
                      CrawledPackage destPackage = mergedPackages.get(newPackageName);
                      if (destPackage == null) {
                        destPackage = new CrawledPackage();
                        destPackage.setExpanded(CFG_LINKCOLLECTOR.CFG.isPackageAutoExpanded());
                        if (sourcePackage != null) {
                          sourcePackage.copyPropertiesTo(destPackage);
                        } else {
                          destPackage.setDownloadFolder(newDownloadFolder);
                        }
                        destPackage.setName(newPackageName);
                        mergedPackages.put(newPackageName, destPackage);
                      }
                      newPkg = destPackage;
                    } else {
                      newPkg = new CrawledPackage();
                      newPkg.setExpanded(CFG_LINKCOLLECTOR.CFG.isPackageAutoExpanded());
                      if (sourcePackage != null) {
                        sourcePackage.copyPropertiesTo(newPkg);
                      } else {
                        newPkg.setDownloadFolder(newDownloadFolder);
                      }
                      newPkg.setName(newPackageName);
                    }
                    LinkCollector.getInstance().moveOrAddAt(newPkg, next2.getValue(), 0, insertAt);
                    insertAt++;
                  }
                }
                return null;
              }
            });
  }
 public boolean isSolved() {
   if (getResult() == null) return false;
   return StringUtils.isNotEmpty(getResult().getValue());
 }
 @Override
 public boolean isSelectorBannedByPlugin(final Plugin plugin, final boolean ignoreConnectBans) {
   final String host = plugin.getHost();
   return !ignoreConnectBans && StringUtils.containsIgnoreCase(getHost(), host);
 }
Пример #21
0
 @SuppressWarnings("deprecation")
 public ArrayList<DownloadLink> decryptIt(CryptedLink param, ProgressController progress)
     throws Exception {
   br = new Browser();
   decryptedLinks = new ArrayList<DownloadLink>();
   this.param = param;
   if (param.toString().matches(TYPE_INVALID)) {
     decryptedLinks.add(createOfflinelink(parameter));
     return decryptedLinks;
   }
   parameter = param.toString().replace("www.", "");
   passCode = new Regex(parameter, "\\?password=(.+)").getMatch(0);
   if (passCode != null) {
     /* Remove this from our url as it is only needed for this decrypter internally. */
     parameter = parameter.replace("?password="******"");
   }
   useOriginalFilename =
       PluginJsonConfig.get(TumblrComConfig.class).isUseOriginalFilenameEnabled();
   final Account aa =
       AccountController.getInstance()
           .getValidAccount(JDUtilities.getPluginForHost(this.getHost()));
   if (aa != null) {
     /* Login whenever possible to be able to download account-only-stuff */
     try {
       jd.plugins.hoster.TumblrCom.login(this.br, aa, false);
     } catch (final Throwable e) {
     }
   }
   try {
     if (parameter.matches(TYPE_FILE)) {
       decryptFile();
     } else if (parameter.matches(TYPE_POST)) {
       decryptPost();
     } else if (parameter.matches(TYPE_IMAGE)) {
       decryptedLinks.addAll(processImage(parameter, null, null));
     } else {
       /*
        * 2016-08-26: Seems like when logged in, users now get the same view they have when not logged in. Using the "old"
        * logged-in method, the crawler will not find all entries which is why we now use the normal method (again).
        */
       // if (loggedin) {
       // decryptUserLoggedIn();
       // } else {
       // parameter = convertUserUrlToLoggedOutUser();
       // decryptUser();
       // }
       parameter = convertUserUrlToLoggedOutUser();
       decryptUser();
     }
   } catch (final BrowserException e) {
     logger.info("Server error, couldn't decrypt link: " + parameter);
     return decryptedLinks;
   } catch (final UnknownHostException eu) {
     logger.info("UnknownHostException, couldn't decrypt link: " + parameter);
     return decryptedLinks;
   } catch (final DecrypterException d) {
     if (StringUtils.equals(d.getMessage(), PLUGIN_DEFECT)) {
       logger.warning("Decrypter broken for link: " + parameter);
       return null;
     } else if (StringUtils.equals(d.getMessage(), OFFLINE)) {
       decryptedLinks.add(createOfflinelink(parameter));
       return decryptedLinks;
     }
     throw d;
   }
   return decryptedLinks;
 }
Пример #22
0
 /** @return */
 public File getFile() {
   if (StringUtils.isEmpty(this.txt.getText())) {
     return null;
   }
   return this.textToFile(this.txt.getText());
 }
Пример #23
0
  @Override
  public Void run() {
    // let's write an info file. and delete if after extraction. this wy we have infosfiles if the
    // extraction crashes jd
    crashLog =
        new ExtractLogFileWriter(
            archive.getName(),
            archive.getFirstArchiveFile().getFilePath(),
            archive.getFactory().getID()) {
          @Override
          public void write(String string) {
            super.write(string);
            logger.info(string);
          }
        };
    try {
      fireEvent(ExtractionEvent.Type.START);
      archive.onStartExtracting();
      crashLog.write("Date: " + new Date());
      crashLog.write("Start Extracting");
      crashLog.write("Extension Setup: \r\n" + extension.getSettings().toString());

      crashLog.write("Archive Setup: \r\n" + JSonStorage.toString(archive.getSettings()));
      extractor.setCrashLog(crashLog);
      logger.info("Start unpacking of " + archive.getFirstArchiveFile().getFilePath());

      for (ArchiveFile l : archive.getArchiveFiles()) {
        if (!new File(l.getFilePath()).exists()) {
          crashLog.write("File missing: " + l.getFilePath());
          logger.info("Could not find archive file " + l.getFilePath());
          archive.addCrcError(l);
        }
      }
      if (archive.getCrcError().size() > 0) {
        fireEvent(ExtractionEvent.Type.FILE_NOT_FOUND);
        crashLog.write("Failed");
        return null;
      }

      if (gotKilled()) {
        return null;
      }
      crashLog.write("Prepare");
      if (extractor.prepare()) {
        extractToFolder = extension.getFinalExtractToFolder(archive);
        crashLog.write("Extract To: " + extractToFolder);
        if (archive.isProtected()) {
          crashLog.write("Archive is Protected");
          if (!StringUtils.isEmpty(archive.getFinalPassword())
              && !checkPassword(archive.getFinalPassword(), false)) {
            /* open archive with found pw */
            logger.info(
                "Password " + archive.getFinalPassword() + " is invalid, try to find correct one");
            archive.setFinalPassword(null);
          }
          if (StringUtils.isEmpty(archive.getFinalPassword())) {
            crashLog.write("Try to find password");
            /* pw unknown yet */
            List<String> spwList = archive.getSettings().getPasswords();
            if (spwList != null) {
              passwordList.addAll(spwList);
            }
            passwordList.addAll(archive.getFactory().getGuessedPasswordList(archive));
            passwordList.add(archive.getName());
            java.util.List<String> pwList = extractor.config.getPasswordList();
            if (pwList == null) {
              pwList = new ArrayList<String>();
            }
            passwordList.addAll(pwList);
            fireEvent(ExtractionEvent.Type.START_CRACK_PASSWORD);
            logger.info("Start password finding for " + archive);
            String correctPW = null;
            for (String password : passwordList) {
              if (password == null) {
                continue;
              }
              if (gotKilled()) {
                return null;
              }
              crashLog.write("Try Password: "******"Found password: \"" + password + "\"");
                break;
              } else {
                // try trimmed password
                String trimmed = password.trim();
                if (trimmed.length() != password.length()) {
                  password = trimmed;
                  if (checkPassword(
                      password, extension.getSettings().isPasswordFindOptimizationEnabled())) {
                    correctPW = password;
                    crashLog.write("Found password: \"" + password + "\"");
                    break;
                  }
                }
              }
            }

            if (correctPW == null) {
              fireEvent(ExtractionEvent.Type.PASSWORD_NEEDED_TO_CONTINUE);
              crashLog.write("Ask for password");
              logger.info("Found no password in passwordlist " + archive);
              if (gotKilled()) {
                return null;
              }
              if (!checkPassword(archive.getFinalPassword(), false)) {
                fireEvent(ExtractionEvent.Type.EXTRACTION_FAILED);
                logger.info("No password found for " + archive);
                crashLog.write("No password found or given");
                crashLog.write("Failed");
                return null;
              }
            }
            fireEvent(ExtractionEvent.Type.PASSWORD_FOUND);
            logger.info("Found password for " + archive + "->" + archive.getFinalPassword());
          }
          if (StringUtils.isNotEmpty(archive.getFinalPassword())) {
            extension.addPassword(archive.getFinalPassword());
          }
        }
        final DiskSpaceReservation extractReservation =
            new DiskSpaceReservation() {

              @Override
              public long getSize() {
                final long completeSize =
                    Math.max(getCompleteBytes(), archive.getContentView().getTotalSize());
                long ret = completeSize - getProcessedBytes();
                return ret;
              }

              @Override
              public File getDestination() {
                return getExtractToFolder();
              }
            };
        DISKSPACERESERVATIONRESULT reservationResult =
            DownloadWatchDog.getInstance()
                .getSession()
                .getDiskSpaceManager()
                .checkAndReserve(extractReservation, this);
        try {
          switch (reservationResult) {
            case FAILED:
              logger.info(
                  "Not enough harddisk space for unpacking archive "
                      + archive.getFirstArchiveFile().getFilePath());
              crashLog.write("Diskspace Problem: " + reservationResult);
              crashLog.write("Failed");
              fireEvent(ExtractionEvent.Type.NOT_ENOUGH_SPACE);
              return null;
            case INVALIDDESTINATION:
              logger.warning("Could use create subpath");
              crashLog.write("Could use create subpath: " + getExtractToFolder());
              crashLog.write("Failed");
              fireEvent(ExtractionEvent.Type.EXTRACTION_FAILED);
              return null;
          }
          fireEvent(ExtractionEvent.Type.OPEN_ARCHIVE_SUCCESS);
          if (!getExtractToFolder().exists()) {
            if (!FileCreationManager.getInstance().mkdir(getExtractToFolder())) {
              logger.warning("Could not create subpath");
              crashLog.write("Could not create subpath: " + getExtractToFolder());
              crashLog.write("Failed");
              fireEvent(ExtractionEvent.Type.EXTRACTION_FAILED);
              return null;
            }
          }
          logger.info("Execute unpacking of:" + archive);
          logger.info("Extract to " + getExtractToFolder());
          crashLog.write(
              "Use Password: "******"|PW Protected:"
                  + archive.isProtected()
                  + ":"
                  + archive.isPasswordRequiredToOpen());
          ScheduledExecutorService scheduler = null;
          try {
            crashLog.write("Start Extracting " + extractor);
            scheduler = DelayedRunnable.getNewScheduledExecutorService();
            timer =
                scheduler.scheduleWithFixedDelay(
                    new Runnable() {
                      public void run() {
                        fireEvent(ExtractionEvent.Type.EXTRACTING);
                      }
                    },
                    1,
                    1,
                    TimeUnit.SECONDS);
            extractor.extract(this);
          } finally {
            crashLog.write("Extractor Returned");
            if (timer != null) {
              timer.cancel(false);
            }
            if (scheduler != null) {
              scheduler.shutdown();
            }
            extractor.close();
            if (extractor.getLastAccessedArchiveFile() != null) {
              crashLog.write("Last used File: " + extractor.getLastAccessedArchiveFile());
            }
            fireEvent(ExtractionEvent.Type.EXTRACTING);
          }
        } finally {
          DownloadWatchDog.getInstance()
              .getSession()
              .getDiskSpaceManager()
              .free(extractReservation, this);
        }
        if (gotKilled()) {
          return null;
        }
        if (extractor.getException() != null) {
          exception = extractor.getException();
          logger.log(exception);
        }
        if (exception != null) {
          crashLog.write("Exception occured: \r\n" + Exceptions.getStackTrace(exception));
        }

        crashLog.write("ExitCode: " + archive.getExitCode());
        switch (archive.getExitCode()) {
          case ExtractionControllerConstants.EXIT_CODE_SUCCESS:
            logger.info("Unpacking successful for " + archive);
            archive
                .getSettings()
                .setExtractionInfo(new ExtractionInfo(getExtractToFolder(), archive));
            crashLog.write(
                "Info: \r\n"
                    + JSonStorage.serializeToJson(
                        new ExtractionInfo(getExtractToFolder(), archive)));
            crashLog.write("Successful");
            successful = true;
            fireEvent(ExtractionEvent.Type.FINISHED);
            logger.clear();
            break;
          case ExtractionControllerConstants.EXIT_CODE_INCOMPLETE_ERROR:
            logger.warning("Archive seems to be incomplete " + archive);
            crashLog.write("Incomplete Archive");
            crashLog.write("Failed");
            fireEvent(ExtractionEvent.Type.FILE_NOT_FOUND);
            break;
          case ExtractionControllerConstants.EXIT_CODE_CRC_ERROR:
            logger.warning("A CRC error occurred when unpacking " + archive);
            crashLog.write("CRC Error occured");
            crashLog.write("Failed");
            fireEvent(ExtractionEvent.Type.EXTRACTION_FAILED_CRC);
            break;
          case ExtractionControllerConstants.EXIT_CODE_USER_BREAK:
            logger.info("User interrupted unpacking of " + archive);
            crashLog.write("Interrupted by User");
            crashLog.write("Failed");
            fireEvent(ExtractionEvent.Type.EXTRACTION_FAILED);
            break;
          case ExtractionControllerConstants.EXIT_CODE_CREATE_ERROR:
            logger.warning("Could not create Outputfile for" + archive);
            crashLog.write("Could not create Outputfile");
            crashLog.write("Failed");
            fireEvent(ExtractionEvent.Type.EXTRACTION_FAILED);
            break;
          case ExtractionControllerConstants.EXIT_CODE_WRITE_ERROR:
            logger.warning("Unable to write unpacked data on harddisk for " + archive);
            this.exception = new ExtractionException("Write to disk error");
            crashLog.write("Harddisk write Error");
            crashLog.write("Failed");
            fireEvent(ExtractionEvent.Type.EXTRACTION_FAILED);
            break;
          case ExtractionControllerConstants.EXIT_CODE_FATAL_ERROR:
            logger.warning("A unknown fatal error occurred while unpacking " + archive);
            crashLog.write("Unknown Fatal Error");
            crashLog.write("Failed");
            fireEvent(ExtractionEvent.Type.EXTRACTION_FAILED);
            break;
          case ExtractionControllerConstants.EXIT_CODE_WARNING:
            logger.warning("Non fatal error(s) occurred while unpacking " + archive);
            crashLog.write("Unknown Non Fatal Error");
            crashLog.write("Failed");
            fireEvent(ExtractionEvent.Type.EXTRACTION_FAILED);
            break;
          default:
            crashLog.write("Failed...unknown reason");
            crashLog.write("Failed");
            fireEvent(ExtractionEvent.Type.EXTRACTION_FAILED);
            break;
        }
        return null;
      } else {
        crashLog.write("Failed");
        fireEvent(ExtractionEvent.Type.EXTRACTION_FAILED);
      }
    } catch (Exception e) {
      logger.log(e);
      this.exception = e;
      crashLog.write("Exception occured: \r\n" + Exceptions.getStackTrace(e));
      crashLog.write("Failed");
      fireEvent(ExtractionEvent.Type.EXTRACTION_FAILED);
    } finally {
      crashLog.close();
      if (!CFG_EXTRACTION.CFG.isWriteExtractionLogEnabled()) {
        crashLog.delete();
      }
      try {
        if (gotKilled()) {
          logger.info("ExtractionController has been killed");
          logger.clear();
        }
        try {
          extractor.close();
        } catch (final Throwable e) {
        }
        fireEvent(ExtractionEvent.Type.CLEANUP);
        archive.onCleanUp();
      } finally {
        logger.close();
      }
    }
    return null;
  }
 private static String getRouterName(String name) {
     if (StringUtils.isEmpty(name)) {
         return _GUI._.unknown_router_name();
     }
     return name;
 }
Пример #25
0
  public ArrayList<DownloadLink> decryptIt(CryptedLink param, ProgressController progress)
      throws Exception {
    final ArrayList<DownloadLink> decryptedLinks = new ArrayList<DownloadLink>();
    final String parameter = param.toString();
    if (StringUtils.contains(parameter, "bs.to/out")) {
      this.br.setFollowRedirects(false);
      br.getPage(parameter);
      if (br.getRedirectLocation() == null || br.containsHTML("g-recaptcha")) {
        final Form form = this.br.getForm(0);
        if (form == null) {
          throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
        }
        final String recaptchaV2Response =
            new CaptchaHelperCrawlerPluginRecaptchaV2(this, br).getToken();
        form.put("response", recaptchaV2Response);
        this.br.submitForm(form);
      }
      final String finallink = br.getRedirectLocation();
      decryptedLinks.add(createDownloadlink(finallink));
      return decryptedLinks;
    }
    this.br.setFollowRedirects(true);
    br.getPage(parameter);
    if (br.getHttpConnection().getResponseCode() == 404) {
      decryptedLinks.add(this.createOfflinelink(parameter));
      return decryptedLinks;
    }
    final String urlpart = new Regex(parameter, "(serie/.+)").getMatch(0);
    if (parameter.matches(TYPE_SINGLE)) {
      String finallink =
          br.getRegex("\"(https?[^<>\"]*?)\" target=\"_blank\"><span class=\"icon link_go\"")
              .getMatch(0);
      if (finallink == null) {
        finallink = br.getRegex("<iframe\\s+[^>]+src\\s*=\\s*(\"|'|)(.*?)\\1").getMatch(1);
      }
      if (finallink == null) {
        throw new DecrypterException(DecrypterException.PLUGIN_DEFECT);
      } else if (finallink.contains("bs.to/out/")) {
        br.setFollowRedirects(false);
        br.getPage(finallink);
        if (br.getRedirectLocation() == null || br.containsHTML("g-recaptcha")) {
          final Form form = this.br.getForm(0);
          if (form == null) {
            throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
          }
          final String recaptchaV2Response =
              new CaptchaHelperCrawlerPluginRecaptchaV2(this, br).getToken();
          form.put("response", recaptchaV2Response);
          this.br.submitForm(form);
        }
        finallink = br.getRedirectLocation();
      }
      decryptedLinks.add(createDownloadlink(finallink));
    } else {
      final String[] links =
          br.getRegex(
                  "class=\"v\\-centered icon [^<>\"]+\"[\t\n\r ]+href=\"(" + urlpart + "/[^/]+)\"")
              .getColumn(0);
      if (links == null || links.length == 0) {
        logger.warning("Decrypter broken for link: " + parameter);
        return null;
      }
      for (final String singleLink : links) {
        decryptedLinks.add(createDownloadlink("http://bs.to/" + singleLink));
      }
    }

    return decryptedLinks;
  }
Пример #26
0
  public TrayIconPopup(TrayExtension trayExtension) {
    super();
    this.extension = trayExtension;
    // resizecomps = new ArrayList<AbstractButton>();
    setVisible(false);
    setLayout(new MigLayout("ins 0", "[grow,fill]", "[grow,fill]"));
    addMouseListener(this);
    this.setUndecorated(true);
    // initEntryPanel();
    // initQuickConfigPanel();
    // initBottomPanel();
    // initExitPanel();
    JPanel content = new JPanel(new MigLayout("ins 5, wrap 1", "[fill]", "[]5[]"));
    add(content);
    JButton header;
    content.add(
        header = new JButton("<html><b>" + JDUtilities.getJDTitle(0) + "</b></html>"),
        "align center");
    header.setBorderPainted(false);
    header.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {
            JDGui.getInstance().setWindowToTray(false);
            dispose();
          }
        });
    AbstractButton ab;
    // System.out.println(this.getColConstraints(list.length));
    MenuItemData last = null;
    for (final MenuItemData menudata : MenuManagerTrayIcon.getInstance().getMenuData().getItems()) {
      AbstractButton bt = null;
      AppAction action;
      try {
        if (!menudata.isVisible()) {
          continue;
        }
        if (menudata instanceof SeparatorData) {
          if (last != null && last instanceof SeparatorData) {
            // no separator dupes
            continue;
          }
          content.add(new JSeparator(SwingConstants.HORIZONTAL), "growx,spanx");
          last = menudata;
          continue;
        }
        if (menudata._getValidateException() != null) {
          continue;
        }

        if (menudata.getType()
            == org.jdownloader.controlling.contextmenu.MenuItemData.Type.CONTAINER) {

          bt =
              new JToggleButton() {

                protected void paintComponent(Graphics g) {

                  super.paintComponent(g);

                  Graphics2D g2 = (Graphics2D) g;
                  g2.setRenderingHint(
                      RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                  g2.setRenderingHint(
                      RenderingHints.KEY_INTERPOLATION,
                      RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                  g2.setRenderingHint(
                      RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                  g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.8f));
                  g2.setColor(Color.BLACK);
                  g2.fillPolygon(
                      new int[] {getWidth() - 5, getWidth() - 5 - 6, getWidth() - 5 - 6},
                      new int[] {getHeight() / 2, getHeight() / 2 - 4, getHeight() / 2 + 4},
                      3);
                }
              };

          bt.setText(menudata.getName());
          bt.setOpaque(false);
          bt.setContentAreaFilled(false);
          bt.setBorderPainted(false);
          bt.addActionListener(
              new ActionListener() {
                private ExtPopupMenu root = null;

                public void actionPerformed(ActionEvent e) {
                  hideThreadrunning = false;
                  if (root != null && root.isShowing()) {
                    return;
                  }
                  root = new ExtPopupMenu();

                  new MenuBuilder(
                      MenuManagerMainToolbar.getInstance(), root, (MenuContainer) menudata) {
                    protected void addAction(
                        final JComponent root, final MenuItemData inst, int index, int size)
                        throws InstantiationException, IllegalAccessException,
                            InvocationTargetException, ClassNotFoundException,
                            NoSuchMethodException, ExtensionNotLoadedException {
                      final JComponent ret = inst.addTo(root);
                      if (ret instanceof AbstractButton) {
                        ((AbstractButton) ret)
                            .addActionListener(
                                new ActionListener() {
                                  public void actionPerformed(ActionEvent evt) {
                                    ((AbstractButton) ret).getAction().actionPerformed(evt);
                                    TrayIconPopup.this.dispose();
                                  }
                                });
                      }
                    }
                  }.run();
                  Object src = e.getSource();
                  if (e.getSource() instanceof Component) {
                    Component button = (Component) e.getSource();
                    Dimension prefSize = root.getPreferredSize();
                    int[] insets = LAFOptions.getInstance().getPopupBorderInsets();
                    root.show(button, button.getWidth(), -insets[0]);
                  }
                }
              });
          bt.setIcon(MenuItemData.getIcon(menudata.getIconKey(), ICON_SIZE));
          bt.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
          bt.setFocusPainted(false);
          bt.setHorizontalAlignment(JButton.LEFT);
          bt.setIconTextGap(5);
          bt.addMouseListener(new HoverEffect(bt));
          final AbstractButton finalBt = bt;
          bt.addMouseListener(
              new MouseListener() {

                private Timer timer;

                @Override
                public void mouseReleased(MouseEvent e) {
                  if (timer != null) {
                    timer.stop();
                    timer = null;
                  }
                }

                @Override
                public void mousePressed(MouseEvent e) {
                  if (timer != null) {
                    timer.stop();
                    timer = null;
                  }
                }

                @Override
                public void mouseExited(MouseEvent e) {
                  if (timer != null) {
                    timer.stop();
                    timer = null;
                  }
                }

                @Override
                public void mouseEntered(MouseEvent e) {

                  timer =
                      new Timer(
                          500,
                          new ActionListener() {

                            @Override
                            public void actionPerformed(ActionEvent e) {
                              finalBt.doClick();
                            }
                          });
                  timer.setRepeats(false);
                  timer.start();
                }

                @Override
                public void mouseClicked(MouseEvent e) {
                  if (timer != null) {
                    timer.stop();
                    timer = null;
                  }
                }
              });
          content.add(bt);

          continue;
        } else if (menudata instanceof MenuLink) {
          final JComponent item = menudata.createItem();
          if (StringUtils.isNotEmpty(menudata.getIconKey())) {
            if (item instanceof AbstractButton) {
              ((AbstractButton) item)
                  .setIcon(MenuItemData.getIcon(menudata.getIconKey(), ICON_SIZE));
            }
          }
          content.add(item, "");

        } else if (menudata.getActionData() != null) {

          action = menudata.createAction();
          if (!action.isVisible()) {
            continue;
          }
          if (StringUtils.isNotEmpty(menudata.getShortcut())
              && KeyStroke.getKeyStroke(menudata.getShortcut()) != null) {
            action.setAccelerator(KeyStroke.getKeyStroke(menudata.getShortcut()));
          } else if (MenuItemData.isEmptyValue(menudata.getShortcut())) {
            action.setAccelerator(null);
          }
          content.add(getMenuEntry(action));
          last = menudata;
        }

      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    // content.add(new JSeparator(), "growx, spanx");
    // content.add(entryPanel);
    // content.add(new JSeparator(), "growx, spanx");
    // content.add(quickConfigPanel);
    // content.add(new JSeparator(), "growx, spanx");
    // content.add(bottomPanel, "pushx,growx");
    // content.add(new JSeparator(), "growx, spanx");
    // content.add(exitPanel);
    //

    content.setBorder(BorderFactory.createLineBorder(content.getBackground().darker()));
    // Dimension size = new Dimension(getPreferredSize().width,
    // resizecomps.get(0).getPreferredSize().height);
    // for (AbstractButton c : resizecomps) {
    // c.setPreferredSize(size);
    // c.setMinimumSize(size);
    // c.setMaximumSize(size);
    // }
    setAlwaysOnTop(true);
    pack();
    hideThread =
        new Thread() {
          /*
           * this thread handles closing of popup because enter/exit/move events are too slow and can miss the exitevent
           */
          public void run() {
            while (true && hideThreadrunning) {
              try {
                sleep(500);
              } catch (InterruptedException e) {
              }
              if (enteredPopup && hideThreadrunning) {
                PointerInfo mouse = MouseInfo.getPointerInfo();
                Point current = TrayIconPopup.this.getLocation();
                if (mouse.getLocation().x < current.x
                    || mouse.getLocation().x > current.x + TrayIconPopup.this.getSize().width) {
                  dispose();
                  break;
                } else if (mouse.getLocation().y < current.y
                    || mouse.getLocation().y > current.y + TrayIconPopup.this.getSize().height) {
                  dispose();
                  break;
                }
              }
            }
          }
        };
    hideThreadrunning = true;
    hideThread.start();
  }
Пример #27
0
 public static boolean addAccount(final Account ac) throws DialogNoAnswerException {
   try {
     checkAccount(ac);
   } catch (DialogNoAnswerException e) {
     throw e;
   } catch (Throwable e) {
     Dialog.getInstance()
         .showExceptionDialog(
             _GUI.T.accountdialog_check_failed(), _GUI.T.accountdialog_check_failed_msg(), e);
   }
   AccountError error = ac.getError();
   String errorMessage = ac.getErrorString();
   if (StringUtils.isEmpty(errorMessage)) {
     AccountInfo ai = ac.getAccountInfo();
     if (ai != null) {
       errorMessage = ai.getStatus();
     }
   }
   if (error != null) {
     switch (error) {
       case PLUGIN_ERROR:
         if (StringUtils.isEmpty(errorMessage)) {
           errorMessage = _JDT.T.AccountController_updateAccountInfo_status_plugin_defect();
         }
         Dialog.getInstance().showMessageDialog(_GUI.T.accountdialog_check_invalid(errorMessage));
         return false;
       case EXPIRED:
         Dialog.getInstance()
             .showConfirmDialog(
                 0,
                 _GUI.T.accountdialog_check_expired_title(),
                 _GUI.T.accountdialog_check_expired(ac.getUser()),
                 null,
                 _GUI.T.accountdialog_check_expired_renew(),
                 null);
         AccountController.getInstance().addAccount(ac, false);
         return true;
       case TEMP_DISABLED:
         if (StringUtils.isEmpty(errorMessage)) {
           errorMessage = _GUI.T.accountdialog_check_failed();
         }
         Dialog.getInstance().showMessageDialog(_GUI.T.accountdialog_check_result(errorMessage));
         AccountController.getInstance().addAccount(ac, false);
         return true;
       default:
       case INVALID:
         if (StringUtils.isEmpty(errorMessage)) {
           errorMessage = _GUI.T.accountdialog_check_failed_msg();
         }
         Dialog.getInstance().showMessageDialog(_GUI.T.accountdialog_check_invalid(errorMessage));
         return false;
     }
   } else {
     String message = null;
     AccountInfo ai = ac.getAccountInfo();
     if (ai != null) {
       message = ai.getStatus();
     }
     if (StringUtils.isEmpty(message)) {
       message = _GUI.T.lit_yes();
     }
     Dialog.getInstance().showMessageDialog(_GUI.T.accountdialog_check_valid(message));
     AccountController.getInstance().addAccount(ac, false);
     return true;
   }
 }
 /**
  * set the name of this FilePackage
  * 
  * @param name
  */
 public void setName(String name) {
     if (StringUtils.isEmpty(name)) {
         name = _JDT._.controller_packages_defaultname();
     }
     this.name = name.trim();
 }
Пример #29
0
  @Override
  protected void setStringValue(final String value, final AbstractNode object) {
    if (StringUtils.isEmpty(value) || object == null) {
      return;
    }
    File oldPath = LinkTreeUtils.getDownloadDirectory(object);
    File newPath = LinkTreeUtils.getDownloadDirectory(value, null, object);
    if (oldPath.equals(newPath)) {
      /* both paths are same, so nothing to do */
      return;
    }
    if (object instanceof CrawledPackage) {
      LinkCollector.getInstance()
          .getQueue()
          .add(
              new QueueAction<Object, RuntimeException>(
                  org.appwork.utils.event.queue.Queue.QueuePriority.HIGH) {
                @Override
                protected Object run() {
                  ((CrawledPackage) object).setDownloadFolder(value);
                  return null;
                }
              });
      return;
    } else if (object instanceof CrawledLink) {
      final CrawledPackage p = ((CrawledLink) object).getParentNode();
      try {
        Dialog.getInstance()
            .showConfirmDialog(
                Dialog.LOGIC_DONOTSHOW_BASED_ON_TITLE_ONLY | Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN,
                _JDT.T.SetDownloadFolderAction_actionPerformed_(p.getName()),
                _JDT.T.SetDownloadFolderAction_msg(p.getName(), 1),
                null,
                _JDT.T.SetDownloadFolderAction_yes(),
                _JDT.T.SetDownloadFolderAction_no());
        LinkCollector.getInstance()
            .getQueue()
            .add(
                new QueueAction<Object, RuntimeException>(
                    org.appwork.utils.event.queue.Queue.QueuePriority.HIGH) {
                  @Override
                  protected Object run() {
                    p.setDownloadFolder(value);
                    return null;
                  }
                });
        return;
      } catch (DialogClosedException e) {
        return;
      } catch (DialogCanceledException e) {
        /* user clicked no */
      }

      final CrawledPackage pkg = new CrawledPackage();
      pkg.setExpanded(CFG_LINKCOLLECTOR.CFG.isPackageAutoExpanded());
      if (TYPE.NORMAL != p.getType()) {
        final String pkgName;
        if (object instanceof AbstractPackageNode) {
          pkgName =
              LinknameCleaner.cleanFileName(
                  object.getName(),
                  false,
                  true,
                  LinknameCleaner.EXTENSION_SETTINGS.REMOVE_KNOWN,
                  true);
        } else {
          pkgName =
              LinknameCleaner.cleanFileName(
                  object.getName(),
                  false,
                  true,
                  LinknameCleaner.EXTENSION_SETTINGS.REMOVE_ALL,
                  true);
        }
        pkg.setName(pkgName);
      } else {
        pkg.setName(p.getName());
      }
      pkg.setComment(p.getComment());
      pkg.setDownloadFolder(value);

      final java.util.List<CrawledLink> links = new ArrayList<CrawledLink>();
      links.add((CrawledLink) object);
      LinkCollector.getInstance()
          .getQueue()
          .add(
              new QueueAction<Object, RuntimeException>(
                  org.appwork.utils.event.queue.Queue.QueuePriority.HIGH) {

                @Override
                protected Object run() {
                  LinkCollector.getInstance().moveOrAddAt(pkg, links, -1);
                  return null;
                }
              });
    }
  }
Пример #30
0
 private void handleErrorsAPI() throws PluginException {
   final int code = getAPIStatuscode(this.br);
   String msg = PluginJSonUtils.getJsonValue(this.br, "msg");
   if (msg == null) {
     msg = "Unknown API error";
   }
   switch (code) {
     case api_status_all_ok:
       /* Everything ok */
       break;
     case 0:
       /* Fatal API error - this should never happen! */
       throw new PluginException(LinkStatus.ERROR_FATAL, msg);
     case 1:
       if ("de".equalsIgnoreCase(System.getProperty("user.language"))) {
         throw new PluginException(
             LinkStatus.ERROR_PREMIUM,
             "\r\nUngültiger Benutzername/Passwort!\r\nDu bist dir sicher, dass dein eingegebener Benutzername und Passwort stimmen? Versuche folgendes:\r\n1. Falls dein Passwort Sonderzeichen enthält, ändere es (entferne diese) und versuche es erneut!\r\n2. Gib deine Zugangsdaten per Hand (ohne kopieren/einfügen) ein.",
             PluginException.VALUE_ID_PREMIUM_DISABLE);
       } else {
         throw new PluginException(
             LinkStatus.ERROR_PREMIUM,
             "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.",
             PluginException.VALUE_ID_PREMIUM_DISABLE);
       }
     case 2:
       /* Folderlink does not exist --> This errorcode should only happen inside jd.plugins.decrypter.CatShareNetFolder !! */
       if (StringUtils.containsIgnoreCase(br.getURL(), "/login/")) {
         throw new PluginException(
             LinkStatus.ERROR_PREMIUM,
             "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.",
             PluginException.VALUE_ID_PREMIUM_DISABLE);
       }
       throw new PluginException(LinkStatus.ERROR_FATAL, msg);
     case 8:
       /* Daily downloadlimit reached (usually happens for premium accounts) */
       throw new PluginException(
           LinkStatus.ERROR_PREMIUM, msg, PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE);
     case 9:
       /* Not enough traffic available */
       throw new PluginException(
           LinkStatus.ERROR_PREMIUM, msg, PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE);
     case 10:
       /* WTF - "U didnt follow the rules!" */
       throw new PluginException(LinkStatus.ERROR_FATAL, "FATAL API error: " + msg);
     case 11:
       /* Wrong captcha input */
       throw new PluginException(LinkStatus.ERROR_CAPTCHA, msg);
     case 12:
       /* "You have to wait" --> (Free) limit reached */
       long wait = 3 * 60 * 60 * 1001l;
       final String wait_str = PluginJSonUtils.getJsonValue(this.br, "wait_time");
       /* wait_time can also be of type Boolean! */
       if (wait_str != null && wait_str.matches("\\d+")) {
         wait = 1001 * Long.parseLong(wait_str);
       }
       throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, msg, wait);
     case 13:
       /* File offline */
       throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND, msg);
     case 14:
       /*
        * Too many links (if someone tried to check more than X(see CheckLinks mass-linkchecker-function) links per request - this
        * should NEVER happen!
        */
       throw new PluginException(LinkStatus.ERROR_FATAL, msg);
     default:
       throw new PluginException(LinkStatus.ERROR_FATAL, msg);
   }
 }