Пример #1
0
  @SuppressWarnings("rawtypes")
  private PollingResultAPIStorable getDownloadProgress() {

    // get packageUUIDs who should be filled with download progress of the containing links e.g
    // because they are expanded in the
    // view
    List<Long> expandedPackageUUIDs = new ArrayList<Long>();
    if (!queryParams._getQueryParam("downloadProgress", List.class, new ArrayList()).isEmpty()) {
      List uuidsFromQuery =
          queryParams._getQueryParam("downloadProgress", List.class, new ArrayList());
      for (Object o : uuidsFromQuery) {
        try {
          expandedPackageUUIDs.add((Long) o);
        } catch (ClassCastException e) {
          continue;
        }
      }
    }

    PollingResultAPIStorable prs = new PollingResultAPIStorable();
    prs.setEventName("downloadProgress");

    List<PollingAPIFilePackageStorable> fpas = new ArrayList<PollingAPIFilePackageStorable>();

    for (FilePackage fp : dwd.getRunningFilePackages()) {
      PollingAPIFilePackageStorable fps = new PollingAPIFilePackageStorable(fp);
      fps.setSpeed(dwd.getDownloadSpeedbyFilePackage(fp));

      // if packages is expanded in view, current state of all running links inside the package
      if (expandedPackageUUIDs.contains(fp.getUniqueID().getID())) {
        boolean readL = fp.getModifyLock().readLock();
        try {
          for (DownloadLink dl : fp.getChildren()) {
            if (dwd.getRunningDownloadLinks().contains(dl.getDownloadLinkController())) {
              PollingAPIDownloadLinkStorable pdls = new PollingAPIDownloadLinkStorable(dl);
              fps.getLinks().add(pdls);
            }
          }
        } finally {
          fp.getModifyLock().readUnlock(readL);
        }
      }
      fpas.add(fps);
    }

    org.jdownloader.myjdownloader.client.json.JsonMap eventData =
        new org.jdownloader.myjdownloader.client.json.JsonMap();
    eventData.put("data", fpas);
    prs.setEventData(eventData);

    return prs;
  }
Пример #2
0
    /**
     * Create a new instance of StartDownloadsAction. This is a singleton class. Access the only existing instance by using
     * {@link #getInstance()}.
     */
    public StartDownloadsAction() {

        setIconKey("media-playback-start");
        setName(_JDT._.StartDownloadsAction_createTooltip_());
        DownloadWatchDog.getInstance().getEventSender().addListener(this, true);
        DownloadWatchDog.getInstance().notifyCurrentState(this);
        CFG_GUI.START_BUTTON_ACTION_IN_LINKGRABBER_CONTEXT.getEventSender().addListener(this, true);
        GUIEventSender.getInstance().addListener(this, true);
        onGuiMainTabSwitch(null, MainTabbedPane.getInstance().getSelectedView());

        setAccelerator(KeyEvent.VK_S);

    }
 protected void startUpdateTimer() {
   Timer currentTimer = updateTimer.get();
   if (currentTimer != null && currentTimer.isRunning()) {
     return;
   }
   if (DownloadWatchDog.getInstance().isRunning() == false) {
     return;
   }
   currentTimer =
       new Timer(
           1000,
           new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent e) {
               if (!(e.getSource() instanceof Timer)) {
                 return;
               }
               if (e.getSource() != updateTimer.get() || !isDisplayable()) {
                 Timer timer = ((Timer) e.getSource());
                 updateTimer.compareAndSet(timer, null);
                 timer.stop();
                 return;
               }
               fastDelayer.run();
             }
           });
   currentTimer.setRepeats(true);
   updateTimer.set(currentTimer);
   currentTimer.start();
 }
 @Override
 public synchronized void unregister(RemoteAPIEventsSender eventsAPI) {
   remoteEventSenders.remove(eventsAPI);
   if (remoteEventSenders.isEmpty()) {
     DownloadController.getInstance().removeListener(this);
     DownloadWatchDog.getInstance().getEventSender().removeListener(this);
   }
 }
 @Override
 public synchronized void register(RemoteAPIEventsSender eventsAPI) {
   boolean wasEmpty = remoteEventSenders.isEmpty();
   remoteEventSenders.add(eventsAPI);
   if (wasEmpty && remoteEventSenders.isEmpty() == false) {
     DownloadController.getInstance().addListener(this, true);
     DownloadWatchDog.getInstance().getEventSender().addListener(this, true);
   }
 }
