Search in sources :

Example 1 with ReturningTask

use of se.light.assembly64.model.ReturningTask in project assembly64fx by freabemania.

the class SearchViewFilesController method loopImages.

private void loopImages(Set<TargetAndPath> images) {
    final TargetAndPath[] imgs = images.toArray(new TargetAndPath[] {});
    final Image[] imgObjs = new Image[imgs.length];
    AtomicInteger ctr = new AtomicInteger();
    Runnable r = () -> {
        if (ctr.get() == imgs.length - 1) {
            ctr.set(0);
        } else {
            ctr.incrementAndGet();
        }
        if (imgObjs[ctr.get()] == null) {
            ReturningTask<Void> task2 = () -> {
                imgObjs[ctr.get()] = new Image(CachedImageService.getInstance().getImage(imgs[ctr.get()]));
                return null;
            };
            ExecutorUtil.executeAsyncWithRetry(task2);
        }
        FadeTransition fadeOutTransition = new FadeTransition(Duration.seconds(1), imageView);
        fadeOutTransition.setFromValue(1.0);
        fadeOutTransition.setToValue(0.0);
        fadeOutTransition.setOnFinished(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent arg0) {
                imageView.setImage(imgObjs[ctr.get()]);
                FadeTransition fadeInTransition = new FadeTransition(Duration.seconds(1), imageView);
                fadeInTransition.setFromValue(0.0);
                fadeInTransition.setToValue(1.0);
                fadeInTransition.setOnFinished(new EventHandler<ActionEvent>() {

                    @Override
                    public void handle(ActionEvent arg0) {
                        imageView.setImage(imgObjs[ctr.get()]);
                    }
                });
                fadeInTransition.play();
            }
        });
        fadeOutTransition.play();
    };
    future = Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(r, 0, 4, TimeUnit.SECONDS);
}
Also used : TargetAndPath(se.light.assembly64.model.TargetAndPath) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ReturningTask(se.light.assembly64.model.ReturningTask) FadeTransition(javafx.animation.FadeTransition) ActionEvent(javafx.event.ActionEvent) EventHandler(javafx.event.EventHandler) Image(javafx.scene.image.Image)

Example 2 with ReturningTask

use of se.light.assembly64.model.ReturningTask in project assembly64fx by freabemania.

the class SearchViewFilesController method downloadFilesAsync.

private void downloadFilesAsync(List<ContentEntry> selectedItems, String customPath) {
    CancelableTask cancelTask = CancelableTask.of();
    ProgressDBController controller = GuiUtils.showDialogOwnerNoWait("progressBarDbUpdate.fxml", "Progress", true, getStage(), new Object[] { selectedItems.size(), cancelTask, customPath + searchedItem.getCategoryShortName() + "/" + searchedItem.getName(), "Files were installed to " + customPath + searchedItem.getName() });
    ReturningTask<Void> task = () -> {
        int failureCtr = 0;
        for (ContentEntry selectedItem : selectedItems) {
            if (cancelTask.isCancelled()) {
                break;
            }
            try {
                downloadService.downloadItem(searchedItem.getId(), searchedItem.getCategory(), selectedItem.getId(), searchedItem.getName(), selectedItem.getName(), searchedItem.getCategoryShortName(), FILE_ACTION.DOWNLOAD, customPath);
            } catch (Exception e) {
                failureCtr++;
            }
            controller.setProgressLabel("Installing " + selectedItem.getName());
            controller.increaseProgress();
        }
        if (failureCtr == 0) {
            controller.progressDone();
        } else {
            controller.progressDone(failureCtr + " of " + selectedItems.size() + " could not be installed to " + customPath);
        }
        return null;
    };
    ExecutorUtil.executeAsyncWithRetry(task, 3);
}
Also used : ContentEntry(se.light.assembly64.model.ContentEntry) CancelableTask(se.light.assembly64.model.CancelableTask)

Example 3 with ReturningTask

use of se.light.assembly64.model.ReturningTask in project assembly64fx by freabemania.

the class SearchViewFilesController method init.