Пример #6
0
    public void setHideIfDownloadsAreRunning(boolean showIfDownloadsAreRunning) {
        this.hideIfDownloadsAreRunning = showIfDownloadsAreRunning;

        if (isHideIfDownloadsAreRunning() && DownloadWatchDog.getInstance().isRunning()) {
            setVisible(false);
        } else {
            setVisible(true);
        }
    }
 private int getDownloads(AbstractNode value) {
     if (value instanceof DownloadLink) {
         SingleDownloadController dlc = ((DownloadLink) value).getDownloadLinkController();
         if (dlc != null) {
             DownloadInterface dli = ((DownloadLink) value).getDownloadInstance();
             if (dli != null) return 1;
         }
     } else if (value instanceof FilePackage) { return DownloadWatchDog.getInstance().getDownloadsbyFilePackage((FilePackage) value); }
     return 0;
 }
Пример #8
0
  private PollingResultAPIStorable getJDState() {
    PollingResultAPIStorable prs = new PollingResultAPIStorable();
    prs.setEventName("jdState");

    org.jdownloader.myjdownloader.client.json.JsonMap eventData =
        new org.jdownloader.myjdownloader.client.json.JsonMap();
    eventData.put("data", dwd.getStateMachine().getState().getLabel());

    prs.setEventData(eventData);
    return prs;
  }
  private void cleanup(DownloadLink dl2) {
    Set<SingleDownloadController> activeDownloads =
        DownloadWatchDog.getInstance().getRunningDownloadLinks();

    HashSet<DownloadLink> linksToProcess = new HashSet<DownloadLink>();
    for (SingleDownloadController dl : activeDownloads) {
      linksToProcess.add(dl.getDownloadLink());
    }
    linksToProcess.addAll(linksWithPluginProgress.values());

    for (Entry<Long, ChannelCollector> es : collectors.entrySet()) {
      es.getValue().cleanUp(linksToProcess);
    }
  }
Пример #10
0
    @Override
    public void onGuiMainTabSwitch(View oldView, final View newView) {
        if (newView instanceof LinkGrabberView && CFG_GUI.CFG.getStartButtonActionInLinkgrabberContext() == StartButtonAction.DISABLED) {
            new EDTRunner() {

                @Override
                protected void runInEDT() {
                    setEnabled(false);
                }
            };
        } else {
            DownloadWatchDog.getInstance().notifyCurrentState(this);
        }
    }
    public ConnectionColumn() {
        super(_GUI._.ConnectionColumn_ConnectionColumn(), null);
        panel = new RendererMigPanel("ins 0 0 0 0", "[]", "[grow,fill]");
        labels = new RenderLabel[DEFAULT_ICON_COUNT + 1];

        // panel.add(Box.createGlue(), "pushx,growx");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i <= DEFAULT_ICON_COUNT; i++) {
            labels[i] = new RenderLabel();
            // labels[i].setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1,
            // Color.RED));
            labels[i].setOpaque(false);
            labels[i].setBackground(null);
            if (sb.length() > 0) sb.append("1");
            sb.append("[18!]");
            panel.add(labels[i]);

        }
        dlWatchdog = DownloadWatchDog.getInstance();
        skipped = NewTheme.I().getIcon("skipped", 16);
        forced = NewTheme.I().getIcon("media-playback-start_forced", 16);
        resumeIndicator = NewTheme.I().getIcon("refresh", 16);
        directConnection = NewTheme.I().getIcon("modem", 16);
        proxyConnection = NewTheme.I().getIcon("proxy_rotate", 16);
        accountInUse = NewTheme.I().getIcon("users", 16);
        connections = NewTheme.I().getIcon("paralell", 16);
        panel.setLayout(new MigLayout("ins 0 0 0 0", sb.toString(), "[]"));
        // panel.add(Box.createGlue(), "pushx,growx");
        this.setRowSorter(new ExtDefaultRowSorter<AbstractNode>() {

            @Override
            public int compare(final AbstractNode o1, final AbstractNode o2) {
                final long l1 = getDownloads(o1);
                final long l2 = getDownloads(o2);
                if (l1 == l2) { return 0; }
                if (this.getSortOrderIdentifier() == ExtColumn.SORT_ASC) {
                    return l1 > l2 ? -1 : 1;
                } else {
                    return l1 < l2 ? -1 : 1;
                }
            }

        });

        resetRenderer();
    }
    public void configureRendererComponent(AbstractNode value, boolean isSelected, boolean hasFocus, int row, int column) {
        if (value instanceof DownloadLink) {
            DownloadLink dlLink = (DownloadLink) value;
            DownloadInterface dli = dlLink.getDownloadInstance();
            SingleDownloadController sdc = dlLink.getDownloadLinkController();
            int index = 0;
            if (dlLink.isSkipped()) {
                labels[index].setIcon(skipped);
                labels[index].setVisible(true);
                index++;
            }

            if (dlWatchdog.isLinkForced(dlLink)) {
                labels[index].setIcon(forced);
                labels[index].setVisible(true);
                index++;
            }
            if (dlLink.isResumeable()) {
                labels[index].setIcon(resumeIndicator);
                labels[index].setVisible(true);
                index++;
            }
            if (dli != null && sdc != null) {
                HTTPProxy proxy = sdc.getCurrentProxy();
                if (proxy != null && proxy.isRemote()) {
                    labels[index].setIcon(proxyConnection);
                    labels[index].setVisible(true);
                } else {
                    labels[index].setIcon(directConnection);
                    labels[index].setVisible(true);
                }
                index++;
                if (sdc.getAccount() != null) {
                    labels[index].setIcon(accountInUse);
                    labels[index].setVisible(true);
                    index++;
                }
                labels[index].setText("" + dli.getManagedConnetionHandler().size());
                labels[index].setIcon(connections);
                labels[index].setVisible(true);
            }
        }
    }
Пример #13
0
    public void actionPerformed(final ActionEvent e) {
        if (JDGui.getInstance().isCurrentPanel(Panels.LINKGRABBER)) {
            TaskQueue.getQueue().add(new QueueAction<Void, RuntimeException>() {

                @Override
                protected Void run() throws RuntimeException {
                    switch (CFG_GUI.CFG.getStartButtonActionInLinkgrabberContext()) {
                    case ADD_ALL_LINKS_AND_START_DOWNLOADS:
                        ConfirmLinksContextAction.confirmSelection(LinkGrabberTable.getInstance().getSelectionInfo(false, true), true, false, true, null, BooleanStatus.FALSE);

                        break;
                    case START_DOWNLOADS_ONLY:
                        DownloadWatchDog.getInstance().startDownloads();
                        break;
                    }
                    return null;
                }
            });
        } else {
            DownloadWatchDog.getInstance().startDownloads();
        }
    }
Пример #14
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;
  }
 public StartStopPauseBubbleSupport() {
     super(_GUI._.plugins_optional_JDLightTray_ballon_startpausestop2(), CFG_BUBBLE.BUBBLE_NOTIFY_START_PAUSE_STOP_ENABLED);
     DownloadWatchDog.getInstance().getEventSender().addListener(this, true);
 }
  @Override
  public void onDownloadControllerUpdatedData(DownloadLink dl, DownloadLinkProperty property) {

    if (property != null) {
      FilePackage parent = dl.getParentNode();
      HashMap<String, Object> dls = null;
      // [DATA_UPDATE.extractionStatus, DATA_UPDATE.finished, DATA_UPDATE.priority,
      // DATA_UPDATE.speed, DATA_UPDATE.url,
      // DATA_UPDATE.enabled, DATA_UPDATE.skipped, DATA_UPDATE.running, DATA_UPDATE.bytesLoaded,
      // DATA_UPDATE.eta,
      // DATA_UPDATE.maxResults, DATA_UPDATE.packageUUIDs, DATA_UPDATE.host, DATA_UPDATE.comment,
      // DATA_UPDATE.bytesTotal,
      // DATA_UPDATE.startAt, DATA_UPDATE.status]
      System.out.println("Property Change: " + property.getProperty());
      switch (property.getProperty()) {
        case ARCHIVE:
          break;
        case ARCHIVE_ID:
          // //archive properties changed;
          break;

        case AVAILABILITY:
          dls = new HashMap<String, Object>();
          dls.put("uuid", dl.getUniqueID().getID());
          dls.put("availability", property.getValue());
          fire(
              BASIC_EVENT.LINK_UPDATE.name() + ".availability",
              dls,
              BASIC_EVENT.LINK_UPDATE.name() + ".availability." + dl.getUniqueID().getID());
          break;
        case CHUNKS:
          break;
        case COMMENT:
          dls = new HashMap<String, Object>();
          dls.put("uuid", dl.getUniqueID().getID());
          dls.put("comment", property.getValue());
          fire(
              BASIC_EVENT.LINK_UPDATE.name() + ".comment",
              dls,
              BASIC_EVENT.LINK_UPDATE.name() + ".comment." + dl.getUniqueID().getID());
          break;
        case URL_CONTAINER:
        case URL_ORIGIN:
        case URL_REFERRER:
        case URL_CONTENT:
          dls = new HashMap<String, Object>();
          dls.put("uuid", dl.getUniqueID().getID());
          dls.put("url", dl.getView().getDisplayUrl());
          fire(
              BASIC_EVENT.LINK_UPDATE.name() + ".url",
              dls,
              BASIC_EVENT.LINK_UPDATE.name() + ".url." + dl.getUniqueID().getID());

          break;
        case CONDITIONAL_SKIPPED:
          pushStatus(dl);
          break;
        case DOWNLOAD_PASSWORD:
          break;
        case DOWNLOADSIZE:
          dls = new HashMap<String, Object>();
          dls.put("uuid", dl.getUniqueID().getID());
          dls.put("bytesTotal", property.getValue());
          fire(
              BASIC_EVENT.LINK_UPDATE.name() + ".bytesTotal",
              dls,
              BASIC_EVENT.LINK_UPDATE.name() + ".bytesTotal." + dl.getUniqueID().getID());
          break;
        case DOWNLOADSIZE_VERIFIED:
          dls = new HashMap<String, Object>();
          dls.put("uuid", dl.getUniqueID().getID());
          dls.put("bytesTotal", property.getValue());
          fire(
              BASIC_EVENT.LINK_UPDATE.name() + ".bytesTotal",
              dls,
              BASIC_EVENT.LINK_UPDATE.name() + ".bytesTotal." + dl.getUniqueID().getID());
          break;
        case DOWNLOAD_CONTROLLER:
          dls = new HashMap<String, Object>();
          dls.put("uuid", dl.getUniqueID().getID());
          dls.put("running", property.getValue() != null);
          fire(
              BASIC_EVENT.LINK_UPDATE.name() + ".running",
              dls,
              BASIC_EVENT.LINK_UPDATE.name() + ".running." + dl.getUniqueID().getID());
          dls = new HashMap<String, Object>();
          dls.put("uuid", parent.getUniqueID().getID());
          dls.put(
              "running",
              property.getValue() != null
                  || DownloadWatchDog.getInstance().hasRunningDownloads(parent));
          fire(
              BASIC_EVENT.PACKAGE_UPDATE.name() + ".running",
              dls,
              BASIC_EVENT.PACKAGE_UPDATE.name() + ".running." + parent.getUniqueID().getID());
          break;
        case ENABLED:
          dls = new HashMap<String, Object>();
          dls.put("uuid", dl.getUniqueID().getID());
          boolean enabled = dl.isEnabled();
          dls.put("enabled", enabled);
          fire(
              BASIC_EVENT.LINK_UPDATE.name() + ".enabled",
              dls,
              BASIC_EVENT.LINK_UPDATE.name() + ".enabled." + dl.getUniqueID().getID());
          dls = new HashMap<String, Object>();
          dls.put("uuid", parent.getUniqueID().getID());
          if (enabled == false) {
            final boolean readL = parent.getModifyLock().readLock();
            try {
              for (DownloadLink link : parent.getChildren()) {
                if (link.isEnabled()) {
                  enabled = true;
                  break;
                }
              }
            } finally {
              parent.getModifyLock().readUnlock(readL);
            }
          }
          dls.put("enabled", enabled);
          fire(
              BASIC_EVENT.PACKAGE_UPDATE.name() + ".enabled",
              dls,
              BASIC_EVENT.PACKAGE_UPDATE.name() + ".enabled." + parent.getUniqueID().getID());
          break;
        case EXTRACTION_STATUS:
          dls = new HashMap<String, Object>();
          dls.put("uuid", dl.getUniqueID().getID());
          ExtractionStatus es = dl.getExtractionStatus();
          dls.put("extractionStatus", es == null ? null : es.toString());
          fire(
              BASIC_EVENT.LINK_UPDATE.name() + ".extractionStatus",
              dls,
              BASIC_EVENT.LINK_UPDATE.name() + ".extractionStatus." + dl.getUniqueID().getID());

          pushStatus(dl);
          break;
        case FINAL_STATE:
          dls = new HashMap<String, Object>();
          dls.put("uuid", dl.getUniqueID().getID());
          dls.put("finished", (FinalLinkState.CheckFinished(dl.getFinalLinkState())));
          fire(
              BASIC_EVENT.LINK_UPDATE.name() + ".finished",
              dls,
              BASIC_EVENT.LINK_UPDATE.name() + ".finished." + dl.getUniqueID().getID());

          final FinalLinkState finalLinkState = dl.getFinalLinkState();

          pushStatus(dl);

          break;
        case LINKSTATUS:
          dls = new HashMap<String, Object>();
          dls.put("uuid", dl.getUniqueID().getID());
          dls.put("status", property.getValue());
          fire(
              BASIC_EVENT.LINK_UPDATE.name() + ".status",
              dls,
              BASIC_EVENT.LINK_UPDATE.name() + ".status." + dl.getUniqueID().getID());

          break;
        case MD5:
          break;
        case NAME:
          dls = new HashMap<String, Object>();
          dls.put("uuid", dl.getUniqueID().getID());
          dls.put("name", dl.getView().getDisplayName());
          fire(
              BASIC_EVENT.LINK_UPDATE.name() + ".name",
              dls,
              BASIC_EVENT.LINK_UPDATE.name() + ".name." + dl.getUniqueID().getID());

          break;
        case PLUGIN_PROGRESS:
          synchronized (linksWithPluginProgress) {
            if (dl.getPluginProgress() == null) {
              linksWithPluginProgress.remove(dl.getUniqueID().getID());
              pushDiff(dl);
              cleanup(dl);
            } else {
              linksWithPluginProgress.put(dl.getUniqueID().getID(), dl);
              updateExecuter(true);
            }
          }
          break;
        case PRIORITY:
          dls = new HashMap<String, Object>();
          dls.put("uuid", dl.getUniqueID().getID());
          dls.put(
              "priority",
              org.jdownloader.myjdownloader.client.bindings.PriorityStorable.valueOf(
                  dl.getPriorityEnum().name()));
          fire(
              BASIC_EVENT.LINK_UPDATE.name() + ".priority",
              dls,
              BASIC_EVENT.LINK_UPDATE.name() + ".priority." + dl.getUniqueID().getID());

          break;
        case RESET:
          dls = new HashMap<String, Object>();
          dls.put("uuid", dl.getUniqueID().getID());
          dls.put("reset", "true");
          fire(
              BASIC_EVENT.LINK_UPDATE.name() + ".reset",
              dls,
              BASIC_EVENT.LINK_UPDATE.name() + ".reset." + dl.getUniqueID().getID());

          dls = new HashMap<String, Object>();
          dls.put("uuid", dl.getUniqueID().getID());
          dls.put("reset", "true");
          fire(
              BASIC_EVENT.PACKAGE_UPDATE.name() + ".reset",
              dls,
              BASIC_EVENT.PACKAGE_UPDATE.name() + ".reset." + parent.getUniqueID().getID());
          break;
        case RESUMABLE:
          break;
        case SHA1:
          break;
        case SHA256:
          break;
        case SKIPPED:
          pushStatus(dl);
          dls = new HashMap<String, Object>();
          dls.put("uuid", dl.getUniqueID().getID());
          dls.put("skipped", property.getValue() != null);
          if (property.getValue() != null) {
            dls.put("skipreason", property.getValue().toString());
          }
          fire(
              BASIC_EVENT.LINK_UPDATE.name() + ".skipped",
              dls,
              BASIC_EVENT.LINK_UPDATE.name() + ".skipped." + dl.getUniqueID().getID());
          break;
        case SPEED_LIMIT:
          break;
        case URL_PROTECTION:
          break;
        case VARIANT:
          break;
        case VARIANTS:
          break;
        case VARIANTS_ENABLED:
          break;
      }
    }
    long newContentChangesCounter = DownloadController.getInstance().getContentChanges();
    if (newContentChangesCounter != this.contentChangesCounter) {
      // avoid dupes
      this.contentChangesCounter = newContentChangesCounter;
      fire(BASIC_EVENT.REFRESH_CONTENT.name(), null, BASIC_EVENT.REFRESH_CONTENT.name());
    }
    flushBuffer();
  }