public void init(SearchResultItem searchedItem, ContentEntryInfo contentEntry, boolean fromSearch) {
    localDb = LocalDBService.getInstance();
    downloadService = DownloadArtifactsService.getInstance();
    playlistService = PlaylistService.getInstance();
    viceService = ViceService.getInstance();
    userService = UserService.getInstance();
    this.fromSearch = fromSearch;
    ReturningTask<Void> task = () -> {
        MetadataService metaDataSercice = MetadataService.getInstance();
        metadata = metaDataSercice.resolve(searchedItem);
        if (metadata.getUrl() == null) {
            toSourceButton.setVisible(false);
        }
        Platform.runLater(() -> {
            if (isNotEmpty(metadata.getEvent()) && isNotEmpty(metadata.getEventType())) {
                eventName.setText(capitalize(metadata.getEvent()));
                eventType.setText(capitalize(metadata.getEventType()));
                showEventName();
            }
            if (isNotEmpty(metadata.getReleaseDate())) {
                date.setText(metadata.getReleaseDate());
                showDate();
            }
            if (isNotEmpty(metadata.getName())) {
                releaseName.setText(capitalize(metadata.getName()));
                showReleaseName();
            }
            if (isNotEmpty(metadata.getGroup())) {
                group.setText(capitalize(metadata.getGroup()));
                showGroup();
            }
            if (isNotEmpty(metadata.getRating())) {
                rating.setText(metadata.getRating());
                showRating();
            }
            if (isNotEmpty(metadata.getPlace())) {
                place.setText("#" + metadata.getPlace());
                showPlace();
            }
            if (metadata.getImages().size() == 1) {
                try {
                    ReturningTask<Void> task2 = () -> {
                        TargetAndPath name = metadata.getImages().iterator().next();
                        fadeUpImage(new Image(CachedImageService.getInstance().getImage(name)));
                        return null;
                    };
                    ExecutorUtil.executeAsyncWithRetry(task2);
                } catch (Exception e) {
                    imageView.setImage(metaDataSercice.getNoPreview());
                }
            } else if (metadata.getImages().size() > 1) {
                loopImages(metadata.getImages());
            } else {
                fadeUpImage(metaDataSercice.getNoPreview());
            }
        });
        return null;
    };
    ExecutorUtil.executeAsyncWithRetry(task);
    this.searchedItem = searchedItem;
    name.setCellValueFactory(new PropertyValueFactory<ContentEntry, String>("name"));
    EventHandler<MouseEvent> mouseEventHandle = (MouseEvent event) -> {
        handleMouseClicked(event);
    };
    table.addEventHandler(MouseEvent.MOUSE_PRESSED, mouseEventHandle);
    table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    contentEntry.getContentEntry().sort((i1, i2) -> i1.getName().toLowerCase().compareTo(i2.getName().toLowerCase()));
    data.addAll(contentEntry.getContentEntry());
    table.setItems(data);
    getStage().setOnCloseRequest(event -> {
        closeImageLoop();
    });
    table.setOnKeyTyped(event -> {
        if (event.getCharacter().charAt(0) == Support.ENTER_KEY) {
            openFile(false);
        }
    });
    Executors.newSingleThreadExecutor().execute(() -> {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
        }
        Platform.runLater(() -> {
            GuiUtils.selectFirstInList(table);
        });
    });
}
Also used : TargetAndPath(se.light.assembly64.model.TargetAndPath) MouseEvent(javafx.scene.input.MouseEvent) ReturningTask(se.light.assembly64.model.ReturningTask) Image(javafx.scene.image.Image) MetadataService(se.light.assembly64.fx.mdresolve.MetadataService) ContentEntry(se.light.assembly64.model.ContentEntry)

Example 4 with ReturningTask

use of se.light.assembly64.model.ReturningTask in project assembly64fx by freabemania.

the class SidifyMainContoller method playSong.

private SidTune playSong(PlaylistEntry song) throws InterruptedException, SongNotAvailableException, SpecifyFileIdException {
    // Ugly, but needed for the nextsub to know
    SidTune sidTune = null;
    setIconPlaying(true);
    Platform.runLater(() -> nowPlaying.setText(song.getNameMasked()));
    try {
        int retries = 0;
        while (true) {
            try {
                File sid = Support.getSid(song);
                if (!sid.exists() && isOffline()) {
                    throw new SongNotAvailableException();
                } else if (!sid.exists()) {
                    downloadService.downloadTo(sid, song.getId(), song.getCategory(), song.getFileId());
                    Platform.runLater(() -> {
                        // update downloaded status
                        songlist.getColumns().get(0).setVisible(false);
                        songlist.getColumns().get(0).setVisible(true);
                    });
                }
                sidTune = sidPlayService.getSidTune(sid);
                sidPlayService.playSid(sidTune, getSongIndex(sidTune) + 1);
                break;
            } catch (Exception e) {
                if (e instanceof SpecifyFileIdException) {
                    throw e;
                } else if (retries > 3 || e instanceof SongNotAvailableException) {
                    throw e;
                }
                retries++;
            }
        }
        // load image async
        ReturningTask<Void> task = () -> {
            if (!Support.isOffline()) {
                Set<TargetAndPath> images = MetadataService.getInstance().resolve(song).getImages();
                if (images.size() > 0) {
                    imageView.setImage(new Image(imageCache.getImage(images.iterator().next())));
                }
            } else {
                imageView.setImage(MetadataService.getInstance().getNoPreview());
            }
            return null;
        };
        ExecutorUtil.executeAsyncWithRetry(task, 1);
    } catch (Exception e) {
        if (e instanceof SpecifyFileIdException) {
            throw new SpecifyFileIdException();
        }
        setIconPlaying(false);
        progressUpdater.stop();
        GenericMessageDialogController.withErrorProps("Sidify", "Sid seems to be broken!", true).showAndWait();
        throw new InterruptedException();
    }
    return sidTune;
}
Also used : SpecifyFileIdException(se.light.assembly64.model.SpecifyFileIdException) Set(java.util.Set) SongNotAvailableException(se.light.assembly64.model.SongNotAvailableException) Image(javafx.scene.image.Image) SidTune(libsidplay.sidtune.SidTune) File(java.io.File) SearchException(se.light.assembly64.model.SearchException) SongNotAvailableException(se.light.assembly64.model.SongNotAvailableException) SpecifyFileIdException(se.light.assembly64.model.SpecifyFileIdException)