Пример #17
0
    public SpeedlimitEditor(boolean b) {
        super(b);
        setLayout(new MigLayout("ins 0", "6[grow,fill][][]", "[]"));

        setOpaque(false);

        lbl = getLbl(_GUI._.SpeedlimitEditor_SpeedlimitEditor_(), NewTheme.I().getIcon("speed", 18));
        spinner = new SizeSpinner(new ConfigIntSpinnerModel(org.jdownloader.settings.staticreferences.CFG_GENERAL.DOWNLOAD_SPEED_LIMIT) {
            /**
             * 
             */
            private static final long serialVersionUID = -8549816276073605186L;

            @Override
            public void setValue(Object value) {
                if (DownloadWatchDog.getInstance().isPaused()) {
                    try {
                        org.jdownloader.settings.staticreferences.CFG_GENERAL.PAUSE_SPEED.setValue(((Number) value).intValue());
                    } catch (ValidationException e) {
                        java.awt.Toolkit.getDefaultToolkit().beep();
                    }
                }
                super.setValue(value);
            }
        }) {
            /**
             * 
             */
            private static final long serialVersionUID = 1L;

            @Override
            protected Object textToObject(String text) {
                if (text != null && text.trim().matches("^[0-9]+$")) {
                    return super.textToObject(text + " kb/s");
                }
                return super.textToObject(text);
            }

            protected String longToText(long longValue) {
                if (longValue <= 0) {
                    return _GUI._.SpeedlimitEditor_format(_AWU.T.literally_kibibyte("0"));
                } else {
                    return _GUI._.SpeedlimitEditor_format(SizeFormatter.formatBytes(longValue));
                }
            }
        };
        try {
            ((DefaultEditor) spinner.getEditor()).getTextField().addFocusListener(new FocusListener() {

                @Override
                public void focusLost(FocusEvent e) {
                }

                @Override
                public void focusGained(FocusEvent e) {
                    // requires invoke later!
                    SwingUtilities.invokeLater(new Runnable() {

                        @Override
                        public void run() {
                            ((DefaultEditor) spinner.getEditor()).getTextField().selectAll();
                        }
                    });

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            // too much fancy Casting.
        }
        add(lbl);
        add(checkbox = new ExtCheckBox(org.jdownloader.settings.staticreferences.CFG_GENERAL.DOWNLOAD_SPEED_LIMIT_ENABLED, lbl, spinner), "width 20!");
        DownloadWatchDog.getInstance().getEventSender().addListener(this, true);
        add(spinner, "height " + Math.max(spinner.getEditor().getPreferredSize().height, 20) + "!,width " + getEditorWidth() + "!");
        DownloadWatchDog.getInstance().notifyCurrentState(this);

    }
Пример #18
0
public class PollingAPIImpl implements PollingAPI {

  private DownloadWatchDog dwd = DownloadWatchDog.getInstance();
  private DownloadController dc = DownloadController.getInstance();
  private LinkCollector lc = LinkCollector.getInstance();
  private APIQuery queryParams;

  @Override
  public List<PollingResultAPIStorable> poll(APIQuery queryParams) {
    this.queryParams = queryParams;

    List<PollingResultAPIStorable> result = new ArrayList<PollingResultAPIStorable>();

    if (queryParams.containsKey("downloadProgress")) {
      result.add(getDownloadProgress());
    }
    if (queryParams.containsKey("jdState")) {
      result.add(getJDState());
    }
    if (queryParams.containsKey("linkGrabberState")) {
      result.add(getLinkGrabberState());
    }
    if (queryParams.containsKey("captchasWaiting")) {
      result.add(getCaptchasWaiting());
    }
    if (queryParams.containsKey("aggregatedNumbers")) {
      result.add(getAggregatedNumbers());
    }

    return result;
  }

  private PollingResultAPIStorable getAggregatedNumbers() {
    PollingResultAPIStorable prs = new PollingResultAPIStorable();
    prs.setEventName("aggregatedNumbers");
    org.jdownloader.myjdownloader.client.json.JsonMap eventData =
        new org.jdownloader.myjdownloader.client.json.JsonMap();
    eventData.put(
        "data",
        new AggregatedNumbersAPIStorable(
            new AggregatedNumbers(dc.getSelectionInfo()),
            new AggregatedCrawlerNumbers(lc.getSelectionInfo())));
    prs.setEventData(eventData);
    return prs;
  }

  @SuppressWarnings("rawtypes")
  private PollingResultAPIStorable getDownloadProgress() {

    // get packageUUIDs who should be filled with download progress of the containing links e.g
    // because they are expanded in the
    // view
    List<Long> expandedPackageUUIDs = new ArrayList<Long>();
    if (!queryParams._getQueryParam("downloadProgress", List.class, new ArrayList()).isEmpty()) {
      List uuidsFromQuery =
          queryParams._getQueryParam("downloadProgress", List.class, new ArrayList());
      for (Object o : uuidsFromQuery) {
        try {
          expandedPackageUUIDs.add((Long) o);
        } catch (ClassCastException e) {
          continue;
        }
      }
    }

    PollingResultAPIStorable prs = new PollingResultAPIStorable();
    prs.setEventName("downloadProgress");

    List<PollingAPIFilePackageStorable> fpas = new ArrayList<PollingAPIFilePackageStorable>();

    for (FilePackage fp : dwd.getRunningFilePackages()) {
      PollingAPIFilePackageStorable fps = new PollingAPIFilePackageStorable(fp);
      fps.setSpeed(dwd.getDownloadSpeedbyFilePackage(fp));

      // if packages is expanded in view, current state of all running links inside the package
      if (expandedPackageUUIDs.contains(fp.getUniqueID().getID())) {
        boolean readL = fp.getModifyLock().readLock();
        try {
          for (DownloadLink dl : fp.getChildren()) {
            if (dwd.getRunningDownloadLinks().contains(dl.getDownloadLinkController())) {
              PollingAPIDownloadLinkStorable pdls = new PollingAPIDownloadLinkStorable(dl);
              fps.getLinks().add(pdls);
            }
          }
        } finally {
          fp.getModifyLock().readUnlock(readL);
        }
      }
      fpas.add(fps);
    }

    org.jdownloader.myjdownloader.client.json.JsonMap eventData =
        new org.jdownloader.myjdownloader.client.json.JsonMap();
    eventData.put("data", fpas);
    prs.setEventData(eventData);

    return prs;
  }

  private PollingResultAPIStorable getJDState() {
    PollingResultAPIStorable prs = new PollingResultAPIStorable();
    prs.setEventName("jdState");

    org.jdownloader.myjdownloader.client.json.JsonMap eventData =
        new org.jdownloader.myjdownloader.client.json.JsonMap();
    eventData.put("data", dwd.getStateMachine().getState().getLabel());

    prs.setEventData(eventData);
    return prs;
  }

  private PollingResultAPIStorable getLinkGrabberState() {
    PollingResultAPIStorable prs = new PollingResultAPIStorable();
    prs.setEventName("linkGrabberState");

    LinkCollector lc = LinkCollector.getInstance();

    String status = "UNKNOWN";
    if (lc.getDefaultLinkChecker().isRunning()) {
      status = "RUNNING";
    } else {
      status = "IDLE";
    }

    org.jdownloader.myjdownloader.client.json.JsonMap eventData =
        new org.jdownloader.myjdownloader.client.json.JsonMap();
    eventData.put("data", status);
    prs.setEventData(eventData);

    return prs;
  }

  private CaptchaAPI captchaAPI = CaptchaAPISolver.getInstance();

  private PollingResultAPIStorable getCaptchasWaiting() {
    PollingResultAPIStorable prs = new PollingResultAPIStorable();
    prs.setEventName("captchasWaiting");

    org.jdownloader.myjdownloader.client.json.JsonMap eventData =
        new org.jdownloader.myjdownloader.client.json.JsonMap();
    eventData.put("data", captchaAPI.list());
    prs.setEventData(eventData);

    return prs;
  }
}