Example 5 with ReturningTask

use of se.light.assembly64.model.ReturningTask in project assembly64fx by freabemania.

the class InstallationService method downloadLatestFromDatabase.

public void downloadLatestFromDatabase() {
    if (controller != null) {
        controller.getStage().show();
        return;
    }
    long nofDays = 0;
    File latestDateFile = new File(Support.removeEndingSlash(userService.getPrimaryInstallation().getPath()) + "/.db/latest");
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
    try {
        if (!latestDateFile.exists()) {
            nofDays = LocalDBService.getInstance().getMagAgeIndexAsLong();
            FileUtils.writeStringToFile(latestDateFile, formatter.format(LocalDate.now()));
        } else {
            nofDays = ChronoUnit.DAYS.between(LocalDate.parse(FileUtils.readFileToString(latestDateFile).substring(0, 8), formatter), LocalDate.now());
            // just to be safe
            nofDays++;
        }
    } catch (Exception e) {
        nofDays = MAX_CONTENT_AGE_DAYS;
        LOGGER.error("Error creating file", e);
    }
    String location = Support.removeEndingSlash(userService.getPrimaryInstallation().getPath()) + "/Misc/Latest-from-db";
    try {
        LOGGER.info("Fetching latest " + (int) nofDays + " days");
        List<SearchResultItem> items = SearchService.getInstance().search2("***", "***", "***", "***", "***", "***", "***", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "n", (int) nofDays);
        CancelableTask cancelTask = CancelableTask.of();
        controller = GuiUtils.showDialogOwnerNoWait("progressBarDbUpdate.fxml", "Progress", true, NullWindowOwner.of(), new Object[] { items.size(), cancelTask, location, "Latest content from database installed to " + location });
        ReturningTask<Void> task = () -> {
            for (SearchResultItem it : items) {
                if (cancelTask.isCancelled()) {
                    break;
                }
                List<ContentEntry> searchItems = SearchService.getInstance().getSearchItems(it.getId(), it.getCategory()).getContentEntry();
                try {
                    for (ContentEntry entry : searchItems) {
                        if (cancelTask.isCancelled()) {
                            break;
                        }
                        try {
                            DownloadArtifactsService.getInstance().downloadItem(it.getId(), it.getCategory(), entry.getId(), it.getName(), entry.getName(), it.getCategoryShortName(), FILE_ACTION.DOWNLOAD, location);
                        } catch (Exception e) {
                            LOGGER.error("Error during contentdownload {}", entry.getId());
                        }
                    }
                } catch (Exception e) {
                    LOGGER.error("Error during download {}", it.getId(), e);
                }
                controller.setProgressLabel("Installing " + it.getName());
                controller.increaseProgress();
            }
            controller.progressDone();
            Platform.runLater(() -> {
                controller.getStage().show();
                controller = null;
            });
            return null;
        };
        ExecutorUtil.executeAsyncWithRetry(task);
    } catch (Exception e) {
        LOGGER.error("Error during search of new items", e);
    }
}
Also used : SearchResultItem(se.light.assembly64.model.SearchResultItem) Support.getTodayDateAsBasicIsoString(se.light.assembly64.Support.getTodayDateAsBasicIsoString) IOException(java.io.IOException) ContentEntry(se.light.assembly64.model.ContentEntry) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File) DateTimeFormatter(java.time.format.DateTimeFormatter) CancelableTask(se.light.assembly64.model.CancelableTask)

Aggregations

File (java.io.File)7 Image (javafx.scene.image.Image)5 ReturningTask (se.light.assembly64.model.ReturningTask)5 ArrayList (java.util.ArrayList)4 Artifact (se.light.assembly64.model.Artifact)4 RandomAccessFile (java.io.RandomAccessFile)3 List (java.util.List)3 Set (java.util.Set)3 FadeTransition (javafx.animation.FadeTransition)3 ActionEvent (javafx.event.ActionEvent)3 EventHandler (javafx.event.EventHandler)3 ContextMenu (javafx.scene.control.ContextMenu)3 MouseEvent (javafx.scene.input.MouseEvent)3 ContentEntry (se.light.assembly64.model.ContentEntry)3 GuiLocation (se.light.assembly64.model.GuiLocation)3 PlatformInfoService (se.light.assembly64.service.PlatformInfoService)3 FileChannel (java.nio.channels.FileChannel)2 FileLock (java.nio.channels.FileLock)2 Collections (java.util.Collections)2 Optional (java.util.Optional)2