file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
MentionsTokensExtractor.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/viewmodel/tokenization/extractors/MentionsTokensExtractor.java
package moe.lyrebird.view.viewmodel.tokenization.extractors; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import moe.lyrebird.model.twitter.user.UserDetailsService; import moe.lyrebird.view.viewmodel.tokenization.Token; import moe.lyrebird.view.viewmodel.tokenization.TokensExtractor; import twitter4j.Status; @Component public class MentionsTokensExtractor implements TokensExtractor { private final UserDetailsService userDetailsService; @Autowired public MentionsTokensExtractor(final UserDetailsService userDetailsService) { this.userDetailsService = userDetailsService; } @Override public List<Token> extractTokens(final Status status) { return Arrays.stream(status.getUserMentionEntities()).map(mention -> new Token( "@" + mention.getText(), mention.getStart(), mention.getEnd(), Token.TokenType.CLICKABLE, () -> userDetailsService.openUserDetails(mention.getId()) )).collect(Collectors.toList()); } }
1,200
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
HashtagTokensExtractor.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/viewmodel/tokenization/extractors/HashtagTokensExtractor.java
package moe.lyrebird.view.viewmodel.tokenization.extractors; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import moe.lyrebird.view.viewmodel.tokenization.Token; import moe.lyrebird.view.viewmodel.tokenization.TokensExtractor; import moe.tristan.easyfxml.model.system.BrowserSupport; import twitter4j.Status; @Component public class HashtagTokensExtractor implements TokensExtractor { private static final String HASHTAG_SEARCH_BASE_URL = "https://twitter.com/hashtag/"; private final BrowserSupport browserSupport; @Autowired public HashtagTokensExtractor(final BrowserSupport browserSupport) { this.browserSupport = browserSupport; } @Override public List<Token> extractTokens(final Status status) { return Arrays.stream(status.getHashtagEntities()).map(hashtag -> new Token( "#" + hashtag.getText(), hashtag.getStart(), hashtag.getEnd(), Token.TokenType.CLICKABLE, () -> browserSupport.openUrl(HASHTAG_SEARCH_BASE_URL + hashtag.getText()) )).collect(Collectors.toList()); } }
1,275
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
UnmanagedUrlsTokensExtractor.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/viewmodel/tokenization/extractors/UnmanagedUrlsTokensExtractor.java
package moe.lyrebird.view.viewmodel.tokenization.extractors; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import moe.lyrebird.model.util.URLMatcher; import moe.lyrebird.view.viewmodel.tokenization.Token; import moe.lyrebird.view.viewmodel.tokenization.TokensExtractor; import moe.tristan.easyfxml.model.system.BrowserSupport; import twitter4j.Status; import twitter4j.URLEntity; /** * This class uses {@link URLMatcher} to process URLs in the tweet content that are not considered * by Twitter to be proper {@link URLEntity}s (like embedded media links) but still need to be clickable by * the end-user. */ @Component public class UnmanagedUrlsTokensExtractor implements TokensExtractor { private final BrowserSupport browserSupport; @Autowired public UnmanagedUrlsTokensExtractor(final BrowserSupport browserSupport) { this.browserSupport = browserSupport; } /** * @return The list of {@link Token}s that cannot be built from {@link Status#getURLEntities()} alone. */ @Override public List<Token> extractTokens(final Status status) { final String statusText = status.getText(); final URLEntity[] managedUrlEntities = status.getURLEntities(); String unamanagedText = statusText; for (final URLEntity processedEntity : managedUrlEntities) { unamanagedText = unamanagedText.replaceAll(processedEntity.getURL(), ""); } return URLMatcher.findAllUrlsWithPosition(unamanagedText).stream().map( urlWithPos -> new Token( urlWithPos._1, urlWithPos._2, urlWithPos._3, Token.TokenType.CLICKABLE, () -> browserSupport.openUrl(urlWithPos._1) ) ).collect(Collectors.toList()); } }
1,978
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
ManagedUrlsTokensExtractor.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/viewmodel/tokenization/extractors/ManagedUrlsTokensExtractor.java
package moe.lyrebird.view.viewmodel.tokenization.extractors; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import moe.lyrebird.view.viewmodel.tokenization.Token; import moe.lyrebird.view.viewmodel.tokenization.TokensExtractor; import moe.tristan.easyfxml.model.system.BrowserSupport; import twitter4j.Status; import twitter4j.URLEntity; @Component public class ManagedUrlsTokensExtractor implements TokensExtractor { private static final Logger LOGGER = LoggerFactory.getLogger(ManagedUrlsTokensExtractor.class); private final BrowserSupport browserSupport; @Autowired public ManagedUrlsTokensExtractor(final BrowserSupport browserSupport) { this.browserSupport = browserSupport; } /** * Tokenizes a Tweet based off of {@link Status#getURLEntities()}. * * @param status The status to tokenize * * @return A list of {@link Token}s. */ @Override public List<Token> extractTokens(final Status status) { return Arrays.stream(status.getURLEntities()).map(this::linkOfEntity).collect(Collectors.toList()); } /** * Helper method to generate a URL-specialized {@link Token}. * * @param urlEntity The entity to map as a Token * * @return A token that correctly this entity. */ private Token linkOfEntity(final URLEntity urlEntity) { LOGGER.trace("Tokenizing URLEntity {}", urlEntity); return new Token( urlEntity.getDisplayURL(), urlEntity.getStart(), urlEntity.getEnd(), Token.TokenType.CLICKABLE, () -> browserSupport.openUrl(urlEntity.getExpandedURL()) ); } }
1,900
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
ClickableText.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/viewmodel/javafx/ClickableText.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.viewmodel.javafx; import java.util.function.Consumer; import javafx.scene.text.Text; public final class ClickableText extends Text { public <T> ClickableText(final T element, final Consumer<T> onClicked) { super(String.valueOf(element)); setOnMouseClicked(e -> onClicked.accept(element)); getStyleClass().setAll("clickable-hyperlink"); } public <T> ClickableText(final T element, final Runnable onClicked) { super(String.valueOf(element)); setOnMouseClicked(e -> onClicked.run()); getStyleClass().setAll("clickable-hyperlink"); } }
1,440
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
StageAware.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/viewmodel/javafx/StageAware.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.viewmodel.javafx; import javafx.stage.Stage; /** * This interface indicates that any controller implementing it needs to know its embedding {@link Stage}. */ public interface StageAware { /** * Sets the embedding stage. * * @param embeddingStage The stage to feed the controller. */ default void setStage(final Stage embeddingStage) { // do nothing by default } }
1,248
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
Clipping.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/viewmodel/javafx/Clipping.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.viewmodel.javafx; import javafx.scene.shape.Circle; import javafx.scene.shape.Rectangle; /** * This is a helper class for a few clipping helper methods to make rounded corners rectangles or circles. */ public final class Clipping { private Clipping() { } /** * Builds a clip-ready rounded corners {@link Rectangle} that is square. * * @param side The size of the size of this square * @param roundedRadius The radius of this square's corners rounding * * @return A square with the given side size and rounded corners with the given radius */ public static Rectangle getSquareClip(final double side, final double roundedRadius) { final Rectangle rectangle = new Rectangle(); rectangle.setHeight(side); rectangle.setWidth(side); rectangle.setArcWidth(roundedRadius); rectangle.setArcHeight(roundedRadius); return rectangle; } /** * Builds a clip-ready {@link Circle} with a specific radius and specific center position. * * @param radius The radius of this circle. * @param centerX The horizontal position for this circle's center * @param centerY The vertical position for this circle's center * * @return A circle with the given radius and center position */ private static Circle getCircleClip(final double radius, final double centerX, final double centerY) { final Circle clip = new Circle(radius); clip.setCenterX(centerX); clip.setCenterY(centerY); return clip; } /** * Builds a clip-ready {@link Circle} with a specific radius and its center moved so that it is moved to the * top-left of its container node. * * @param radius The radius of the circle in question * * @return A circle with the given radius */ public static Circle getCircleClip(final double radius) { return getCircleClip(radius, radius, radius); } }
2,823
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
ImageResources.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/assets/ImageResources.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.assets; import java.util.Objects; import javafx.scene.image.Image; /** * This enumeration contains some static images used either as placeholders or fallback. */ public enum ImageResources { BACKGROUND_DARK_1PX("background-dark-1px.png"), CONTROLBAR_ADD_USER("controlbar_icon_add_user.png"), GENERAL_USER_AVATAR_DARK("general_icon_user_avatar_dark.png"), GENERAL_USER_AVATAR_LIGHT("general_icon_user_avatar_light.png"), GENERAL_LOADING_REMOTE("general_icon_loading_remote.png"), TWEETPANE_RETWEET_OFF("tweetpane_icon_retweet_off.png"), TWEETPANE_RETWEET_ON("tweetpane_icon_retweet_on.png"), TWEETPANE_LIKE_OFF("tweetpane_icon_heart_off.png"), TWEETPANE_LIKE_ON("tweetpane_icon_heart_on.png"), TWEETPANE_VIDEO("tweetpane_icon_video.png"); private final Image backingImage; /** * @param path The path of the resource relative to src/main/resources/assets/img */ ImageResources(final String path) { this.backingImage = loadImage(path); } /** * This method is the load call executed on constructor call to preload the images on startup. * * @param path The path from the enum member declaration. * * @return The underlying image that will actually get used. */ private static Image loadImage(final String path) { final ClassLoader cl = ImageResources.class.getClassLoader(); final String finalPath = "assets/img/" + path; return new Image(Objects.requireNonNull(cl.getResourceAsStream(finalPath))); } public Image getImage() { return backingImage; } }
2,457
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
MediaResources.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/assets/MediaResources.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.assets; import javafx.scene.media.Media; import java.net.URI; import java.net.URISyntaxException; import java.util.Objects; /** * This enum contains media resources used either as placeholder or fallback. */ public enum MediaResources { LOADING_REMOTE_GTARD("loading-gtard.mp4"); private final Media media; /** * @param path The path of the resource relative to src/main/resources/assets/video */ MediaResources(final String path) { try { this.media = loadMediaFile(path); } catch (final URISyntaxException e) { throw new IllegalStateException("Could not load required temporary media resource!", e); } } /** * This method is the load call executed on constructor call to preload the media on startup. * * @param path The path from the enum member declaration. * * @return The underlying media that will actually get used. */ private static Media loadMediaFile(final String path) throws URISyntaxException { final String root = "assets/video/"; final ClassLoader classLoader = MediaResources.class.getClassLoader(); final URI mediaUri = Objects.requireNonNull(classLoader.getResource(root + path)).toURI(); return new Media(mediaUri.toString()); } public Media getMedia() { return media; } }
2,208
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
MediaEmbeddingService.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/screens/media/MediaEmbeddingService.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.screens.media; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Component; import moe.lyrebird.view.screens.media.handlers.direct.DirectImageHandler; import moe.lyrebird.view.screens.media.handlers.twitter.TwitterMediaEntity; import moe.lyrebird.view.screens.media.handlers.twitter.TwitterVideoHandler; import twitter4j.MediaEntity; import twitter4j.Status; import javafx.scene.Node; import javafx.scene.image.ImageView; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * This service is in charge of creating preview {@link ImageView} for embedded images (and media in general) that a * tweet can contain. * * @see moe.lyrebird.view.screens.media.handlers * @see TwitterMediaEntity */ @Component public class MediaEmbeddingService { public static final double EMBEDDED_MEDIA_RECTANGLE_SIDE = 64.0; public static final double EMBEDDED_MEDIA_RECTANGLE_CORNER_RADIUS = 10.0; private final DirectImageHandler directPhotoHandler; private final TwitterVideoHandler twitterVideoHandler; public MediaEmbeddingService( final DirectImageHandler directPhotoHandler, final TwitterVideoHandler twitterVideoHandler ) { this.directPhotoHandler = directPhotoHandler; this.twitterVideoHandler = twitterVideoHandler; } /** * Generates a cached list of appropriate nodes (usually {@link ImageView}) to preview the embedded media in the * given status. * * @param status The status to generate previews for. * * @return The list of previews generated. Called only once for every tweet since it is cached via {@link * Cacheable}. */ public List<Node> embed(final Status status) { return Arrays.stream(status.getMediaEntities()) .filter(TwitterMediaEntity::isSupported) .map(this::embedOne) .collect(Collectors.toList()); } /** * Generates preview for a single Twitter-side {@link MediaEntity} matching it against the {@link * TwitterMediaEntity} enumeration. * * @param entity The entity whose preview will be generated. * * @return The preview for the given entity. * * @throws IllegalArgumentException when an unsupported entity is given since it should only be called on valid * entities. */ private Node embedOne(final MediaEntity entity) { switch (TwitterMediaEntity.fromTwitterType(entity.getType())) { case PHOTO: return directPhotoHandler.handleMedia(entity.getMediaURLHttps()); case VIDEO: case ANIMATED_GIF: return twitterVideoHandler.handleMedia(entity.getVideoVariants()); case UNMANAGED: default: throw new IllegalArgumentException("Twitter type " + entity.getType() + " is not supported!"); } } }
3,839
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
EmbeddedMediaViewHelper.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/screens/media/handlers/EmbeddedMediaViewHelper.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.screens.media.handlers; import static moe.lyrebird.view.screens.media.MediaEmbeddingService.EMBEDDED_MEDIA_RECTANGLE_CORNER_RADIUS; import static moe.lyrebird.view.screens.media.MediaEmbeddingService.EMBEDDED_MEDIA_RECTANGLE_SIDE; import java.util.Arrays; import java.util.function.Consumer; import org.springframework.stereotype.Component; import javafx.application.Platform; import javafx.scene.Node; import javafx.scene.image.ImageView; import javafx.scene.layout.Pane; import javafx.scene.shape.Rectangle; import moe.lyrebird.view.assets.ImageResources; import moe.lyrebird.view.screens.media.MediaEmbeddingService; import moe.lyrebird.view.screens.media.display.MediaScreenController; import moe.lyrebird.view.viewmodel.javafx.Clipping; import moe.tristan.easyfxml.EasyFxml; import moe.tristan.easyfxml.api.FxmlComponent; import moe.tristan.easyfxml.model.exception.ExceptionHandler; import moe.tristan.easyfxml.model.fxml.FxmlLoadResult; import moe.tristan.easyfxml.util.Stages; /** * This helper class offers basic common setup for creation and management of the previews. (i.e. creation of the miniature, opening of the detailed view etc.) * * @see MediaEmbeddingService * @see moe.lyrebird.view.screens.media.handlers */ @Component public class EmbeddedMediaViewHelper { private final EasyFxml easyFxml; public EmbeddedMediaViewHelper(final EasyFxml easyFxml) { this.easyFxml = easyFxml; } /** * @param displayScreen The screen to open on click on the miniature * @param imageResource The image to display as miniature * @param mediaUrl The media that will be displayed in the detailed screen on click * @param andThen Possible post-processing on the view (for async load purposes) * * @return A media preview {@link ImageView} with given parameters. */ @SafeVarargs public final Pane makeWrapperWithIcon( final FxmlComponent displayScreen, final ImageResources imageResource, final String mediaUrl, final Consumer<ImageView>... andThen ) { final Pane containerPane = new Pane(); containerPane.setPrefWidth(EMBEDDED_MEDIA_RECTANGLE_SIDE); containerPane.setPrefHeight(EMBEDDED_MEDIA_RECTANGLE_SIDE); final ImageView imageView = new ImageView(); imageView.setImage(imageResource.getImage()); imageView.setFitWidth(EMBEDDED_MEDIA_RECTANGLE_SIDE); imageView.setFitHeight(EMBEDDED_MEDIA_RECTANGLE_SIDE); final Rectangle clipRectangle = Clipping.getSquareClip( EMBEDDED_MEDIA_RECTANGLE_SIDE, EMBEDDED_MEDIA_RECTANGLE_CORNER_RADIUS ); clipRectangle.layoutXProperty().bind(imageView.layoutXProperty()); clipRectangle.layoutYProperty().bind(imageView.layoutYProperty()); imageView.setClip(clipRectangle); containerPane.getChildren().setAll(imageView); Arrays.stream(andThen).forEach(op -> op.accept(imageView)); setOnOpen(displayScreen, containerPane, mediaUrl); return containerPane; } /** * Binds the click on the preview to opening of the detailed view. * * @param screenToLoad The {@link FxmlComponent} to open on click * @param clickable The preview node * @param mediaUrl The URL of the media that will be displayed */ private void setOnOpen(final FxmlComponent screenToLoad, final Node clickable, final String mediaUrl) { clickable.setOnMouseClicked(e -> { final FxmlLoadResult<Pane, MediaScreenController> mediaScreenLoad = loadMediaScreen(screenToLoad, mediaUrl); final Pane mediaScreenPane = mediaScreenLoad.getNode().getOrElseGet(ExceptionHandler::fromThrowable); final MediaScreenController mediaScreenController = mediaScreenLoad.getController().get(); Stages.stageOf(mediaUrl, mediaScreenPane).thenAcceptAsync(stage -> { mediaScreenController.setStage(stage); stage.show(); }, Platform::runLater); }); } /** * Opens the given media screen type for a given media. * * @param mediaDisplayScreen The screen to open this media with * @param mediaUrl The media to display * * @return The {@link FxmlLoadResult} with preconfigured controller. */ private FxmlLoadResult<Pane, MediaScreenController> loadMediaScreen( final FxmlComponent mediaDisplayScreen, final String mediaUrl ) { return easyFxml.load( mediaDisplayScreen, Pane.class, MediaScreenController.class ).afterControllerLoaded(msc -> msc.handleMedia(mediaUrl)); } }
5,594
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
MediaHandler.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/screens/media/handlers/MediaHandler.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.screens.media.handlers; import javafx.scene.layout.Pane; /** * A media handler is responsible for mapping a given media to a miniature of it that will open a detailed view on * click. * * @param <T> The input type for the media in question */ public interface MediaHandler<T> { Pane handleMedia(final T mediaSource); }
1,170
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
DirectVideoHandler.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/screens/media/handlers/direct/DirectVideoHandler.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.screens.media.handlers.direct; import org.springframework.stereotype.Component; import javafx.scene.layout.Pane; import moe.lyrebird.view.screens.media.display.video.VideoScreenComponent; import moe.lyrebird.view.screens.media.handlers.EmbeddedMediaViewHelper; import moe.lyrebird.view.screens.media.handlers.base.VideoHandler; /** * Implementation of {@link VideoHandler} for videos already in URL form. * <p> * Simple pass-through. */ @Component public class DirectVideoHandler extends VideoHandler<String> { public DirectVideoHandler(EmbeddedMediaViewHelper embeddedMediaViewHelper, VideoScreenComponent videoScreenComponent) { super(embeddedMediaViewHelper, videoScreenComponent); } @Override public Pane handleMedia(final String mediaSource) { return handleMediaSource(mediaSource); } }
1,677
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
DirectImageHandler.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/screens/media/handlers/direct/DirectImageHandler.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.screens.media.handlers.direct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javafx.scene.layout.Pane; import moe.lyrebird.model.io.AsyncIO; import moe.lyrebird.view.screens.media.display.photo.ImageScreenComponent; import moe.lyrebird.view.screens.media.handlers.EmbeddedMediaViewHelper; import moe.lyrebird.view.screens.media.handlers.base.ImageHandler; /** * Implementation of {@link ImageHandler} for images already in URL form. * <p> * Simple pass-through. */ @Component public class DirectImageHandler extends ImageHandler<String> { @Autowired public DirectImageHandler(AsyncIO asyncIO, EmbeddedMediaViewHelper embeddedMediaViewHelper, ImageScreenComponent imageScreenComponent) { super(asyncIO, embeddedMediaViewHelper, imageScreenComponent); } @Override public Pane handleMedia(final String mediaSource) { return handleMediaSource(mediaSource); } }
1,819
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
ImageHandler.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/screens/media/handlers/base/ImageHandler.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.screens.media.handlers.base; import static moe.lyrebird.view.screens.media.MediaEmbeddingService.EMBEDDED_MEDIA_RECTANGLE_SIDE; import javafx.application.Platform; import javafx.scene.image.ImageView; import javafx.scene.layout.Pane; import moe.lyrebird.model.io.AsyncIO; import moe.lyrebird.view.assets.ImageResources; import moe.lyrebird.view.screens.media.display.photo.ImageScreenComponent; import moe.lyrebird.view.screens.media.handlers.EmbeddedMediaViewHelper; import moe.lyrebird.view.screens.media.handlers.MediaHandler; /** * Basic implementation for image handlers that can extract a URL to preview. * * @param <T> The input type for the original image description type * * @see EmbeddedMediaViewHelper */ public abstract class ImageHandler<T> implements MediaHandler<T> { private final AsyncIO asyncIO; private final EmbeddedMediaViewHelper embeddedMediaViewHelper; private final ImageScreenComponent imageScreenComponent; public ImageHandler( AsyncIO asyncIO, EmbeddedMediaViewHelper embeddedMediaViewHelper, ImageScreenComponent imageScreenComponent ) { this.asyncIO = asyncIO; this.embeddedMediaViewHelper = embeddedMediaViewHelper; this.imageScreenComponent = imageScreenComponent; } /** * Implementation side of the miniature creation once the image has been mapped to an URL. * * @param imageUrl The image described as an URL * * @return An {@link ImageView} with asynchronously loaded image miniature as display image with by default (until the asynchronous call is done) a static * image ({@link ImageResources#GENERAL_LOADING_REMOTE}). This {@link ImageView} will open a {@link ImageScreenComponent} screen displaying the media when * it is clicked. */ protected Pane handleMediaSource(final String imageUrl) { return embeddedMediaViewHelper.makeWrapperWithIcon( imageScreenComponent, ImageResources.GENERAL_LOADING_REMOTE, imageUrl, imageView -> loadMiniatureAsync(imageView, imageUrl) ); } /** * Helper for loading the asynchronous image inside the preview {@link ImageView}. * * @param imageView The preview {@link ImageView}. * @param actualImageUrl The media's URL compliant description */ private void loadMiniatureAsync(final ImageView imageView, final String actualImageUrl) { asyncIO.loadImageMiniature(actualImageUrl, EMBEDDED_MEDIA_RECTANGLE_SIDE, EMBEDDED_MEDIA_RECTANGLE_SIDE) .thenAcceptAsync(imageView::setImage, Platform::runLater); } }
3,508
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
VideoHandler.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/screens/media/handlers/base/VideoHandler.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.screens.media.handlers.base; import javafx.scene.image.ImageView; import javafx.scene.layout.Pane; import moe.lyrebird.view.assets.ImageResources; import moe.lyrebird.view.screens.media.display.video.VideoScreenComponent; import moe.lyrebird.view.screens.media.handlers.EmbeddedMediaViewHelper; import moe.lyrebird.view.screens.media.handlers.MediaHandler; /** * Basic implementation for video media handlers that can extract a URL to preview. * * @param <T> The input type for the original video description type * * @see EmbeddedMediaViewHelper */ public abstract class VideoHandler<T> implements MediaHandler<T> { private final EmbeddedMediaViewHelper embeddedMediaViewHelper; private final VideoScreenComponent videoScreenComponent; public VideoHandler(EmbeddedMediaViewHelper embeddedMediaViewHelper, VideoScreenComponent videoScreenComponent) { this.embeddedMediaViewHelper = embeddedMediaViewHelper; this.videoScreenComponent = videoScreenComponent; } /** * Implementation side of the miniature creation once the video has been mapped to an URL. * * @param mediaUrl The video described as an URL * * @return An {@link ImageView} with a static image ({@link ImageResources#TWEETPANE_VIDEO}). This {@link ImageView} * will open a {@link VideoScreenComponent} screen displaying the media when it is clicked. */ protected Pane handleMediaSource(final String mediaUrl) { return embeddedMediaViewHelper.makeWrapperWithIcon( videoScreenComponent, ImageResources.TWEETPANE_VIDEO, mediaUrl ); } }
2,489
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
TwitterVideoHandler.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/screens/media/handlers/twitter/TwitterVideoHandler.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.screens.media.handlers.twitter; import java.util.Arrays; import java.util.Comparator; import org.springframework.stereotype.Component; import javafx.scene.layout.Pane; import moe.lyrebird.view.screens.media.display.video.VideoScreenComponent; import moe.lyrebird.view.screens.media.handlers.EmbeddedMediaViewHelper; import moe.lyrebird.view.screens.media.handlers.base.VideoHandler; import twitter4j.MediaEntity; /** * Twitter-specific implementation of the {@link VideoHandler}. */ @Component public class TwitterVideoHandler extends VideoHandler<MediaEntity.Variant[]> { public TwitterVideoHandler(EmbeddedMediaViewHelper embeddedMediaViewHelper, VideoScreenComponent videoScreenComponent) { super(embeddedMediaViewHelper, videoScreenComponent); } /** * Takes a media entity's variants array and returns the best quality available. * * @param mediaSource The source media variants * * @return The best quality one's URL among those */ @Override public Pane handleMedia(final MediaEntity.Variant[] mediaSource) { final var best = Arrays.stream(mediaSource).max(Comparator.comparingInt(MediaEntity.Variant::getBitrate)); final MediaEntity.Variant bestVersion = best.orElseThrow(); return handleMediaSource(bestVersion.getUrl()); } }
2,168
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
TwitterMediaEntity.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/screens/media/handlers/twitter/TwitterMediaEntity.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.screens.media.handlers.twitter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import twitter4j.MediaEntity; import java.util.Arrays; /** * Contains matchers for the currently known media entity types from Twitter. */ public enum TwitterMediaEntity { PHOTO("photo"), ANIMATED_GIF("animated_gif"), VIDEO("video"), UNMANAGED("<UNMANAGED_TYPE>"); private static final Logger LOG = LoggerFactory.getLogger(TwitterMediaEntity.class); private final String codeName; TwitterMediaEntity(final String codeName) { this.codeName = codeName; } /** * @return The Twitter-side entity type code. */ public String getCodeName() { return codeName; } /** * Maps a given Twitter-side {@link MediaEntity} to a Lyrebird-side {@link TwitterMediaEntity}. * * @param actualCode The twitter code of a {@link MediaEntity}. * * @return The matching Lyrebird-side entity or {@link #UNMANAGED}. */ public static TwitterMediaEntity fromTwitterType(final String actualCode) { return Arrays.stream(values()) .filter(type -> type.getCodeName().equals(actualCode)) .findAny() .orElse(UNMANAGED); } /** * Tests whether a given entity has an associated embedding mapping inside of Lyrebird. * * @param entity The entity to test * * @return true if and only if calling {@link #fromTwitterType(String)} does not yield {@link #UNMANAGED}. */ public static boolean isSupported(final MediaEntity entity) { final boolean supported = fromTwitterType(entity.getType()) != UNMANAGED; if (!supported) { LOG.warn("Unsupported twitter media entity, skipping. Twitter type was : [{}]", entity.getType()); } return supported; } }
2,709
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
MediaScreenController.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/screens/media/display/MediaScreenController.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.screens.media.display; import moe.tristan.easyfxml.api.FxmlController; import moe.lyrebird.view.viewmodel.javafx.StageAware; import java.net.URL; /** * Simple interface for controllers for individual media display. */ public interface MediaScreenController extends FxmlController, StageAware { /** * Loads the given media and displays it appropriately given the implementation and media type. * * @param mediaUrl The URL of the media type as a String. Always use {@link URL#toExternalForm()} for it if you have * a URL-type object to begin with. */ void handleMedia(final String mediaUrl); /** * Enforces media controllers to think about properly sizing their stage to fit as well as possible the embedded * media. */ void bindViewSizeToParent(); }
1,667
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
VideoScreenComponent.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/screens/media/display/video/VideoScreenComponent.java
package moe.lyrebird.view.screens.media.display.video; import org.springframework.stereotype.Component; import moe.tristan.easyfxml.api.FxmlComponent; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.api.FxmlFile; @Component public class VideoScreenComponent implements FxmlComponent { @Override public FxmlFile getFile() { return () -> "VideoScreen.fxml"; } @Override public Class<? extends FxmlController> getControllerClass() { return VideoScreenController.class; } }
544
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
VideoScreenController.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/screens/media/display/video/VideoScreenController.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.screens.media.display.video; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import moe.lyrebird.model.io.AsyncIO; import moe.lyrebird.view.assets.MediaResources; import moe.lyrebird.view.screens.media.display.MediaScreenController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javafx.application.Platform; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.fxml.FXML; import javafx.scene.layout.AnchorPane; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.scene.media.MediaView; import javafx.stage.Stage; import java.util.concurrent.CompletableFuture; /** * This class manages a video's detailed view */ @Component @Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE) public class VideoScreenController implements MediaScreenController { private static final Logger LOG = LoggerFactory.getLogger(VideoScreenController.class); private static final Media TEMPORARY_MEDIA_LOAD = MediaResources.LOADING_REMOTE_GTARD.getMedia(); @FXML private AnchorPane container; @FXML private MediaView mediaView; private final AsyncIO asyncIO; private final ObjectProperty<Media> mediaProperty; @Autowired public VideoScreenController(final AsyncIO asyncIO) { this.asyncIO = asyncIO; mediaProperty = new SimpleObjectProperty<>(TEMPORARY_MEDIA_LOAD); } @Override public void initialize() { bindViewSizeToParent(); mediaView.setSmooth(true); mediaProperty.addListener((o, temp, actual) -> openMediaPlayer()); } @Override public void handleMedia(final String mediaUrl) { asyncIO.loadMedia(mediaUrl).thenAcceptAsync(mediaProperty::setValue, Platform::runLater); } @Override public void bindViewSizeToParent() { mediaView.fitHeightProperty().bind(container.heightProperty()); mediaView.fitWidthProperty().bind(container.widthProperty()); } /** * Opens a backing {@link MediaPlayer} for the embedded video. */ private void openMediaPlayer() { CompletableFuture.supplyAsync(() -> new MediaPlayer(mediaProperty.getValue())) .thenAcceptAsync(mediaPlayer -> { mediaPlayer.setAutoPlay(true); mediaPlayer.setOnEndOfMedia(mediaPlayer::stop); mediaView.setOnMouseClicked(e -> onClickHandler(mediaPlayer)); mediaView.setMediaPlayer(mediaPlayer); }, Platform::runLater); } /** * Sets up reasonable settings for {@link MediaPlayer} behavior when it comes to user interactions. * <p> * Basically the same as any wide-usage video player with replaying when un-pausing after a video ended. * * @param mediaPlayer The media player to setup. */ private static void onClickHandler(final MediaPlayer mediaPlayer) { final MediaPlayer.Status playerStatus = mediaPlayer.statusProperty().get(); switch (playerStatus) { case READY: mediaPlayer.play(); break; case PAUSED: mediaPlayer.play(); break; case PLAYING: mediaPlayer.pause(); break; case STOPPED: mediaPlayer.play(); break; case HALTED: case UNKNOWN: case STALLED: case DISPOSED: LOG.warn("Media player was already disposed! [status = {}]", playerStatus); break; default: LOG.error("UNKNOWN MEDIA PLAYER STATUS ! [status = {}]", playerStatus); } } /** * Makes sure that this media player is stopped and disposed when the user closes the stage for this screen. * * @param embeddingStage The stage for which to listen to close requests */ @Override public void setStage(final Stage embeddingStage) { embeddingStage.setOnCloseRequest(e -> { final MediaPlayer mediaPlayer = mediaView.getMediaPlayer(); if (mediaPlayer != null) { mediaPlayer.stop(); mediaPlayer.dispose(); } }); } }
5,370
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
ImageScreenController.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/screens/media/display/photo/ImageScreenController.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.screens.media.display.photo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javafx.beans.property.Property; import javafx.beans.property.SimpleObjectProperty; import javafx.fxml.FXML; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; import moe.lyrebird.model.io.CachedMedia; import moe.lyrebird.view.assets.ImageResources; import moe.lyrebird.view.screens.media.display.MediaScreenController; /** * This controller if managing detailed views of images. */ @Component @Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE) public class ImageScreenController implements MediaScreenController { @FXML private AnchorPane container; @FXML private ImageView photoImageView; private final CachedMedia cachedMedia; private final Property<Image> imageProp = new SimpleObjectProperty<>(ImageResources.GENERAL_LOADING_REMOTE.getImage()); @Autowired public ImageScreenController(final CachedMedia cachedMedia) { this.cachedMedia = cachedMedia; imageProp.addListener((observable, oldValue, newValue) -> bindViewSizeToParent()); } @Override public void initialize() { photoImageView.imageProperty().bind(imageProp); } @Override public void handleMedia(final String mediaUrl) { imageProp.setValue(cachedMedia.loadImage(mediaUrl)); } @Override public void bindViewSizeToParent() { container.setPrefWidth(imageProp.getValue().getWidth()); container.setPrefHeight(imageProp.getValue().getHeight()); photoImageView.fitHeightProperty().bind(container.heightProperty()); photoImageView.fitWidthProperty().bind(container.widthProperty()); } }
2,773
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
ImageScreenComponent.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/screens/media/display/photo/ImageScreenComponent.java
package moe.lyrebird.view.screens.media.display.photo; import org.springframework.stereotype.Component; import moe.tristan.easyfxml.api.FxmlComponent; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.api.FxmlFile; @Component public class ImageScreenComponent implements FxmlComponent { @Override public FxmlFile getFile() { return () -> "ImageScreen.fxml"; } @Override public Class<? extends FxmlController> getControllerClass() { return ImageScreenController.class; } }
544
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
LoginScreenController.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/screens/login/LoginScreenController.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.screens.login; import java.net.URL; import java.util.Optional; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.Separator; import javafx.scene.control.TextField; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import moe.lyrebird.model.sessions.SessionManager; import moe.lyrebird.model.twitter.twitter4j.TwitterHandler; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.model.exception.ExceptionHandler; import moe.tristan.easyfxml.model.system.BrowserSupport; import moe.tristan.easyfxml.util.Buttons; import io.vavr.Tuple2; import twitter4j.auth.AccessToken; import twitter4j.auth.RequestToken; /** * This class is responsible for managing the login screen. * <p> * It is built around a multi-step process to guide the user better. * <p> * It is also made {@link Lazy} in the case the user is already authenticated and does not want to add another account * in the current run of the application. * <p> * It is made {@link ConfigurableBeanFactory#SCOPE_PROTOTYPE} because there might be multiple login going on at the * same time. */ @Lazy @Component @Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE) public class LoginScreenController implements FxmlController { private static final Logger LOG = LoggerFactory.getLogger(LoginScreenController.class); @FXML private VBox step1Box; @FXML private Button openLoginUrlButton; @FXML private VBox step2Box; @FXML private TextField pinCodeField; @FXML private Button validatePinCodeButton; @FXML private VBox step3Box; @FXML private Label loggedUsernameLabel; @FXML private Separator separator1; @FXML private Separator separator2; private final BrowserSupport browserSupport; private final TwitterHandler twitterHandler; private final SessionManager sessionManager; public LoginScreenController( final BrowserSupport browserSupport, final TwitterHandler twitterHandler, final SessionManager sessionManager ) { this.browserSupport = browserSupport; this.twitterHandler = twitterHandler; this.sessionManager = sessionManager; } @Override public void initialize() { validatePinCodeButton.setDisable(true); Stream.of(step1Box, step2Box, step3Box, separator1, separator2).forEach(node -> setNodeVisibility(node, false)); uiStep1(); Buttons.setOnClick(openLoginUrlButton, this::startNewSession); this.pinCodeField.textProperty().addListener((o, prev, cur) -> pinCodeTextListener(cur)); } /** * Start the first step of the process where the user clicks a link to open an oauth on Twitter's side. */ private void uiStep1() { setNodeVisibility(step1Box, true); } /** * Starts the second step of the process where the user must copy an OTP in a field to authenticate the OAuth * login. */ private void uiStep2() { Stream.of(separator1, step2Box).forEach(node -> setNodeVisibility(node, true)); } /** * Ends the process by checking the OTP against the OAuth request and tells the user whether authentication was * successful in the end. */ private void uiStep3() { Stream.of(separator2, step3Box).forEach(node -> setNodeVisibility(node, true)); } /** * Initiates the OAuth request workflow by requesting an OAuth {@link RequestToken} from Twitter. */ private void startNewSession() { final Tuple2<URL, RequestToken> tokenUrl = this.twitterHandler.newSession(); LOG.info("Got authorization URL {}, opening the browser!", tokenUrl._1); browserSupport.openUrl(tokenUrl._1); this.openLoginUrlButton.setDisable(true); Buttons.setOnClick(validatePinCodeButton, () -> this.registerPinCode(tokenUrl._2)); uiStep2(); } /** * Tries the given OTP (pin code) against Twitter's API. * * @param requestToken the OAuth request to test the OTP against */ private void registerPinCode(final RequestToken requestToken) { final Optional<AccessToken> success = this.twitterHandler.registerAccessToken( requestToken, this.pinCodeField.getText() ); if (success.isPresent()) { sessionManager.addNewSession(this.twitterHandler); final AccessToken token = success.get(); this.loggedUsernameLabel.setText(token.getScreenName()); validatePinCodeButton.setDisable(true); pinCodeField.setDisable(true); pinCodeField.setEditable(false); uiStep3(); } else { ExceptionHandler.displayExceptionPane( "Authentication Error", "Could not authenticate you!", new Exception("No token could be used.") ); } } /** * Checks whether anything was entered so the user does not mistakenly try to validate the authentication without * prior entering of the Twitter OTP. * * @param currentPin The current pin inside the {@link #pinCodeField}. */ private void pinCodeTextListener(final String currentPin) { try { Integer.parseInt(currentPin); validatePinCodeButton.setDisable(false); } catch (final NumberFormatException e) { validatePinCodeButton.setDisable(true); } } /** * Helper method to manage step box visibility into the containing {@link HBox} by taking advantage of JavaFX layout * computation process. * * @param node The node targeted * @param visible Whether to make it visible or not */ private static void setNodeVisibility(final Node node, final boolean visible) { node.setVisible(visible); node.setManaged(visible); } }
7,183
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
LoginScreenComponent.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/screens/login/LoginScreenComponent.java
package moe.lyrebird.view.screens.login; import org.springframework.stereotype.Component; import moe.tristan.easyfxml.api.FxmlComponent; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.api.FxmlFile; @Component public class LoginScreenComponent implements FxmlComponent { @Override public FxmlFile getFile() { return () -> "Login.fxml"; } @Override public Class<? extends FxmlController> getControllerClass() { return LoginScreenController.class; } }
524
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
CreditsScreenController.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/screens/credits/CreditsScreenController.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.screens.credits; import java.net.URL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Lazy; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import javafx.beans.property.ReadOnlyListWrapper; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Hyperlink; import javafx.scene.image.ImageView; import moe.lyrebird.model.credits.CreditsService; import moe.lyrebird.model.credits.objects.CreditedWork; import moe.lyrebird.model.io.CachedMedia; import moe.lyrebird.model.twitter.user.UserDetailsService; import moe.lyrebird.view.components.cells.CreditsCell; import moe.lyrebird.view.components.credits.CreditController; import moe.lyrebird.view.viewmodel.javafx.Clipping; import moe.tristan.easyfxml.model.components.listview.ComponentListViewFxmlController; import moe.tristan.easyfxml.model.system.BrowserSupport; import moe.tristan.easyfxml.util.Buttons; import twitter4j.User; /** * This class manages with Credits/About window. * <p> * It is configured as {@link Lazy} mostly because we do not want to initialize it if the user doesn't ever load the * about window. * * @see CreditsService * @see ComponentListViewFxmlController * @see CreditsCell * @see CreditController */ @Lazy @Component public class CreditsScreenController extends ComponentListViewFxmlController<CreditedWork> { private static final Logger LOG = LoggerFactory.getLogger(CreditsScreenController.class); @FXML private Button licenseButton; @FXML private Button sourceCodeButton; @FXML private Button knownIssuesButton; @FXML private ImageView applicationAuthorProfilePicture; @FXML private Hyperlink applicationAuthorProfileLink; private final CreditsService creditsService; private final BrowserSupport browserSupport; private final UserDetailsService userDetailsService; private final Environment environment; private final CachedMedia cachedMedia; @Autowired public CreditsScreenController( final ApplicationContext context, final CreditsService creditsService, final BrowserSupport browserSupport, final UserDetailsService userDetailsService, final Environment environment, final CachedMedia cachedMedia ) { super(context, CreditsCell.class); this.creditsService = creditsService; this.browserSupport = browserSupport; this.userDetailsService = userDetailsService; this.environment = environment; this.cachedMedia = cachedMedia; } @Override public void initialize() { super.initialize(); LOG.debug("Loading credits..."); listView.itemsProperty().bind(new ReadOnlyListWrapper<>(creditsService.creditedWorks())); bindButtonToOpenHrefEnvProperty(licenseButton, "credits.license"); bindButtonToOpenHrefEnvProperty(sourceCodeButton, "credits.sourceCode"); bindButtonToOpenHrefEnvProperty(knownIssuesButton, "credits.knownIssues"); displayApplicationAuthor(); } private void displayApplicationAuthor() { applicationAuthorProfileLink.setOnAction(e -> userDetailsService.openUserDetails("_tristan971_")); userDetailsService.findUser("_tristan971_") .map(User::getProfileImageURLHttps) .map(cachedMedia::loadImage) .onSuccess(applicationAuthorProfilePicture::setImage) .andThen(() -> applicationAuthorProfilePicture.setClip(Clipping.getCircleClip(16.0))); } /** * Small setup to make repository-related resources clickable. * * @param button The button to make open an URL * @param prop The name of the URL in application.properties */ private void bindButtonToOpenHrefEnvProperty(final Button button, final String prop) { final URL actualUrl = environment.getRequiredProperty(prop, URL.class); Buttons.setOnClick(button, () -> browserSupport.openUrl(actualUrl)); } }
5,112
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
CreditScreenComponent.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/screens/credits/CreditScreenComponent.java
package moe.lyrebird.view.screens.credits; import org.springframework.stereotype.Component; import moe.tristan.easyfxml.api.FxmlComponent; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.api.FxmlFile; @Component public class CreditScreenComponent implements FxmlComponent { @Override public FxmlFile getFile() { return () -> "Credits.fxml"; } @Override public Class<? extends FxmlController> getControllerClass() { return CreditsScreenController.class; } }
531
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
RootScreenController.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/screens/root/RootScreenController.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.screens.root; import java.util.Map; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.scene.layout.BorderPane; import javafx.scene.layout.Pane; import moe.lyrebird.view.components.controlbar.ControlBarComponent; import moe.lyrebird.view.components.notifications.NotificationPaneComponent; import moe.tristan.easyfxml.EasyFxml; import moe.tristan.easyfxml.api.FxmlComponent; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.model.exception.ExceptionHandler; /** * The RootViewController manages the location of content on the root view scene. */ @Component public class RootScreenController implements FxmlController { private static final Logger LOG = LoggerFactory.getLogger(RootScreenController.class); @FXML private BorderPane contentPane; private final EasyFxml easyFxml; private final ControlBarComponent controlBarComponent; private final NotificationPaneComponent notificationPaneComponent; private final Map<FxmlComponent, Pane> cachedComponents = new ConcurrentHashMap<>(); public RootScreenController( EasyFxml easyFxml, ControlBarComponent controlBarComponent, NotificationPaneComponent notificationPaneComponent ) { this.easyFxml = easyFxml; this.controlBarComponent = controlBarComponent; this.notificationPaneComponent = notificationPaneComponent; } @Override public void initialize() { loadControlBar(); loadNotificationPane(); } /** * Loads up the {@link ControlBarComponent} on the left side of the {@link BorderPane} which is the main container for the main view. */ private void loadControlBar() { LOG.debug("Initializing control bar..."); loadComponentAsync(controlBarComponent).thenAcceptAsync( this.contentPane::setLeft, Platform::runLater ); } /** * Loads up the {@link NotificationPaneComponent} on the top side of the {@link BorderPane} which is the main container for the main view. */ private void loadNotificationPane() { LOG.debug("Initializing notification pane..."); loadComponentAsync(notificationPaneComponent).thenAcceptAsync( this.contentPane::setTop, Platform::runLater ); } /** * Helper function to load a given {@link FxmlComponent} as center node for the {@link BorderPane} which is the main container for the root view. * * @param fxComponent The fxComponent to load. */ public void setContent(FxmlComponent fxComponent) { loadComponentAsync(fxComponent).thenAcceptAsync(this.contentPane::setCenter, Platform::runLater); } private CompletableFuture<Pane> loadComponentAsync(final FxmlComponent fxComponent) { return CompletableFuture.supplyAsync(() -> { LOG.info("Switching content of root pane to {}", fxComponent); final Pane loadedPane = cachedComponents.computeIfAbsent(fxComponent, this::loadComponentSynchronous); return Objects.requireNonNull(loadedPane); }, Platform::runLater); } private Pane loadComponentSynchronous(final FxmlComponent fxComponent) { return this.easyFxml .load(fxComponent) .getNode() .getOrElseGet(ExceptionHandler::fromThrowable); } }
4,489
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
RootScreenComponent.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/screens/root/RootScreenComponent.java
package moe.lyrebird.view.screens.root; import org.springframework.stereotype.Component; import moe.tristan.easyfxml.api.FxmlComponent; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.api.FxmlFile; @Component public class RootScreenComponent implements FxmlComponent { @Override public FxmlFile getFile() { return () -> "RootView.fxml"; } @Override public Class<? extends FxmlController> getControllerClass() { return RootScreenController.class; } }
524
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
NewTweetController.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/screens/newtweet/NewTweetController.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.screens.newtweet; import static io.vavr.API.$; import static io.vavr.API.Case; import static io.vavr.API.Match; import static javafx.scene.paint.Color.BLUE; import static javafx.scene.paint.Color.GREEN; import static javafx.scene.paint.Color.ORANGE; import static javafx.scene.paint.Color.RED; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javafx.application.Platform; import javafx.beans.binding.BooleanBinding; import javafx.beans.property.ListProperty; import javafx.beans.property.Property; import javafx.beans.property.SimpleListProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.FXCollections; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextArea; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCodeCombination; import javafx.scene.input.KeyCombination; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.FileChooser; import javafx.stage.FileChooser.ExtensionFilter; import javafx.stage.Stage; import moe.lyrebird.model.sessions.SessionManager; import moe.lyrebird.model.twitter.observables.Mentions; import moe.lyrebird.model.twitter.observables.Timeline; import moe.lyrebird.model.twitter.refresh.RateLimited; import moe.lyrebird.model.twitter.services.NewTweetService; import moe.lyrebird.model.twitter.util.TwitterMediaExtensionFilter; import moe.lyrebird.view.components.tweet.TweetPaneComponent; import moe.lyrebird.view.components.tweet.TweetPaneController; import moe.lyrebird.view.viewmodel.javafx.Clipping; import moe.lyrebird.view.viewmodel.javafx.StageAware; import moe.tristan.easyfxml.EasyFxml; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.model.exception.ExceptionHandler; import moe.tristan.easyfxml.util.Buttons; import twitter4j.Status; import twitter4j.User; import twitter4j.UserMentionEntity; /** * This controller manages the new tweet view. * <p> * It is made {@link Lazy} in case the user never uses it. * <p> * It is also made {@link ConfigurableBeanFactory#SCOPE_PROTOTYPE} in case multiple new tweet screens are open at the same time. */ @Lazy @Component @Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE) public class NewTweetController implements FxmlController, StageAware { private static final Logger LOG = LoggerFactory.getLogger(NewTweetController.class); private static final double MEDIA_PREVIEW_IMAGE_SIZE = 32.0; @FXML private BorderPane container; @FXML private Button sendButton; @FXML private Button pickMediaButton; @FXML private HBox mediaPreviewBox; @FXML private TextArea tweetTextArea; @FXML private Label charactersLeft; private final NewTweetService newTweetService; private final TwitterMediaExtensionFilter twitterMediaExtensionFilter; private final EasyFxml easyFxml; private final SessionManager sessionManager; private final Timeline timeline; private final Mentions mentions; private final TweetPaneComponent tweetPaneComponent; private final ListProperty<File> mediasToUpload; private final Property<Stage> embeddingStage; private final Property<Status> inReplyStatus = new SimpleObjectProperty<>(); public NewTweetController( NewTweetService newTweetService, TwitterMediaExtensionFilter extensionFilter, EasyFxml easyFxml, SessionManager sessionManager, Timeline timeline, Mentions mentions, TweetPaneComponent tweetPaneComponent ) { this.newTweetService = newTweetService; this.twitterMediaExtensionFilter = extensionFilter; this.easyFxml = easyFxml; this.sessionManager = sessionManager; this.timeline = timeline; this.mentions = mentions; this.tweetPaneComponent = tweetPaneComponent; this.mediasToUpload = new SimpleListProperty<>(FXCollections.observableList(new ArrayList<>())); this.embeddingStage = new SimpleObjectProperty<>(null); } @Override public void initialize() { LOG.debug("New tweet stage ready."); enableTweetLengthCheck(); Buttons.setOnClick(sendButton, this::send); Buttons.setOnClick(pickMediaButton, this::openMediaAttachmentsFilePicker); final BooleanBinding mediasNotEmpty = mediasToUpload.emptyProperty().not(); mediaPreviewBox.visibleProperty().bind(mediasNotEmpty); mediaPreviewBox.managedProperty().bind(mediasNotEmpty); inReplyStatus.addListener((o, prev, cur) -> prefillMentionsForReply()); sendOnControlEnter(); } /** * @param embeddingStage The stage that will be closed on successful publication of the tweet */ @Override public void setStage(final Stage embeddingStage) { this.embeddingStage.setValue(embeddingStage); } /** * If this tweet is in reply to another, we set proper display of the previous one because it looks good. * * @param repliedTweet the tweet ({@link Status} to which this is in reply to */ public void setInReplyToTweet(final Status repliedTweet) { LOG.debug("Set new tweet stage to embed status : {}", repliedTweet.getId()); inReplyStatus.setValue(repliedTweet); easyFxml.load(tweetPaneComponent, Pane.class, TweetPaneController.class) .afterControllerLoaded(tpc -> { tpc.embeddedPropertyProperty().setValue(true); tpc.updateWithValue(repliedTweet); }) .getNode() .recover(ExceptionHandler::fromThrowable) .onSuccess(this.container::setTop); } /** * In case this is a reply we pre-fill the content field with the appropriate mentions. */ private void prefillMentionsForReply() { final User currentUser = sessionManager.currentSessionProperty().getValue().getTwitterUser().get(); final Status replied = inReplyStatus.getValue(); final StringBuilder prefillText = new StringBuilder(); prefillText.append('@').append(replied.getUser().getScreenName()); Arrays.stream(replied.getUserMentionEntities()) .map(UserMentionEntity::getScreenName) .filter(username -> !username.equals(currentUser.getScreenName())) .forEach(username -> prefillText.append(' ').append('@').append(username)); prefillText.append(' '); final String prefill = prefillText.toString(); tweetTextArea.setText(prefill); tweetTextArea.positionCaret(prefill.length()); } /** * Makes the character counter colorful depending on the current amount typed relative to the maximum Twitter allows. */ private void enableTweetLengthCheck() { tweetTextArea.textProperty().addListener((observable, oldValue, newValue) -> { final Color color = Match(newValue.length()).of( Case($(tweetLen -> tweetLen < 250), GREEN), Case($(tweetLen -> tweetLen >= 250 && tweetLen < 280), ORANGE), Case($(tweetLen -> tweetLen > 280), RED), Case($(tweetLen -> tweetLen == 280), BLUE) ); Platform.runLater(() -> { charactersLeft.setText(Integer.toString(newValue.length())); charactersLeft.setTextFill(color); }); }); } /** * Dynamically either sends a normal tweet or a reply depending on whether the controller was used to prepare a "normal" new tweet or a reply (i.e. if there * was a value set for {@link #inReplyStatus}. */ private void send() { Match(inReplyStatus.getValue()).of( Case($(Objects::nonNull), this::sendReply), Case($(Objects::isNull), this::sendTweet) ).thenRunAsync( () -> Stream.of(timeline, mentions).forEach(RateLimited::refresh), CompletableFuture.delayedExecutor(2, TimeUnit.SECONDS) ); } /** * Sends a tweet using the {@link NewTweetService}. */ private CompletionStage<Void> sendTweet() { Stream.of(tweetTextArea, sendButton, pickMediaButton).forEach(ctr -> ctr.setDisable(true)); return newTweetService.sendTweet(tweetTextArea.getText(), mediasToUpload) .thenAcceptAsync(status -> { LOG.info("Tweeted status : {} [{}]", status.getId(), status.getText()); this.embeddingStage.getValue().hide(); }, Platform::runLater); } /** * Sends a reply using the {@link NewTweetService}. */ private CompletionStage<Void> sendReply() { final long inReplyToId = inReplyStatus.getValue().getId(); Stream.of(tweetTextArea, sendButton, pickMediaButton).forEach(ctr -> ctr.setDisable(true)); return newTweetService.sendReply(tweetTextArea.getText(), mediasToUpload, inReplyToId) .thenAcceptAsync(status -> { LOG.info( "Tweeted reply to {} : {} [{}]", inReplyToId, status.getId(), status.getText() ); this.embeddingStage.getValue().hide(); }, Platform::runLater); } /** * Opens a file picker for choosing attachments for the currently made tweet and registers the asynchronous choice result in {@link #mediasToUpload}. */ private void openMediaAttachmentsFilePicker() { pickMediaButton.setDisable(true); this.openFileChooserForMedia() .thenAcceptAsync( this::mediaFilesChosen, Platform::runLater ); } /** * Opens a {@link FileChooser} to pick attachments from with a pre-made {@link ExtensionFilter} for the allowed media types. * * @return an asynchronous result containing the list of selected files once user is done with choosing them. */ private CompletionStage<List<File>> openFileChooserForMedia() { final FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Pick a media for your tweet"); final ExtensionFilter extensionFilter = twitterMediaExtensionFilter.getExtensionFilter(); fileChooser.getExtensionFilters().add(extensionFilter); fileChooser.setSelectedExtensionFilter(extensionFilter); fileChooser.setInitialDirectory(new File(System.getProperty("user.home"))); return CompletableFuture.supplyAsync(() -> { final Stage stage = this.embeddingStage.getValue(); final List<File> chosenFiles = fileChooser.showOpenMultipleDialog(stage); return chosenFiles != null ? chosenFiles : Collections.emptyList(); }, Platform::runLater); } /** * Creates previews for every media selected for upload. * * @param selectedFiles the selected files */ private void mediaFilesChosen(final List<File> selectedFiles) { pickMediaButton.setDisable(false); mediasToUpload.addAll(selectedFiles); LOG.debug("Added media files for upload with next tweet : {}", selectedFiles); final List<ImageView> mediaImagePreviews = selectedFiles.stream() .map(NewTweetController::buildMediaPreviewImageView) .filter(Objects::nonNull) .collect(Collectors.toList()); if (!mediaImagePreviews.isEmpty()) { mediaPreviewBox.getChildren().addAll(mediaImagePreviews); } } private void sendOnControlEnter() { tweetTextArea.sceneProperty().addListener((o, prev, cur) -> cur.getAccelerators().put( new KeyCodeCombination(KeyCode.ENTER, KeyCombination.CONTROL_DOWN), sendButton::fire )); } /** * Builds an {@link ImageView} preview for a given file. * * @param previewedFile The file in question * * @return The miniature {@link ImageView} previewing it */ private static ImageView buildMediaPreviewImageView(final File previewedFile) { try { final ImageView imageView = new ImageView(); imageView.setFitHeight(MEDIA_PREVIEW_IMAGE_SIZE); imageView.setFitWidth(MEDIA_PREVIEW_IMAGE_SIZE); final URL imageUrl = previewedFile.toURI().toURL(); final Image image = new Image( imageUrl.toExternalForm(), MEDIA_PREVIEW_IMAGE_SIZE, MEDIA_PREVIEW_IMAGE_SIZE, false, true ); imageView.setImage(image); final Rectangle previewClip = Clipping.getSquareClip( MEDIA_PREVIEW_IMAGE_SIZE, MEDIA_PREVIEW_IMAGE_SIZE * 0.25 ); imageView.setClip(previewClip); return imageView; } catch (final MalformedURLException e) { LOG.error("Can not preview media" + previewedFile.toString(), e); return null; } } }
15,142
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
NewTweetScreenComponent.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/screens/newtweet/NewTweetScreenComponent.java
package moe.lyrebird.view.screens.newtweet; import org.springframework.stereotype.Component; import moe.tristan.easyfxml.api.FxmlComponent; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.api.FxmlFile; @Component public class NewTweetScreenComponent implements FxmlComponent { @Override public FxmlFile getFile() { return () -> "NewTweet.fxml"; } @Override public Class<? extends FxmlController> getControllerClass() { return NewTweetController.class; } }
530
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
UserViewController.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/screens/user/UserViewController.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.screens.user; import static moe.lyrebird.model.twitter.services.interraction.UserInteraction.FOLLOW; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javafx.application.Platform; import javafx.beans.property.Property; import javafx.beans.property.SimpleObjectProperty; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.Separator; import javafx.scene.image.ImageView; import javafx.scene.layout.Pane; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import javafx.scene.shape.Rectangle; import moe.lyrebird.model.io.AsyncIO; import moe.lyrebird.model.sessions.SessionManager; import moe.lyrebird.model.twitter.services.interraction.TwitterInteractionService; import moe.lyrebird.view.assets.ImageResources; import moe.lyrebird.view.components.usertimeline.UserTimelineComponent; import moe.lyrebird.view.components.usertimeline.UserTimelineController; import moe.lyrebird.view.viewmodel.javafx.Clipping; import moe.tristan.easyfxml.EasyFxml; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.model.exception.ExceptionHandler; import twitter4j.Relationship; import twitter4j.User; /** * This controller is responsible for managing the {@link UserScreenComponent}, which is used to display details about a specific user. * <p> * Made {@link Lazy} in case the user never uses it. * <p> * Also made {@link ConfigurableBeanFactory#SCOPE_PROTOTYPE} because the user might want to display multiple users at the same time. */ @Lazy @Component @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) public class UserViewController implements FxmlController { private static final Logger LOG = LoggerFactory.getLogger(UserViewController.class); private static final String FOLLOW_BTN_TEXT = "Follow"; private static final String UNFOLLOW_BTN_TEXT = "Unfollow"; private static final String YOURSELF_BTN_TEXT = "It's you !"; @FXML private VBox container; @FXML private VBox userDetailsVBox; @FXML private ImageView userBanner; @FXML private ImageView userProfilePictureImageView; @FXML private Label userNameLabel; @FXML private Label userIdLabel; @FXML private Button followButton; @FXML private Label userTweetCount; @FXML private Label userFollowingCount; @FXML private Label userFollowerCount; @FXML private Label userDescription; @FXML private Label userFriendshipStatus; @FXML private Label userLocation; @FXML private Separator userLocationWebsiteSeparator; @FXML private Label userWebsite; @FXML private Label userCreationDate; private final EasyFxml easyFxml; private final AsyncIO asyncIO; private final SessionManager sessionManager; private final TwitterInteractionService interactionService; private final UserTimelineComponent userTimelineComponent; private final Property<User> targetUserProp; @Autowired public UserViewController( EasyFxml easyFxml, AsyncIO asyncIO, SessionManager sessionManager, TwitterInteractionService interactionService, UserTimelineComponent userTimelineComponent ) { this.easyFxml = easyFxml; this.asyncIO = asyncIO; this.sessionManager = sessionManager; this.interactionService = interactionService; this.userTimelineComponent = userTimelineComponent; this.targetUserProp = new SimpleObjectProperty<>(null); } /** * @return The user this detailed user view is displaying. */ public Property<User> targetUserProperty() { return targetUserProp; } @Override public void initialize() { followButton.setDisable(true); userBanner.fitWidthProperty().bind(userDetailsVBox.widthProperty()); userBanner.fitHeightProperty().bind(userDetailsVBox.heightProperty()); userBanner.setPreserveRatio(false); userBanner.setImage(ImageResources.BACKGROUND_DARK_1PX.getImage()); userProfilePictureImageView.setImage(ImageResources.GENERAL_USER_AVATAR_LIGHT.getImage()); final Rectangle profilePictureClip = Clipping.getSquareClip(290.0, 50.0); userProfilePictureImageView.setClip(profilePictureClip); if (targetUserProp.getValue() == null) { this.targetUserProp.addListener((o, prev, cur) -> displayTargetUser()); } else { displayTargetUser(); } } /** * Basic orchestrator method call for visual setup. */ private void displayTargetUser() { this.fillTextData(); this.asyncLoadImages(); this.setupFollowData(); this.loadTargetUserTimeline(); } /** * Method responsible for loading all the non-network-dependent textual data. */ private void fillTextData() { final User user = targetUserProp.getValue(); userNameLabel.setText(user.getName()); userIdLabel.setText("@" + user.getScreenName()); userDescription.setText(user.getDescription()); userTweetCount.setText(Integer.toString(user.getStatusesCount())); userFollowingCount.setText(Integer.toString(user.getFriendsCount())); userFollowerCount.setText(Integer.toString(user.getFollowersCount())); userCreationDate.setText(user.getCreatedAt().toString()); final String userLocationText = user.getLocation(); if (userLocationText != null) { userLocation.setText(userLocationText); } else { userLocation.setVisible(false); userLocation.setManaged(false); } final String userWebsiteText = user.getURL(); if (userWebsiteText != null) { userWebsite.setText(userWebsiteText); } else { userWebsite.setVisible(false); userWebsite.setManaged(false); } if (userLocationText == null || userWebsiteText == null) { userLocationWebsiteSeparator.setVisible(false); userLocationWebsiteSeparator.setManaged(false); } } /** * This method asynchronously loads the user's profile picture and banner in the view. */ private void asyncLoadImages() { final User user = targetUserProp.getValue(); asyncIO.loadImage(user.getOriginalProfileImageURLHttps()) .thenAcceptAsync(userProfilePictureImageView::setImage, Platform::runLater); final String bannerUrl = user.getProfileBannerURL(); if (bannerUrl == null) { LOG.debug("No profile banner. Keep background color pixel instead."); } else { asyncIO.loadImage(bannerUrl) .thenAcceptAsync(userBanner::setImage, Platform::runLater); } } /** * Sets up follow/unfollow related network-dependent data in the view. */ private void setupFollowData() { final User user = targetUserProp.getValue(); followButton.setOnAction(e -> { interactionService.interact(user, FOLLOW); updateFollowStatusText(); }); updateFollowStatusText(); } /** * Updates the follow button's text to match the current status of the two user's relationship. */ private void updateFollowStatusText() { final User targetUser = this.targetUserProp.getValue(); CompletableFuture.supplyAsync(() -> interactionService.notYetFollowed(targetUser)) .thenApplyAsync(notFollowed -> notFollowed ? FOLLOW_BTN_TEXT : UNFOLLOW_BTN_TEXT) .thenAcceptAsync(followButton::setText, Platform::runLater); CompletableFuture.supplyAsync(sessionManager.currentSessionProperty().getValue()::getTwitterUser) .thenApplyAsync(currentUser -> currentUser.get().getId()) .thenAcceptAsync( currentUserId -> { if (currentUserId == targetUser.getId()) { followButton.setText(YOURSELF_BTN_TEXT); followButton.setDisable(true); } else { followButton.setDisable(false); } }, Platform::runLater ) .thenRunAsync(this::updateFriendshipStatus, Platform::runLater); } /** * Called by {@link #updateFollowStatusText()} ()} to give, if pertinent, a simple text displaying if the target user is already following the current * user. */ private void updateFriendshipStatus() { CompletableFuture.supplyAsync(this::getRelationship) .thenAcceptAsync(relationship -> { String relStatusText = null; if (relationship.isTargetFollowingSource()) { if (relationship.isTargetFollowedBySource()) { relStatusText = "You follow each other!"; } else { relStatusText = "Follows you."; } } if (relStatusText == null) { userFriendshipStatus.setVisible(false); userFriendshipStatus.setManaged(false); } else { userFriendshipStatus.setText(relStatusText); userFriendshipStatus.setVisible(true); userFriendshipStatus.setManaged(true); } }, Platform::runLater); } /** * @return The {@link Relationship} between the current user in the direction of the {@link #targetUserProp}. */ private Relationship getRelationship() { return sessionManager.doWithCurrentTwitter( twitter -> sessionManager.currentSessionProperty() .getValue() .getTwitterUser() .mapTry(us -> twitter.showFriendship( us.getId(), targetUserProp.getValue().getId() )).get() ).getOrElseThrow((Function<? super Throwable, IllegalStateException>) IllegalStateException::new); } /** * Loads the target user's timeline into the view. */ private void loadTargetUserTimeline() { final User user = targetUserProp.getValue(); easyFxml.load(userTimelineComponent, Pane.class, UserTimelineController.class) .afterControllerLoaded(utc -> utc.setTargetUser(user)) .afterNodeLoaded(userDetailsTimeline -> VBox.setVgrow(userDetailsTimeline, Priority.ALWAYS)) .getNode() .recover(ExceptionHandler::fromThrowable) .onSuccess(container.getChildren()::add); } }
12,609
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
UserScreenComponent.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/screens/user/UserScreenComponent.java
package moe.lyrebird.view.screens.user; import org.springframework.stereotype.Component; import moe.lyrebird.view.screens.update.UpdateScreenController; import moe.tristan.easyfxml.api.FxmlComponent; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.api.FxmlFile; @Component public class UserScreenComponent implements FxmlComponent { @Override public FxmlFile getFile() { return () -> "UserView.fxml"; } @Override public Class<? extends FxmlController> getControllerClass() { return UpdateScreenController.class; } }
590
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
UpdateScreenComponent.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/screens/update/UpdateScreenComponent.java
package moe.lyrebird.view.screens.update; import org.springframework.stereotype.Component; import moe.tristan.easyfxml.api.FxmlComponent; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.api.FxmlFile; @Component public class UpdateScreenComponent implements FxmlComponent { @Override public FxmlFile getFile() { return () -> "Update.fxml"; } @Override public Class<? extends FxmlController> getControllerClass() { return UpdateScreenController.class; } }
528
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
UpdateScreenController.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/screens/update/UpdateScreenController.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.screens.update; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import moe.lyrebird.api.model.LyrebirdVersion; import moe.lyrebird.model.update.UpdateService; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.model.system.BrowserSupport; /** * This controller is responsible for managing the {@link UpdateScreenComponent}. */ @Component public class UpdateScreenController implements FxmlController { @FXML private Label currentVersionLabel; @FXML private Label latestVersionLabel; @FXML private Button updateButton; @FXML private Button openInBrowserUrl; private final Environment environment; private final UpdateService updateService; private final BrowserSupport browserSupport; public UpdateScreenController( final Environment environment, final UpdateService updateService, final BrowserSupport browserSupport ) { this.environment = environment; this.updateService = updateService; this.browserSupport = browserSupport; } @Override public void initialize() { updateService.getLatestVersion() .thenAcceptAsync(this::displayVersion, Platform::runLater); final boolean canSelfupdate = UpdateService.selfupdateCompatible(); updateButton.setVisible(canSelfupdate); updateButton.setManaged(canSelfupdate); updateButton.setOnAction(e -> { this.updateButton.setDisable(true); this.updateService.selfupdate(); }); } /** * Displays the current version and the one detected as latest from the API. * * @param latestVersion The latest version fetched from the API. */ private void displayVersion(final LyrebirdVersion latestVersion) { this.currentVersionLabel.setText(environment.getRequiredProperty("app.version")); this.latestVersionLabel.setText(latestVersion.getVersion()); this.openInBrowserUrl.setOnAction(e -> browserSupport.openUrl(latestVersion.getReleaseUrl())); } }
3,111
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
DirectMessagePaneComponent.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/directmessages/DirectMessagePaneComponent.java
package moe.lyrebird.view.components.directmessages; import org.springframework.stereotype.Component; import moe.tristan.easyfxml.api.FxmlComponent; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.api.FxmlFile; @Component public class DirectMessagePaneComponent implements FxmlComponent { @Override public FxmlFile getFile() { return () -> "DMPane.fxml"; } @Override public Class<? extends FxmlController> getControllerClass() { return DMPaneController.class; } }
538
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
DirectMessagesController.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/directmessages/DirectMessagesController.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.components.directmessages; import java.util.HashSet; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; import javafx.application.Platform; import javafx.beans.binding.Bindings; import javafx.collections.FXCollections; import javafx.collections.MapChangeListener; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.layout.Pane; import moe.lyrebird.model.twitter.observables.DirectMessages; import moe.tristan.easyfxml.EasyFxml; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.model.exception.ExceptionHandler; import twitter4j.DirectMessage; import twitter4j.User; @Lazy @Component public class DirectMessagesController implements FxmlController { private static final Logger LOG = LoggerFactory.getLogger(DirectMessagesController.class); @FXML private TabPane conversationsTabPane; private final EasyFxml easyFxml; private final DirectMessages directMessages; private final DirectMessagesConversationComponent directMessagesConversationComponent; private final Set<User> loadedPals = new HashSet<>(); private final ObservableList<Tab> conversationsManaged; @Autowired public DirectMessagesController( EasyFxml easyFxml, DirectMessages directMessages, DirectMessagesConversationComponent directMessagesConversationComponent ) { this.easyFxml = easyFxml; this.directMessages = directMessages; this.directMessagesConversationComponent = directMessagesConversationComponent; this.conversationsManaged = FXCollections.observableArrayList(); listenToNewConversations(); } @Override public void initialize() { LOG.info("Displaying direct messages."); Bindings.bindContent(conversationsTabPane.getTabs(), conversationsManaged); } private void listenToNewConversations() { directMessages.directMessages().keySet().forEach(this::createTabForPal); directMessages.directMessages().addListener((MapChangeListener<User, ObservableList<DirectMessage>>) change -> { if (change.wasAdded()) { this.createTabForPal(change.getKey()); } }); } private void createTabForPal(final User user) { if (loadedPals.contains(user)) { return; } LOG.debug("Creating a conversation tab for conversation with {}", user.getScreenName()); easyFxml.load(directMessagesConversationComponent, Pane.class, DMConversationController.class) .afterControllerLoaded(dmc -> dmc.setPal(user)) .getNode() .recover(ExceptionHandler::fromThrowable) .map(conversation -> new Tab(user.getName(), conversation)) .onSuccess(tab -> Platform.runLater(() -> { LOG.debug("Adding [{}] as tab for user {}", tab.getText(), user.getScreenName()); this.conversationsManaged.add(tab); })); loadedPals.add(user); } }
4,151
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
DMPaneController.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/directmessages/DMPaneController.java
package moe.lyrebird.view.components.directmessages; import static moe.tristan.easyfxml.util.Properties.whenPropertyIsSet; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javafx.application.Platform; import javafx.beans.property.Property; import javafx.beans.property.SimpleObjectProperty; import javafx.fxml.FXML; import javafx.geometry.Pos; import javafx.scene.control.Label; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import moe.lyrebird.model.io.AsyncIO; import moe.lyrebird.model.sessions.SessionManager; import moe.lyrebird.model.twitter.services.CachedTwitterInfoService; import moe.lyrebird.model.twitter.user.UserDetailsService; import moe.lyrebird.view.viewmodel.javafx.Clipping; import moe.tristan.easyfxml.model.components.listview.ComponentCellFxmlController; import twitter4j.DirectMessage; import twitter4j.User; @Component @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) public class DMPaneController implements ComponentCellFxmlController<DirectMessage> { @FXML private HBox container; @FXML private ImageView currentUserPpBox; @FXML private ImageView otherPpBox; @FXML private Label messageContent; private final AsyncIO asyncIO; private final CachedTwitterInfoService cachedTwitterInfoService; private final SessionManager sessionManager; private final UserDetailsService userDetailsService; private final Property<DirectMessage> currentMessage = new SimpleObjectProperty<>(null); @Autowired public DMPaneController( final SessionManager sessionManager, final AsyncIO asyncIO, final CachedTwitterInfoService cachedTwitterInfoService, final UserDetailsService userDetailsService ) { this.sessionManager = sessionManager; this.asyncIO = asyncIO; this.cachedTwitterInfoService = cachedTwitterInfoService; this.userDetailsService = userDetailsService; } @Override public void initialize() { currentUserPpBox.setClip(Clipping.getCircleClip(24.0)); otherPpBox.setClip(Clipping.getCircleClip(24.0)); textualContent(); profilePictures(); } @Override public void updateWithValue(final DirectMessage newValue) { this.currentMessage.setValue(newValue); } private void profilePictures() { whenPropertyIsSet(currentMessage, messageEvent -> { final boolean isSentByMe = sessionManager.isCurrentUser(messageEvent.getSenderId()); final User sender = cachedTwitterInfoService.getUser(messageEvent.getSenderId()); if (isSentByMe) { container.setAlignment(Pos.TOP_RIGHT); ppSetupSender(currentUserPpBox, sender); ppSetupReceiver(otherPpBox); } else { container.setAlignment(Pos.TOP_LEFT); ppSetupSender(otherPpBox, sender); ppSetupReceiver(currentUserPpBox); } }); } private void ppSetupSender(final ImageView ppView, final User user) { ppView.setVisible(true); ppView.setManaged(true); ppView.setOnMouseClicked(e -> userDetailsService.openUserDetails(user)); asyncIO.loadImageMiniature(user.getProfileImageURLHttps(), 128.0, 128.0) .thenAcceptAsync(ppView::setImage, Platform::runLater); } private static void ppSetupReceiver(final ImageView ppView) { ppView.setVisible(false); ppView.setManaged(false); } private void textualContent() { whenPropertyIsSet(currentMessage, DirectMessage::getText, messageContent::setText); } }
3,858
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
DirectMessagesComponent.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/directmessages/DirectMessagesComponent.java
package moe.lyrebird.view.components.directmessages; import org.springframework.stereotype.Component; import moe.tristan.easyfxml.api.FxmlComponent; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.api.FxmlFile; @Component public class DirectMessagesComponent implements FxmlComponent { @Override public FxmlFile getFile() { return () -> "DirectMessages.fxml"; } @Override public Class<? extends FxmlController> getControllerClass() { return DirectMessagesController.class; } }
551
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
DMConversationController.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/directmessages/DMConversationController.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.components.directmessages; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import moe.tristan.easyfxml.model.components.listview.ComponentListViewFxmlController; import moe.lyrebird.model.twitter.observables.DirectMessages; import moe.lyrebird.model.twitter.services.NewDirectMessageService; import moe.lyrebird.view.components.cells.DirectMessageListCell; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import twitter4j.DirectMessage; import twitter4j.User; import javafx.application.Platform; import javafx.beans.property.Property; import javafx.beans.property.ReadOnlyListWrapper; import javafx.beans.property.SimpleObjectProperty; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.TextArea; import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE; @Component @Scope(scopeName = SCOPE_PROTOTYPE) public class DMConversationController extends ComponentListViewFxmlController<DirectMessage> { private static final Logger LOG = LoggerFactory.getLogger(DMConversationController.class); @FXML private TextArea messageContent; @FXML private Button sendButton; private final DirectMessages directMessages; private final NewDirectMessageService newDirectMessageService; private final Property<User> currentPal = new SimpleObjectProperty<>(); public DMConversationController( final DirectMessages directMessages, final ApplicationContext applicationContext, final NewDirectMessageService newDirectMessageService ) { super(applicationContext, DirectMessageListCell.class); this.directMessages = directMessages; this.newDirectMessageService = newDirectMessageService; } @Override public void initialize() { super.initialize(); LOG.debug("Schedule displaying of conversation once senderId has been received!"); sendButton.setOnAction(e -> sendMessage()); } public void setPal(final User pal) { LOG.debug("Messages for [{}] loaded!", pal.getScreenName()); this.currentPal.setValue(pal); listView.itemsProperty().bind(new ReadOnlyListWrapper<>(directMessages.directMessages().get(pal))); } private void sendMessage() { LOG.debug("Sending direct message!"); messageContent.setDisable(true); sendButton.setDisable(true); newDirectMessageService.sendMessage( currentPal.getValue(), messageContent.getText() ).whenCompleteAsync((res, err) -> { messageContent.clear(); messageContent.setDisable(false); sendButton.setDisable(false); }, Platform::runLater); } }
3,690
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
DirectMessagesConversationComponent.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/directmessages/DirectMessagesConversationComponent.java
package moe.lyrebird.view.components.directmessages; import org.springframework.stereotype.Component; import moe.tristan.easyfxml.api.FxmlComponent; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.api.FxmlFile; @Component public class DirectMessagesConversationComponent implements FxmlComponent { @Override public FxmlFile getFile() { return () -> "DMConversation.fxml"; } @Override public Class<? extends FxmlController> getControllerClass() { return DMConversationController.class; } }
563
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
CurrentAccountComponent.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/currentaccount/CurrentAccountComponent.java
package moe.lyrebird.view.components.currentaccount; import org.springframework.stereotype.Component; import moe.tristan.easyfxml.api.FxmlComponent; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.api.FxmlFile; @Component public class CurrentAccountComponent implements FxmlComponent { @Override public FxmlFile getFile() { return () -> "CurrentAccount.fxml"; } @Override public Class<? extends FxmlController> getControllerClass() { return CurrentAccountController.class; } }
551
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
CurrentAccountController.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/currentaccount/CurrentAccountController.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.components.currentaccount; import static moe.lyrebird.view.assets.ImageResources.CONTROLBAR_ADD_USER; import java.util.concurrent.CompletableFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.image.ImageView; import javafx.scene.shape.Circle; import moe.lyrebird.model.io.AsyncIO; import moe.lyrebird.model.sessions.Session; import moe.lyrebird.model.sessions.SessionManager; import moe.lyrebird.model.twitter.user.UserDetailsService; import moe.lyrebird.view.components.controlbar.ControlBarComponent; import moe.lyrebird.view.screens.login.LoginScreenComponent; import moe.lyrebird.view.screens.user.UserScreenComponent; import moe.lyrebird.view.viewmodel.javafx.Clipping; import moe.tristan.easyfxml.EasyFxml; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.util.Stages; import io.vavr.control.Try; import twitter4j.User; /** * This component is loaded at the top of the {@link ControlBarComponent} and serves as a very basic preview for who is the current user that will be used to * perform all the actions requested. * * @see SessionManager */ @Component public class CurrentAccountController implements FxmlController { private static final Logger LOG = LoggerFactory.getLogger(CurrentAccountController.class); @FXML private ImageView userProfilePicture; @FXML private Circle userProfilePictureBorder; @FXML private Label userScreenName; private final AsyncIO asyncIO; private final EasyFxml easyFxml; private final SessionManager sessionManager; private final UserDetailsService userDetailsService; private final LoginScreenComponent loginScreenComponent; @Autowired public CurrentAccountController( SessionManager sessionManager, AsyncIO asyncIO, EasyFxml easyFxml, UserDetailsService userDetailsService, LoginScreenComponent loginScreenComponent ) { this.sessionManager = sessionManager; this.asyncIO = asyncIO; this.easyFxml = easyFxml; this.userDetailsService = userDetailsService; this.loginScreenComponent = loginScreenComponent; } @Override public void initialize() { userProfilePictureBorder.visibleProperty().bind(sessionManager.isLoggedInProperty()); userProfilePicture.setClip(Clipping.getCircleClip(32.0)); userProfilePicture.setImage(CONTROLBAR_ADD_USER.getImage()); userProfilePicture.setOnMouseClicked(e -> handleClickOnProfile()); bindUsername(); bindProfilePicture(); } /** * Binds the displayed username to the one resolved by the {@link SessionManager}. */ private void bindUsername() { this.userScreenName.textProperty().bind(sessionManager.currentSessionUsernameProperty()); } /** * Asynchronously binds the displayed profile picture to the one resolved for the user in the current session via calling {@link SessionManager}. */ private void bindProfilePicture() { sessionManager.currentSessionProperty().addListener( (observable, oldValue, newValue) -> this.userChanged(newValue) ); this.userChanged(sessionManager.currentSessionProperty().getValue()); } /** * Handles the change of a user either from none (unlogged) or to another one if the user has multiple accounts set up. * * @param newValue The newly selected user for usage. */ private void userChanged(final Session newValue) { CompletableFuture.runAsync(() -> loadAndSetUserAvatar(newValue.getTwitterUser())); } /** * Handles clicks on the user profile picture. It either relates to adding an account (in unlogged state) or to displaying the current user's detailed * view. */ private void handleClickOnProfile() { LOG.debug("Clicked on current session profile picture"); if (sessionManager.currentSessionProperty().getValue() == null) { LOG.debug("Disconnected. Consider it as a request for new session!"); handleNewSessionRequest(); } else { LOG.debug("Connected. Consider it as a request to see personal profile."); loadDetailsForCurrentUser(); } } /** * Called when the user requests the adding of a new account. */ private void handleNewSessionRequest() { easyFxml.load(loginScreenComponent) .getNode() .map(loginScreen -> Stages.stageOf("Add new account", loginScreen)) .andThen(Stages::scheduleDisplaying); } /** * Called when the user requests the displaying of the current user's detailed view. * * @see UserScreenComponent */ private void loadDetailsForCurrentUser() { sessionManager.currentSessionProperty() .getValue() .getTwitterUser() .onSuccess(userDetailsService::openUserDetails); } /** * Asynchronous load and set of the user profile picture. * * @param user The user with which to work, mostly because we do not keep a reference to it inside this class. */ private void loadAndSetUserAvatar(final Try<User> user) { user.map(User::getOriginalProfileImageURLHttps) .map(imageUrl -> asyncIO.loadImageMiniature(imageUrl, 128.0, 128.0)) .onSuccess(loadRequest -> loadRequest.thenAcceptAsync(userProfilePicture::setImage, Platform::runLater)); } }
6,597
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
CreditController.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/credits/CreditController.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.components.credits; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javafx.application.Platform; import javafx.beans.property.Property; import javafx.beans.property.SimpleObjectProperty; import javafx.fxml.FXML; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import moe.lyrebird.model.credits.objects.CreditedWork; import moe.lyrebird.view.screens.credits.CreditScreenComponent; import moe.tristan.easyfxml.model.components.listview.ComponentCellFxmlController; import moe.tristan.easyfxml.model.system.BrowserSupport; /** * This component is the one managing a single credit disclaimer unit in the credits list view. * * @see CreditScreenComponent */ @Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE) @Component public class CreditController implements ComponentCellFxmlController<CreditedWork> { @FXML private Label title; @FXML private Hyperlink author; @FXML private Hyperlink licensor; @FXML private Hyperlink license; private final Property<CreditedWork> creditedWork; private final BrowserSupport browserSupport; @Autowired public CreditController(final BrowserSupport browserSupport) { this.browserSupport = browserSupport; this.creditedWork = new SimpleObjectProperty<>(null); } @Override public void updateWithValue(final CreditedWork newValue) { creditedWork.setValue(newValue); } @Override public void initialize() { creditedWork.addListener((o, prev, cur) -> { if (cur != null) { Platform.runLater(() -> { title.setText(cur.getTitle()); author.setText(cur.getAuthor().getName()); author.setOnAction(e -> browserSupport.openUrl(cur.getAuthor().getUrl())); licensor.setText(cur.getLicensor().getName()); licensor.setOnAction(e -> browserSupport.openUrl(cur.getLicensor().getUrl())); license.setText(cur.getLicense().getName()); license.setOnAction(e -> browserSupport.openUrl(cur.getLicense().getUrl())); }); } }); } }
3,231
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
CreditComponent.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/credits/CreditComponent.java
package moe.lyrebird.view.components.credits; import org.springframework.stereotype.Component; import moe.tristan.easyfxml.api.FxmlComponent; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.api.FxmlFile; @Component public class CreditComponent implements FxmlComponent { @Override public FxmlFile getFile() { return () -> "CreditPane.fxml"; } @Override public Class<? extends FxmlController> getControllerClass() { return CreditController.class; } }
524
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
ControlBarController.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/controlbar/ControlBarController.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.components.controlbar; import static moe.tristan.easyfxml.model.exception.ExceptionHandler.displayExceptionPane; import java.util.List; import java.util.concurrent.CompletionStage; import java.util.function.Function; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javafx.beans.property.Property; import javafx.beans.property.SimpleObjectProperty; import javafx.fxml.FXML; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.stage.Stage; import moe.lyrebird.model.sessions.SessionManager; import moe.lyrebird.model.update.UpdateService; import moe.lyrebird.view.components.currentaccount.CurrentAccountComponent; import moe.lyrebird.view.components.directmessages.DirectMessagesComponent; import moe.lyrebird.view.components.mentions.MentionsComponent; import moe.lyrebird.view.components.timeline.TimelineComponent; import moe.lyrebird.view.screens.credits.CreditScreenComponent; import moe.lyrebird.view.screens.newtweet.NewTweetController; import moe.lyrebird.view.screens.newtweet.NewTweetScreenComponent; import moe.lyrebird.view.screens.root.RootScreenController; import moe.lyrebird.view.screens.update.UpdateScreenComponent; import moe.lyrebird.view.viewmodel.javafx.Clipping; import moe.tristan.easyfxml.EasyFxml; import moe.tristan.easyfxml.api.FxmlComponent; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.model.beanmanagement.StageManager; import moe.tristan.easyfxml.model.exception.ExceptionHandler; import moe.tristan.easyfxml.model.fxml.FxmlLoadResult; import moe.tristan.easyfxml.util.Stages; import io.vavr.control.Option; /** * The ControlBar is the left-side view selector for Lyrebird's main UI window. */ @Component public class ControlBarController implements FxmlController { private static final Logger LOG = LoggerFactory.getLogger(ControlBarController.class); @FXML private BorderPane container; @FXML private HBox tweet; @FXML private HBox timeline; @FXML private HBox mentions; @FXML private HBox directMessages; @FXML private HBox credits; @FXML private HBox update; private final EasyFxml easyFxml; private final RootScreenController rootScreenController; private final SessionManager sessionManager; private final UpdateService updateService; private final StageManager stageManager; private final TimelineComponent timelineComponent; private final MentionsComponent mentionsComponent; private final DirectMessagesComponent directMessagesComponent; private final CurrentAccountComponent currentAccountComponent; private final NewTweetScreenComponent newTweetScreenComponent; private final CreditScreenComponent creditScreenComponent; private final UpdateScreenComponent updateScreenComponent; private final Property<HBox> currentViewButton; public ControlBarController( EasyFxml easyFxml, RootScreenController rootScreenController, SessionManager sessionManager, UpdateService updateService, StageManager stageManager, TimelineComponent timelineComponent, MentionsComponent mentionsComponent, DirectMessagesComponent directMessagesComponent, CurrentAccountComponent currentAccountComponent, NewTweetScreenComponent newTweetScreenComponent, CreditScreenComponent creditScreenComponent, UpdateScreenComponent updateScreenComponent ) { this.easyFxml = easyFxml; this.rootScreenController = rootScreenController; this.sessionManager = sessionManager; this.updateService = updateService; this.stageManager = stageManager; this.timelineComponent = timelineComponent; this.mentionsComponent = mentionsComponent; this.directMessagesComponent = directMessagesComponent; this.currentAccountComponent = currentAccountComponent; this.newTweetScreenComponent = newTweetScreenComponent; this.creditScreenComponent = creditScreenComponent; this.updateScreenComponent = updateScreenComponent; this.currentViewButton = new SimpleObjectProperty<>(null); } @Override public void initialize() { currentViewButton.addListener((o, prev, current) -> { if (prev != null) { prev.setDisable(false); prev.setOpacity(1.0); } current.setDisable(true); current.setOpacity(0.5); }); setUpTweetButton(); bindActionImageToLoadingView(timeline, timelineComponent); bindActionImageToLoadingView(mentions, mentionsComponent); bindActionImageToLoadingView(directMessages, directMessagesComponent); credits.setOnMouseClicked(e -> openCreditsView()); sessionManager.isLoggedInProperty().addListener((o, prev, cur) -> handleLogStatusChange(prev, cur)); handleLogStatusChange(false, sessionManager.isLoggedInProperty().getValue()); loadCurrentAccountPanel(); update.managedProperty().bind(updateService.isUpdateAvailableProperty()); update.visibleProperty().bind(updateService.isUpdateAvailableProperty()); update.setOnMouseClicked(e -> openUpdatesScreen()); } /** * Makes sure the tweet button appears as a nice circle through CSS and clipping work. */ private void setUpTweetButton() { tweet.setOnMouseClicked(e -> this.openTweetWindow()); tweet.setClip(Clipping.getCircleClip(28.0)); } /** * Loads the current user's account view on the top of the bar. */ private void loadCurrentAccountPanel() { easyFxml.load(currentAccountComponent) .getNode() .onSuccess(container::setTop) .onFailure(err -> displayExceptionPane( "Could not load current user!", "There was an error mapping the current session to a twitter account.", err )); } /** * Called on click on the {@link #tweet} box. Opens a new tweet window. * * @see NewTweetScreenComponent */ private void openTweetWindow() { LOG.info("Opening new tweet stage..."); final FxmlLoadResult<Pane, NewTweetController> newTweetViewLoadResult = this.easyFxml.load( newTweetScreenComponent, Pane.class, NewTweetController.class ); final Pane newTweetPane = newTweetViewLoadResult.getNode().getOrElseGet(ExceptionHandler::fromThrowable); final NewTweetController newTweetController = newTweetViewLoadResult.getController().get(); Stages.stageOf("Tweet", newTweetPane) .thenComposeAsync(Stages::scheduleDisplaying) .thenAcceptAsync(newTweetController::setStage); } /** * This method managed switching from an unlogged to a logged state. It is tied to {@link SessionManager#isLoggedInProperty()}'s value. * * @param previous Whether the user was previously logged-in * @param current Whether the user is not logged-in */ private void handleLogStatusChange(final boolean previous, final boolean current) { List.of( timeline, tweet, mentions, directMessages, tweet ).forEach(btn -> btn.setVisible(current)); // was not connected and now is, mostly to distinguish with the future feature of // multiple accounts management if (!previous && current) { timeline.onMouseClickedProperty().get().handle(null); } } private void bindActionImageToLoadingView(final HBox imageBox, final FxmlComponent fxComponent) { imageBox.setOnMouseClicked(e -> { currentViewButton.setValue(imageBox); rootScreenController.setContent(fxComponent); }); } private void openCreditsView() { final Option<Stage> existingCreditsStage = stageManager.getSingle(creditScreenComponent); if (existingCreditsStage.isDefined()) { final Stage creditsStage = existingCreditsStage.get(); creditsStage.show(); creditsStage.toFront(); } else { loadCreditsStage().thenAcceptAsync(stage -> { stageManager.registerSingle(creditScreenComponent, stage); Stages.scheduleDisplaying(stage); }); } } private CompletionStage<Stage> loadCreditsStage() { return easyFxml.load(creditScreenComponent) .orExceptionPane() .map(pane -> Stages.stageOf("Credits", pane)) .getOrElseThrow((Function<? super Throwable, ? extends RuntimeException>) RuntimeException::new); } /** * The {@link #update} box only show up when an update is detected as available. Then if it is the case, this method is called on click to open the update * information screen. * * @see UpdateScreenComponent */ private void openUpdatesScreen() { final FxmlLoadResult<Pane, FxmlController> updateScreenLoadResult = easyFxml.load(updateScreenComponent); final Pane updatePane = updateScreenLoadResult.getNode().getOrElseGet(ExceptionHandler::fromThrowable); Stages.stageOf("Updates", updatePane).thenAcceptAsync(Stages::scheduleDisplaying); } }
10,456
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
ControlBarComponent.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/controlbar/ControlBarComponent.java
package moe.lyrebird.view.components.controlbar; import org.springframework.stereotype.Component; import moe.tristan.easyfxml.api.FxmlComponent; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.api.FxmlFile; @Component public class ControlBarComponent implements FxmlComponent { @Override public FxmlFile getFile() { return () -> "ControlBar.fxml"; } @Override public Class<? extends FxmlController> getControllerClass() { return ControlBarController.class; } }
535
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
MentionsController.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/mentions/MentionsController.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.components.mentions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.stereotype.Component; import moe.lyrebird.model.twitter.observables.Mentions; import moe.lyrebird.view.components.base.TimelineControllerBase; /** * Mostly setup for Mentions timeline view. * * @see TimelineControllerBase */ @Component public class MentionsController extends TimelineControllerBase { private static final Logger LOG = LoggerFactory.getLogger(MentionsController.class); public MentionsController(final Mentions mentions, final ConfigurableApplicationContext context) { super(mentions, context); } @Override protected Logger getLogger() { return LOG; } }
1,631
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
MentionsComponent.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/mentions/MentionsComponent.java
package moe.lyrebird.view.components.mentions; import org.springframework.stereotype.Component; import moe.tristan.easyfxml.api.FxmlComponent; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.api.FxmlFile; @Component public class MentionsComponent implements FxmlComponent { @Override public FxmlFile getFile() { return () -> "Mentions.fxml"; } @Override public Class<? extends FxmlController> getControllerClass() { return MentionsController.class; } }
527
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
TimelineController.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/timeline/TimelineController.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.components.timeline; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.stereotype.Component; import moe.lyrebird.model.twitter.observables.Timeline; import moe.lyrebird.view.components.base.TimelineControllerBase; /** * Mostly setup for default timeline view. * * @see TimelineControllerBase */ @Component public class TimelineController extends TimelineControllerBase { private static final Logger LOG = LoggerFactory.getLogger(TimelineController.class); public TimelineController(final Timeline timeline, final ConfigurableApplicationContext context) { super(timeline, context); } @Override protected Logger getLogger() { return LOG; } }
1,630
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
TimelineComponent.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/timeline/TimelineComponent.java
package moe.lyrebird.view.components.timeline; import org.springframework.stereotype.Component; import moe.tristan.easyfxml.api.FxmlComponent; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.api.FxmlFile; @Component public class TimelineComponent implements FxmlComponent { @Override public FxmlFile getFile() { return () -> "Timeline.fxml"; } @Override public Class<? extends FxmlController> getControllerClass() { return TimelineController.class; } }
527
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
UserTimelineComponent.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/usertimeline/UserTimelineComponent.java
package moe.lyrebird.view.components.usertimeline; import org.springframework.stereotype.Component; import moe.tristan.easyfxml.api.FxmlComponent; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.api.FxmlFile; @Component public class UserTimelineComponent implements FxmlComponent { @Override public FxmlFile getFile() { return () -> "UserTimeline.fxml"; } @Override public Class<? extends FxmlController> getControllerClass() { return UserTimelineController.class; } }
543
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
UserTimelineController.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/usertimeline/UserTimelineController.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.components.usertimeline; import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import moe.lyrebird.model.twitter.observables.UserTimeline; import moe.lyrebird.view.components.base.TimelineControllerBase; import twitter4j.User; /** * Mostly setup for the self timeline view of a given user. * * @see UserTimelineController */ @Component @Scope(SCOPE_PROTOTYPE) public class UserTimelineController extends TimelineControllerBase { private static final Logger LOG = LoggerFactory.getLogger(UserTimelineController.class); private final UserTimeline userTimeline; @Autowired public UserTimelineController(final UserTimeline userTimeline, final ConfigurableApplicationContext context) { super(userTimeline, context); this.userTimeline = userTimeline; } @Override public void initialize() { super.initialize(); userTimeline.refresh(); } /** * @param user The user whose self timeline we want to display */ public void setTargetUser(final User user) { userTimeline.targetUserProperty().setValue(user); } @Override protected Logger getLogger() { return LOG; } }
2,351
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
TweetInteractionPaneController.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/tweet/TweetInteractionPaneController.java
package moe.lyrebird.view.components.tweet; import static moe.lyrebird.model.twitter.services.interraction.StatusInteraction.LIKE; import static moe.lyrebird.model.twitter.services.interraction.StatusInteraction.RETWEET; import java.util.concurrent.CompletableFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javafx.application.Platform; import javafx.beans.property.Property; import javafx.beans.property.SimpleObjectProperty; import javafx.fxml.FXML; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import moe.lyrebird.model.twitter.services.interraction.StatusInteraction; import moe.lyrebird.model.twitter.services.interraction.TwitterBinaryInteraction; import moe.lyrebird.model.twitter.services.interraction.TwitterInteractionService; import moe.lyrebird.view.assets.ImageResources; import moe.lyrebird.view.screens.newtweet.NewTweetController; import moe.lyrebird.view.screens.newtweet.NewTweetScreenComponent; import moe.lyrebird.view.viewmodel.javafx.Clipping; import moe.tristan.easyfxml.EasyFxml; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.model.exception.ExceptionHandler; import moe.tristan.easyfxml.model.fxml.FxmlLoadResult; import moe.tristan.easyfxml.util.Stages; import twitter4j.Status; /** * This class manages the display of an interaction toolbar under every non-embedded tweet. * <p> * Its role is to enable interaction and reflect it visually. * * @see TweetPaneController * @see TwitterInteractionService */ @Component @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) public class TweetInteractionPaneController implements FxmlController { private static final Logger LOG = LoggerFactory.getLogger(TweetInteractionPaneController.class); private static final double INTERACTION_BUTTON_CLIP_RADIUS = 14.0; @FXML private HBox replyButton; @FXML private HBox likeButton; @FXML private ImageView likeButtonGraphic; @FXML private HBox retweetButton; @FXML private ImageView retweetButtonGraphic; private final TwitterInteractionService interactionService; private final EasyFxml easyFxml; private final Property<Status> targetStatus; private final NewTweetScreenComponent newTweetScreenComponent; @Autowired public TweetInteractionPaneController( EasyFxml easyFxml, TwitterInteractionService interactionService, NewTweetScreenComponent newTweetScreenComponent ) { this.interactionService = interactionService; this.easyFxml = easyFxml; this.newTweetScreenComponent = newTweetScreenComponent; this.targetStatus = new SimpleObjectProperty<>(null); } @Override public void initialize() { setUpInteractionActions(); targetStatus.addListener((o, prev, cur) -> { updateRetweetVisual(cur.isRetweet() ? cur.getRetweetedStatus().isRetweeted() : cur.isRetweeted()); updateLikeVisual(cur.isFavorited()); }); } Property<Status> targetStatusProperty() { return targetStatus; } /** * Binds click on a button to its expected action */ private void setUpInteractionActions() { replyButton.setOnMouseClicked(e -> this.onReply()); replyButton.setClip(Clipping.getCircleClip(INTERACTION_BUTTON_CLIP_RADIUS)); likeButton.setOnMouseClicked(e -> this.onLike()); likeButton.setClip(Clipping.getCircleClip(INTERACTION_BUTTON_CLIP_RADIUS)); retweetButton.setOnMouseClicked(e -> this.onRetweet()); retweetButton.setClip(Clipping.getCircleClip(INTERACTION_BUTTON_CLIP_RADIUS)); } /** * Opens a {@link NewTweetScreenComponent} with the current status embedded for reply features. */ private void onReply() { final FxmlLoadResult<Pane, NewTweetController> replyStageLoad = easyFxml.load( newTweetScreenComponent, Pane.class, NewTweetController.class ).afterControllerLoaded(ntc -> ntc.setInReplyToTweet(targetStatus.getValue())); final NewTweetController newTweetController = replyStageLoad.getController().get(); final Pane newTweetPane = replyStageLoad.getNode().getOrElseGet(ExceptionHandler::fromThrowable); Stages.stageOf("Reply to tweet", newTweetPane) .thenAcceptAsync(stage -> { newTweetController.setStage(stage); Stages.scheduleDisplaying(stage); }); } /** * Called on click of the retweet button. * <p> * Will call {@link #updateRetweetVisual(boolean)} on task finish to set the appropriate visual value. * * @see TwitterInteractionService * @see TwitterBinaryInteraction * @see StatusInteraction#RETWEET */ private void onRetweet() { LOG.debug("Retweet interaction on status {}", targetStatus.getValue().getId()); retweetButton.setDisable(true); CompletableFuture.supplyAsync( () -> interactionService.interact(targetStatus.getValue(), RETWEET) ).thenAcceptAsync(res -> { final Status originalStatus = targetStatus.getValue().isRetweet() ? targetStatus.getValue().getRetweetedStatus() : targetStatus.getValue(); updateRetweetVisual(!interactionService.notYetRetweeted(originalStatus)); retweetButton.setDisable(false); }, Platform::runLater); } /** * Updates the visual clue for whether the current tweet was already retweeted by the current user. * * @param retweeted whether the current tweet was determined to having been retweeted by the current user */ private void updateRetweetVisual(final boolean retweeted) { retweetButtonGraphic.setImage( retweeted ? ImageResources.TWEETPANE_RETWEET_ON.getImage() : ImageResources.TWEETPANE_RETWEET_OFF.getImage() ); } /** * Called on click of the like button. * <p> * Will call {@link #updateLikeVisual(boolean)} on task finish to set the appropriate visual value. * * @see TwitterInteractionService * @see TwitterBinaryInteraction * @see StatusInteraction#LIKE */ private void onLike() { LOG.debug("Like interaction on status {}", targetStatus.getValue().getId()); likeButton.setDisable(true); CompletableFuture.supplyAsync( () -> interactionService.interact(targetStatus.getValue(), LIKE) ).thenAcceptAsync(res -> { updateLikeVisual(res.isFavorited()); likeButton.setDisable(false); }, Platform::runLater); } /** * Updates the visual clue for whether the current tweet was already liked by the current user. * * @param liked whether the current tweet was determined to having been liked by the current user */ private void updateLikeVisual(final boolean liked) { likeButtonGraphic.setImage( liked ? ImageResources.TWEETPANE_LIKE_ON.getImage() : ImageResources.TWEETPANE_LIKE_OFF.getImage() ); } }
7,551
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
TweetInteractionPaneComponent.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/tweet/TweetInteractionPaneComponent.java
package moe.lyrebird.view.components.tweet; import org.springframework.stereotype.Component; import moe.tristan.easyfxml.api.FxmlComponent; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.api.FxmlFile; @Component public class TweetInteractionPaneComponent implements FxmlComponent { @Override public FxmlFile getFile() { return () -> "TweetInteractionPane.fxml"; } @Override public Class<? extends FxmlController> getControllerClass() { return TweetInteractionPaneController.class; } }
560
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
TweetContentPaneComponent.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/tweet/TweetContentPaneComponent.java
package moe.lyrebird.view.components.tweet; import org.springframework.stereotype.Component; import moe.tristan.easyfxml.api.FxmlComponent; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.api.FxmlFile; @Component public class TweetContentPaneComponent implements FxmlComponent { @Override public FxmlFile getFile() { return () -> "TweetContentPane.fxml"; } @Override public Class<? extends FxmlController> getControllerClass() { return TweetContentPaneController.class; } }
548
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
TweetPaneComponent.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/tweet/TweetPaneComponent.java
package moe.lyrebird.view.components.tweet; import org.springframework.stereotype.Component; import moe.tristan.easyfxml.api.FxmlComponent; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.api.FxmlFile; @Component public class TweetPaneComponent implements FxmlComponent { @Override public FxmlFile getFile() { return () -> "TweetPane.fxml"; } @Override public Class<? extends FxmlController> getControllerClass() { return TweetPaneController.class; } }
527
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
TweetContentPaneController.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/tweet/TweetContentPaneController.java
package moe.lyrebird.view.components.tweet; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javafx.beans.property.Property; import javafx.beans.property.SimpleObjectProperty; import javafx.fxml.FXML; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.scene.text.TextFlow; import moe.lyrebird.view.viewmodel.tokenization.TweetContentTokenizer; import moe.tristan.easyfxml.api.FxmlController; import twitter4j.Status; /** * This controller and its associated view represent and display the textual content of a Tweet as rich text. * * @see TweetContentTokenizer */ @Component @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) public class TweetContentPaneController implements FxmlController { @FXML private TextFlow tweetContent; private final TweetContentTokenizer tweetContentTokenizer; private final Property<Status> statusProp = new SimpleObjectProperty<>(); @Autowired public TweetContentPaneController(final TweetContentTokenizer tweetContentTokenizer) { this.tweetContentTokenizer = tweetContentTokenizer; } @Override public void initialize() { if (statusProp.getValue() != null) { statusReady(); } statusProp.addListener((observable, oldValue, newValue) -> statusReady()); VBox.setVgrow(tweetContent, Priority.ALWAYS); } public void setStatusProp(final Status status) { this.statusProp.setValue(status); } /** * This method tokenizes the newly loaded tweet via {@link TweetContentTokenizer#asTextFlowTokens(Status)} and * puts that result inside the embedding {@link TextFlow}. */ private void statusReady() { final List<Text> textFlowElements = tweetContentTokenizer.asTextFlowTokens(statusProp.getValue()); tweetContent.getChildren().setAll(textFlowElements); } }
2,122
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
TweetPaneController.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/tweet/TweetPaneController.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.components.tweet; import static moe.lyrebird.view.assets.ImageResources.GENERAL_USER_AVATAR_DARK; import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE; import java.util.List; import org.ocpsoft.prettytime.PrettyTime; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javafx.application.Platform; import javafx.beans.property.BooleanProperty; import javafx.beans.property.Property; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.image.ImageView; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import moe.lyrebird.model.io.AsyncIO; import moe.lyrebird.model.twitter.user.UserDetailsService; import moe.lyrebird.view.components.cells.TweetListCell; import moe.lyrebird.view.screens.media.MediaEmbeddingService; import moe.lyrebird.view.screens.newtweet.NewTweetController; import moe.lyrebird.view.viewmodel.javafx.Clipping; import moe.tristan.easyfxml.EasyFxml; import moe.tristan.easyfxml.model.components.listview.ComponentCellFxmlController; import moe.tristan.easyfxml.model.exception.ExceptionHandler; import moe.tristan.easyfxml.model.fxml.FxmlLoadResult; import moe.tristan.easyfxml.util.Nodes; import twitter4j.Status; /** * Displays a single tweet ({@link Status} in Twitter4J). * * @see TweetListCell * @see NewTweetController */ @Component @Scope(scopeName = SCOPE_PROTOTYPE) public class TweetPaneController implements ComponentCellFxmlController<Status> { private static final PrettyTime PRETTY_TIME = new PrettyTime(); @FXML private Label author; @FXML private Label authorId; @FXML private Label time; @FXML private ImageView authorProfilePicture; @FXML private Pane authorProfilePicturePane; @FXML private VBox tweetContent; @FXML private HBox mediaBox; @FXML private Label retweeterLabel; @FXML private Label retweeterIdLabel; @FXML private HBox retweetHbox; @FXML private BorderPane interactionBox; private final EasyFxml easyFxml; private final AsyncIO asyncIO; private final MediaEmbeddingService mediaEmbeddingService; private final UserDetailsService userDetailsService; private final TweetContentPaneComponent tweetContentPaneComponent; private final TweetInteractionPaneComponent tweetInteractionPaneComponent; private final Property<Status> currentStatus; private final BooleanProperty isRetweet = new SimpleBooleanProperty(false); private final BooleanProperty embeddedProperty = new SimpleBooleanProperty(false); public TweetPaneController( AsyncIO asyncIO, MediaEmbeddingService mediaEmbeddingService, UserDetailsService userDetailsService, EasyFxml easyFxml, TweetContentPaneComponent tweetContentPaneComponent, TweetInteractionPaneComponent tweetInteractionPaneComponent ) { this.asyncIO = asyncIO; this.mediaEmbeddingService = mediaEmbeddingService; this.userDetailsService = userDetailsService; this.easyFxml = easyFxml; this.tweetContentPaneComponent = tweetContentPaneComponent; this.tweetInteractionPaneComponent = tweetInteractionPaneComponent; this.currentStatus = new SimpleObjectProperty<>(null); } @Override public void initialize() { authorProfilePicturePane.setClip(Clipping.getCircleClip(24.0)); Nodes.hideAndResizeParentIf(retweetHbox, isRetweet); authorProfilePicture.setImage(GENERAL_USER_AVATAR_DARK.getImage()); setUpInteractionButtons(); mediaBox.setManaged(false); mediaBox.setVisible(false); } /** * @return whether this tweet is displayed in an embedding node (e.g. for replies) */ public BooleanProperty embeddedPropertyProperty() { return embeddedProperty; } private void setUpInteractionButtons() { interactionBox.visibleProperty().bind(embeddedProperty.not()); interactionBox.managedProperty().bind(embeddedProperty.not()); easyFxml.load(tweetInteractionPaneComponent, Pane.class, TweetInteractionPaneController.class) .afterControllerLoaded(tipc -> tipc.targetStatusProperty().bind(currentStatus)) .getNode() .recover(ExceptionHandler::fromThrowable) .onSuccess(interactionBox::setCenter); } /** * @param newValue The status to prepare displaying for. */ @Override public void updateWithValue(final Status newValue) { if (newValue == null || this.currentStatus.getValue() == newValue) { return; } this.currentStatus.setValue(newValue); this.isRetweet.set(currentStatus.getValue().isRetweet()); authorProfilePicture.setImage(GENERAL_USER_AVATAR_DARK.getImage()); if (currentStatus.getValue().isRetweet()) { handleRetweet(currentStatus.getValue()); } else { setStatusDisplay(currentStatus.getValue()); } } /** * Handles retweets so as to add retweet info at the top and then display the actual underlying status. */ private void handleRetweet(final Status status) { retweeterLabel.setText(status.getUser().getName()); retweeterIdLabel.setText("@" + status.getUser().getScreenName()); setStatusDisplay(status.getRetweetedStatus()); } /** * @param statusToDisplay The status to fill user readable information from. */ private void setStatusDisplay(final Status statusToDisplay) { author.setText(statusToDisplay.getUser().getName()); authorId.setText("@" + statusToDisplay.getUser().getScreenName()); time.setText(PRETTY_TIME.format(statusToDisplay.getCreatedAt())); loadTextIntoTextFlow(statusToDisplay); final String ppUrl = statusToDisplay.getUser().getOriginalProfileImageURLHttps(); asyncIO.loadImageMiniature(ppUrl, 96.0, 96.0) .thenAcceptAsync(authorProfilePicture::setImage, Platform::runLater); authorProfilePicture.setOnMouseClicked(e -> userDetailsService.openUserDetails(statusToDisplay.getUser())); readMedias(currentStatus.getValue()); } /** * Pre-formats a status' text content. * * @param status The status whose content we have to format */ private void loadTextIntoTextFlow(final Status status) { tweetContent.getChildren().clear(); final FxmlLoadResult<Pane, TweetContentPaneController> result = easyFxml.load( tweetInteractionPaneComponent, Pane.class, TweetContentPaneController.class ); result.afterControllerLoaded(tcpc -> tcpc.setStatusProp(status)) .getNode() .peek(pane -> VBox.setVgrow(pane, Priority.ALWAYS)) .recover(ExceptionHandler::fromThrowable) .andThen(tweetContent.getChildren()::add); } /** * Manages extracting and previewing the medias embedded in this tweet. * * @param status The status for which to manage the embedded media. */ private void readMedias(final Status status) { final List<Node> embeddingNodes = mediaEmbeddingService.embed(status); mediaBox.setManaged(!embeddingNodes.isEmpty()); mediaBox.setVisible(!embeddingNodes.isEmpty()); mediaBox.getChildren().setAll(embeddingNodes); } }
8,616
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
DirectMessageListCell.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/cells/DirectMessageListCell.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.components.cells; import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javafx.scene.control.ListView; import moe.lyrebird.view.components.directmessages.DirectMessagePaneComponent; import moe.tristan.easyfxml.EasyFxml; import moe.tristan.easyfxml.model.components.listview.ComponentListCell; import twitter4j.DirectMessage; /** * This is the class managing the cell of a direct message from the point of view of its embedding {@link ListView}. * * @see ComponentListCell */ @Component @Scope(scopeName = SCOPE_PROTOTYPE) public class DirectMessageListCell extends ComponentListCell<DirectMessage> { public DirectMessageListCell(final EasyFxml easyFxml, DirectMessagePaneComponent directMessagePaneComponent) { super(easyFxml, directMessagePaneComponent); } }
1,777
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
TweetListCell.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/cells/TweetListCell.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.components.cells; import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javafx.scene.control.ListView; import moe.lyrebird.view.components.tweet.TweetPaneComponent; import moe.tristan.easyfxml.EasyFxml; import moe.tristan.easyfxml.model.components.listview.ComponentListCell; import twitter4j.Status; /** * This is the class managing the cell of a tweet from the point of view of its embedding {@link ListView}. * * @see ComponentListCell */ @Component @Scope(scopeName = SCOPE_PROTOTYPE) public class TweetListCell extends ComponentListCell<Status> { public TweetListCell(EasyFxml easyFxml, TweetPaneComponent tweetPaneComponent) { super(easyFxml, tweetPaneComponent); } }
1,691
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
CreditsCell.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/cells/CreditsCell.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.components.cells; import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.scene.control.ListView; import moe.lyrebird.model.credits.objects.CreditedWork; import moe.lyrebird.view.components.credits.CreditComponent; import moe.tristan.easyfxml.EasyFxml; import moe.tristan.easyfxml.model.components.listview.ComponentListCell; /** * This is the class managing the cell of a credit disclaimer from the point of view of its embedding {@link ListView}. * * @see ComponentListCell */ @Component @Scope(scopeName = SCOPE_PROTOTYPE) public class CreditsCell extends ComponentListCell<CreditedWork> { private final BooleanProperty shouldDisplay; public CreditsCell(EasyFxml easyFxml, CreditComponent creditComponent) { super(easyFxml, creditComponent); this.shouldDisplay = new SimpleBooleanProperty(false); this.cellNode.visibleProperty().bind(shouldDisplay); } @Override protected void updateItem(final CreditedWork item, final boolean empty) { super.updateItem(item, empty); this.shouldDisplay.setValue(item != null && !empty); } }
2,196
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
TimelineControllerBase.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/base/TimelineControllerBase.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.components.base; import java.util.Optional; import org.slf4j.Logger; import org.springframework.context.ConfigurableApplicationContext; import javafx.beans.property.ListProperty; import javafx.beans.property.ReadOnlyListWrapper; import moe.lyrebird.model.twitter.observables.TwitterTimelineBaseModel; import moe.lyrebird.view.components.cells.TweetListCell; import moe.lyrebird.view.components.mentions.MentionsController; import moe.lyrebird.view.components.timeline.TimelineController; import moe.tristan.easyfxml.model.components.listview.ComponentListViewFxmlController; import twitter4j.Status; /** * This class serves as a base implementation for backend observing lists of chronologically reverse-sorted tweets (aka * a timeline). * * @see TimelineController * @see MentionsController * @see TimelineControllerBase */ public abstract class TimelineControllerBase extends ComponentListViewFxmlController<Status> { private final TwitterTimelineBaseModel timelineBase; private final ListProperty<Status> tweetsProperty; /** * This constructor is called by the implementing class rather than Spring because there is no way we will ever use * field injection in Lyrebird. * * @param timelineBase The backing model-side controller taking care of requests and exposing tweets * @param context The spring context that is passed onto {@link ComponentListViewFxmlController} for * constructor injection. */ public TimelineControllerBase( final TwitterTimelineBaseModel timelineBase, final ConfigurableApplicationContext context ) { super(context, TweetListCell.class); this.timelineBase = timelineBase; this.tweetsProperty = new ReadOnlyListWrapper<>(timelineBase.loadedTweets()); } @Override public void initialize() { super.initialize(); listView.itemsProperty().bind(new ReadOnlyListWrapper<>(timelineBase.loadedTweets())); } /** * Requests loading of older tweets. */ private void loadMoreTweets() { getOldestTweetLoaded().ifPresent(oldestStatus -> { getLogger().debug("Loading tweets before {}", oldestStatus.getId()); timelineBase.loadMoreTweets(oldestStatus.getId()); listView.scrollTo(oldestStatus); }); } /** * @return The previously oldest loaded tweets for use in {@link #loadMoreTweets()}. */ private Optional<Status> getOldestTweetLoaded() { if (tweetsProperty.isEmpty()) { getLogger().debug("No older tweets to load."); return Optional.empty(); } final Status oldest = tweetsProperty.getValue().get(tweetsProperty.size() - 1); getLogger().debug("Loading tweets before {}", oldest.getId()); return Optional.of(oldest); } /** * Called when the user scrolls to the end of {@link #listView}. */ @Override protected void onScrolledToEndOfListView() { loadMoreTweets(); } /** * @return The logger to use for calls from the child class. */ protected abstract Logger getLogger(); }
4,049
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
NotificationPaneComponent.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/notifications/NotificationPaneComponent.java
package moe.lyrebird.view.components.notifications; import org.springframework.stereotype.Component; import moe.tristan.easyfxml.api.FxmlComponent; import moe.tristan.easyfxml.api.FxmlController; import moe.tristan.easyfxml.api.FxmlFile; @Component public class NotificationPaneComponent implements FxmlComponent { @Override public FxmlFile getFile() { return () -> "NotificationPane.fxml"; } @Override public Class<? extends FxmlController> getControllerClass() { return NotificationsController.class; } }
553
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
NotificationsController.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/components/notifications/NotificationsController.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.view.components.notifications; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import moe.tristan.easyfxml.api.FxmlController; import moe.lyrebird.model.notifications.Notification; import moe.lyrebird.model.notifications.system.InternalNotificationSystem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javafx.application.Platform; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.layout.AnchorPane; /** * This controller is responsible for in-app notifications (as opposed to system-side ones). This component can only * display one single notification at a time because there is not realistic need for more. * * @see InternalNotificationSystem */ @Component public class NotificationsController implements FxmlController { private static final Logger LOG = LoggerFactory.getLogger(NotificationsController.class); private final InternalNotificationSystem internalNotificationSystem; @FXML private AnchorPane notificationPane; @FXML private Label notificationTitle; @FXML private Label notificationContent; private final BooleanProperty shouldDisplay = new SimpleBooleanProperty(false); @Autowired public NotificationsController(final InternalNotificationSystem internalNotificationSystem) { this.internalNotificationSystem = internalNotificationSystem; } @Override public void initialize() { notificationPane.visibleProperty().bind(shouldDisplay); notificationPane.managedProperty().bind(shouldDisplay); notificationPane.setOnMouseClicked(e -> shouldDisplay.setValue(false)); notificationContent.textProperty().addListener((observable, oldValue, newValue) -> { notificationContent.visibleProperty().setValue(!newValue.isEmpty()); notificationContent.managedProperty().setValue(!newValue.isEmpty()); }); LOG.debug("Starting internal notification system. Listening on new notification requests."); internalNotificationSystem.notificationProperty().addListener((o, prev, cur) -> this.handleChange(cur)); } /** * Called when the notification to display exposed by the backend is changed. * * @param notification The new notification to display. */ private void handleChange(final Notification notification) { LOG.debug("New notification to display!"); shouldDisplay.setValue(true); LOG.debug("Displaying notification {} internally.", notification); Platform.runLater(() -> { notificationTitle.setText(notification.getTitle()); notificationContent.setText(notification.getText()); }); } }
3,690
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
BackendComponents.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/BackendComponents.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model; import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Scope; import moe.lyrebird.model.sessions.SessionManager; import moe.lyrebird.model.sessions.SessionRepository; import moe.lyrebird.model.twitter.twitter4j.Twitter4JComponents; import moe.lyrebird.model.twitter.twitter4j.TwitterHandler; import twitter4j.Twitter; /** * Back-end (Twitter, persistence etc.) components go here. * <p> * For Twitter4J wrapping see {@link Twitter4JComponents} */ @Configuration public class BackendComponents { private static final Logger LOG = LoggerFactory.getLogger(BackendComponents.class); @Bean @Lazy @Scope(scopeName = SCOPE_PROTOTYPE) public TwitterHandler twitterHandler(final Twitter twitter) { return new TwitterHandler(twitter); } @Bean public SessionManager sessionManager(final ApplicationContext context, final SessionRepository sessionRepository) { final SessionManager sessionManager = new SessionManager(context, sessionRepository); final long loadedSessions = sessionManager.loadAllSessions(); LOG.info("Loaded {} previously saved sessions.", loadedSessions); return sessionManager; } }
2,383
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
CachedMedia.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/io/CachedMedia.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.io; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Component; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javafx.scene.image.Image; import javafx.scene.media.Media; /** * This class exposes convenience methods for doing cached IO operations. */ @Component @SuppressWarnings("MethodMayBeStatic") @Cacheable(value = "cachedMedia", sync = true) public class CachedMedia { private static final Logger LOG = LoggerFactory.getLogger(CachedMedia.class); /** * Loads and caches an image. * * @param imageUrl The url of this image * * @return This image loaded in an {@link Image} instance. */ public Image loadImage(final String imageUrl) { LOG.trace("First load of image {}", imageUrl); return new Image(imageUrl); } /** * Loads and caches an image as a miniature. * * @param imageUrl The url of this image * @param width The width to miniaturize this image to * @param height The height to miniaturize this image to * * @return This image's miniature loaded in an {@link Image} instance. */ public Image loadImageMiniature(final String imageUrl, final double width, final double height) { LOG.trace("First load of miniature image {} [width = {}, height = {}]", imageUrl, width, height); return new Image(imageUrl, width, height, false, true); } /** * Loads and caches a media file. * * @param mediaUrl The url of this media file * * @return This media loaded in a {@link Media} instance. */ public Media loadMediaFile(final String mediaUrl) { LOG.trace("First load of media {}", mediaUrl); return new Media(mediaUrl); } }
2,625
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
AsyncIO.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/io/AsyncIO.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.io; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javafx.scene.image.Image; import javafx.scene.media.Media; /** * This class exposes convenience method to execute asynchronous network operations on the asyncIo thread. * <p> * Every call here must be explicitly made with the {@link CachedMedia} service until proven that the cache really grows * too big with that rule. */ @Component public class AsyncIO { private static final Executor ASYNC_IO_EXECUTOR = Executors.newFixedThreadPool(4); private final CachedMedia cachedMedia; @Autowired public AsyncIO(final CachedMedia cachedMedia) { this.cachedMedia = cachedMedia; } /** * Asynchronously loads an image. * * @param imageUrl the image to load's url as a string * * @return A {@link CompletableFuture} which can be asynchronously consumed if needed upon termination of this load * operation. */ public CompletableFuture<Image> loadImage(final String imageUrl) { return CompletableFuture.supplyAsync(() -> cachedMedia.loadImage(imageUrl), ASYNC_IO_EXECUTOR); } /** * Asynchronously loads an image in miniature version. * * @param imageUrl the image to load's url as a string * @param width the width of the miniature * @param height the height of the miniature * * @return A {@link CompletableFuture} which can be asynchronously consumed if needed upon termination of this load * operation. */ public CompletableFuture<Image> loadImageMiniature(final String imageUrl, final double width, final double height) { return CompletableFuture.supplyAsync( () -> cachedMedia.loadImageMiniature(imageUrl, width, height), ASYNC_IO_EXECUTOR ); } /** * Asynchronously loads a given media. * * @param mediaUrl The loaded media's string-represented url * * @return A {@link CompletableFuture} which can be asynchronously consumed if needed upon termination of this load * operation. */ public CompletableFuture<Media> loadMedia(final String mediaUrl) { return CompletableFuture.supplyAsync( () -> cachedMedia.loadMediaFile(mediaUrl), ASYNC_IO_EXECUTOR ); } }
3,338
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
SystemTrayService.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/systemtray/SystemTrayService.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.systemtray; import java.awt.TrayIcon; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javafx.beans.property.Property; import javafx.beans.property.SimpleObjectProperty; import dorkbox.systemTray.Menu; import dorkbox.systemTray.MenuItem; import dorkbox.systemTray.SystemTray; /** * This class is responsible for management and exposure of the {@link LyrebirdTrayIcon}. */ @Component public class SystemTrayService { private static final Logger LOG = LoggerFactory.getLogger(SystemTrayService.class); private final LyrebirdTrayIcon lyrebirdTrayIcon; private final Property<TrayIcon> trayIcon = new SimpleObjectProperty<>(null); public SystemTrayService(final LyrebirdTrayIcon lyrebirdTrayIcon) { this.lyrebirdTrayIcon = lyrebirdTrayIcon; //loadTrayIcon(); } public Property<TrayIcon> trayIconProperty() { return trayIcon; } /** * Loads the {@link LyrebirdTrayIcon} in the current OS's system tray. */ private void loadTrayIcon() { LOG.debug("Registering tray icon for Lyrebird..."); LOG.debug("Creating a tray icon..."); final SystemTray tray = SystemTray.get(); tray.setImage(lyrebirdTrayIcon.getIcon()); tray.setTooltip("Lyrebird"); LOG.debug("Adding items to tray icon's menu..."); final Menu menu = tray.getMenu(); lyrebirdTrayIcon.getMenuItems().forEach((item, action) -> { LOG.debug("Adding menu item : {} (callback : {})", item, action); final MenuItem menuItem = new MenuItem(item.getLabel()); menuItem.setCallback(action); menu.add(menuItem); }); LOG.debug("Finished creating tray icon!"); } }
2,625
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
LyrebirdTrayIcon.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/systemtray/LyrebirdTrayIcon.java
package moe.lyrebird.model.systemtray; import java.awt.MenuItem; import java.awt.event.ActionListener; import java.net.URL; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cache.annotation.Cacheable; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import javafx.application.Platform; import moe.lyrebird.view.screens.root.RootScreenComponent; import moe.tristan.easyfxml.model.beanmanagement.StageManager; @Component public class LyrebirdTrayIcon { private static final Logger LOG = LoggerFactory.getLogger(LyrebirdTrayIcon.class); private final Environment environment; private final StageManager stageManager; private final RootScreenComponent rootScreenComponent; public LyrebirdTrayIcon(Environment environment, StageManager stageManager, RootScreenComponent rootScreenComponent) { this.environment = environment; this.stageManager = stageManager; this.rootScreenComponent = rootScreenComponent; } public String getLabel() { return environment.getRequiredProperty("app.promo.name"); } @Cacheable("lyrebirdTrayIconURL") public URL getIcon() { return getClass().getClassLoader().getResource("assets/img/general_icon_lyrebird_logo_small.png"); } Map<MenuItem, ActionListener> getMenuItems() { final Map<MenuItem, ActionListener> menuItems = new LinkedHashMap<>(); menuItems.put(new MenuItem("Open Lyrebird", null), e -> showMainStage()); menuItems.put(new MenuItem("Quit Lyrebird", null), e -> Platform.runLater(this::exitApplication)); return menuItems; } /** * Fetches, shows and moves the main application stage to the front. */ private void showMainStage() { CompletableFuture.runAsync( () -> stageManager.getSingle(rootScreenComponent) .toTry(IllegalStateException::new) .onSuccess(stage -> { stage.show(); stage.setIconified(false); }).onFailure(err -> LOG.error("Could not show main stage!", err)), Platform::runLater ); } /** * Requests closure of the application. */ private void exitApplication() { LOG.info("Requesting application closure from tray icon."); stageManager.getSingle(rootScreenComponent).getOrElseThrow(IllegalStateException::new).close(); Platform.exit(); } }
2,706
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
CreditsService.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/credits/CreditsService.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.credits; import static io.vavr.API.unchecked; import static javafx.collections.FXCollections.observableList; import static javafx.collections.FXCollections.unmodifiableObservableList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.stereotype.Component; import javafx.collections.ObservableList; import com.fasterxml.jackson.databind.ObjectMapper; import moe.lyrebird.model.credits.objects.CreditedWork; import io.vavr.collection.Stream; import io.vavr.control.Try; /** * This service aims at exposing credited works disclaimers in src/main/resources/assets/credits/third-parties * * @see CreditedWork */ @Lazy @Component public class CreditsService { private static final String CREDITS_RESOURCES_PATH = "classpath:assets/credits/third-parties/*.json"; private final ObservableList<CreditedWork> creditedWorks; @Autowired public CreditsService(final ObjectMapper objectMapper) { this.creditedWorks = unmodifiableObservableList(observableList(loadCreditsFiles( objectMapper, new PathMatchingResourcePatternResolver() ))); } /** * Deserializes the credited works matching the {@link #CREDITS_RESOURCES_PATH} location pattern. * * @param objectMapper The object mapper used for deserialization * @param pmpr The {@link PathMatchingResourcePatternResolver} used for location pattern matching * * @return The list of deserialized credits files */ private static List<CreditedWork> loadCreditsFiles( final ObjectMapper objectMapper, final PathMatchingResourcePatternResolver pmpr ) { return Try.of(() -> pmpr.getResources(CREDITS_RESOURCES_PATH)) .toStream() .flatMap(Stream::of) .map(unchecked(Resource::getInputStream)) .map(unchecked(cis -> objectMapper.readValue(cis, CreditedWork.class))) .toJavaList(); } /** * @return the observable list of loaded {@link CreditedWork}s. */ public ObservableList<CreditedWork> creditedWorks() { return creditedWorks; } }
3,233
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
CreditedWorkLicense.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/credits/objects/CreditedWorkLicense.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.credits.objects; import java.net.MalformedURLException; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; /** * @see CreditedWork */ public final class CreditedWorkLicense extends SimpleNameUrlBinding { @JsonCreator CreditedWorkLicense( @JsonProperty("name") final String name, @JsonProperty("url") final String url ) throws MalformedURLException { super(name, url); } @Override public String toString() { return "CreditedWorkLicense{" + "name='" + name + '\'' + ", url=" + url + '}'; } }
1,506
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
SimpleNameUrlBinding.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/credits/objects/SimpleNameUrlBinding.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.credits.objects; import com.fasterxml.jackson.annotation.JsonProperty; import java.net.MalformedURLException; import java.net.URL; import java.util.Objects; /** * Simple helper base for fields of {@link CreditedWork} since they all have in common a name and a related URL. * * @see CreditedWork */ public abstract class SimpleNameUrlBinding { @JsonProperty protected final String name; @JsonProperty protected final URL url; SimpleNameUrlBinding(final String name, final String url) throws MalformedURLException { this.name = name; this.url = new URL(url); } public String getName() { return name; } public URL getUrl() { return url; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof SimpleNameUrlBinding)) { return false; } final SimpleNameUrlBinding that = (SimpleNameUrlBinding) o; return Objects.equals(getName(), that.getName()) && Objects.equals(getUrl(), that.getUrl()); } @Override public int hashCode() { return Objects.hash(getName(), getUrl()); } }
2,058
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
CreditedWorkAuthor.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/credits/objects/CreditedWorkAuthor.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.credits.objects; import java.net.MalformedURLException; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; /** * @see CreditedWork */ public final class CreditedWorkAuthor extends SimpleNameUrlBinding { @JsonCreator CreditedWorkAuthor( @JsonProperty("name") final String name, @JsonProperty("url") final String url ) throws MalformedURLException { super(name, url); } @Override public String toString() { return "CreditedWorkAuthor{" + "name='" + name + '\'' + ", url=" + url + '}'; } }
1,503
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
CreditedWork.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/credits/objects/CreditedWork.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.credits.objects; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; /** * POJO used to map the credited works. */ public final class CreditedWork { @JsonProperty private final String title; @JsonProperty private final CreditedWorkAuthor author; @JsonProperty private final CreditedWorkLicensor licensor; @JsonProperty private final CreditedWorkLicense license; @JsonCreator public CreditedWork( @JsonProperty("title") final String title, @JsonProperty("author") final CreditedWorkAuthor author, @JsonProperty("licensor") final CreditedWorkLicensor licensor, @JsonProperty("license") final CreditedWorkLicense license ) { this.title = title; this.author = author; this.licensor = licensor; this.license = license; } public String getTitle() { return title; } public CreditedWorkAuthor getAuthor() { return author; } public CreditedWorkLicensor getLicensor() { return licensor; } public CreditedWorkLicense getLicense() { return license; } }
2,041
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
CreditedWorkLicensor.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/credits/objects/CreditedWorkLicensor.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.credits.objects; import java.net.MalformedURLException; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; /** * @see CreditedWork */ public final class CreditedWorkLicensor extends SimpleNameUrlBinding { @JsonCreator CreditedWorkLicensor( @JsonProperty("name") final String name, @JsonProperty("url") final String url ) throws MalformedURLException { super(name, url); } }
1,324
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
CleanupOperation.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/interrupts/CleanupOperation.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.interrupts; /** * A cleanup operation consists of a name and an operation which are respectively logged and executed during the * application's shutdown process. */ public final class CleanupOperation { private final String name; private final Runnable operation; /** * @param name The human-readable name that will be logged for this operation * @param operation The actual operation to execute at shutdown time */ public CleanupOperation(final String name, final Runnable operation) { this.name = name; this.operation = operation; } String getName() { return name; } Runnable getOperation() { return operation; } }
1,553
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
CleanupService.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/interrupts/CleanupService.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.interrupts; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; /** * This service is called at shutdown to execute a certain amount of cleanup operations. */ @Component public class CleanupService { private static final Logger LOG = LoggerFactory.getLogger(CleanupService.class); private static final Executor CLEANUP_EXECUTOR = Executors.newSingleThreadExecutor(); private final Queue<CleanupOperation> onShutdownHooks = new LinkedList<>(); /** * Registers a cleanup operation for execution at shutdown. * * @param cleanupOperation The operation to execute at shutdown */ public void registerCleanupOperation(final CleanupOperation cleanupOperation) { CompletableFuture.runAsync(() -> { LOG.debug("Registering cleanup operation : {}", cleanupOperation.getName()); onShutdownHooks.add(cleanupOperation); }, CLEANUP_EXECUTOR); } /** * Executes the cleanup operations that were previously registered via * {@link #registerCleanupOperation(CleanupOperation)}. */ public void executeCleanupOperations() { CLEANUP_EXECUTOR.execute(() -> { LOG.info("Cleaning up..."); LOG.debug("Executing cleanup hooks:"); onShutdownHooks.forEach(CleanupService::executeCleanupOperationWithTimeout); LOG.debug("All cleanup hooks have been executed!"); }); } /** * This method executes a single cleanup operation with a timeout. We are not systemd that gives 1m30s for a cleanup * operation so you get 5 seconds to do whatever it is you need. * * @param cleanupOperation The operation to execute */ private static void executeCleanupOperationWithTimeout(final CleanupOperation cleanupOperation) { LOG.debug("\t-> {}", cleanupOperation.getName()); cleanupOperation.getOperation().run(); } }
2,978
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
SettingsUtils.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/settings/SettingsUtils.java
package moe.lyrebird.model.settings; import java.util.prefs.Preferences; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class manages persistent user application settings. * * It is mostly a verbose decorator around {@link Preferences#userRoot()}. */ public final class SettingsUtils { private static final Logger LOG = LoggerFactory.getLogger(SettingsUtils.class); private static final Preferences USER_PREFERENCES = Preferences.userRoot().node("Lyrebird"); private SettingsUtils() { } public static String get(final Setting setting, final String defaultValue) { final String value = USER_PREFERENCES.get(setting.getPreferenceKey(), defaultValue); LOG.debug("Fetched user setting {} : {}", setting, value); return value; } public static void set(final Setting setting, final String value) { LOG.debug("Saving user setting {} with value {}", setting, value); USER_PREFERENCES.put(setting.getPreferenceKey(), value); } public static boolean get(final Setting setting, final boolean defaultValue) { final boolean value = USER_PREFERENCES.getBoolean(setting.getPreferenceKey(), defaultValue); LOG.debug("Fetched boolean user setting {} : {}", setting, value); return value; } public static void set(final Setting setting, final boolean value) { LOG.debug("Saving boolean user setting {} with value {}", setting, value); USER_PREFERENCES.putBoolean(setting.getPreferenceKey(), value); } }
1,549
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
Setting.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/settings/Setting.java
package moe.lyrebird.model.settings; public enum Setting { NOTIFICATION_MAIN_STAGE_TRAY_SEEN("ui.notification.mainStageCloseToTray"); private final String preferenceKey; Setting(final String preferenceKey) { this.preferenceKey = preferenceKey; } public String getPreferenceKey() { return preferenceKey; } }
352
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
TwitterHandler.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/twitter/twitter4j/TwitterHandler.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.twitter.twitter4j; import org.springframework.beans.factory.annotation.Autowired; import io.vavr.CheckedFunction0; import io.vavr.Tuple; import io.vavr.Tuple2; import io.vavr.control.Try; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import twitter4j.Twitter; import twitter4j.auth.AccessToken; import twitter4j.auth.RequestToken; import java.net.URL; import java.util.Optional; import static io.vavr.API.unchecked; /** * This class is a decorator around the {@link Twitter} class. */ public class TwitterHandler { private static final Logger LOG = LoggerFactory.getLogger(TwitterHandler.class); private static final AccessToken FAKE_ACCESS_TOKEN = new AccessToken("fake", "token"); private final Twitter twitter; private AccessToken accessToken = FAKE_ACCESS_TOKEN; @Autowired public TwitterHandler(final Twitter twitter) { this.twitter = twitter; } public Twitter getTwitter() { return twitter; } public AccessToken getAccessToken() { return accessToken; } /** * Creates a user authentication request on Twitter side * * @return a tuple containing the URL for OTP, and the RequestToken to which this OTP will be bound to */ public Tuple2<URL, RequestToken> newSession() { LOG.info("Requesting new Session!"); final RequestToken requestToken = unchecked((CheckedFunction0<RequestToken>) this.twitter::getOAuthRequestToken) .apply(); LOG.info("Got request token : {}", requestToken); return Tuple.of( unchecked((CheckedFunction0<URL>) (() -> new URL(requestToken.getAuthorizationURL()))).apply(), requestToken ); } /** * Tries registering a RequestToken with a given OTP to fetch a persistable AccessToken authenticating the current * user to Twitter through Lyrebird. * * @param requestToken The request token of the authentication request * @param pinCode The OTP bound to this request token * * @return An optional containing the resulting {@link AccessToken} if the authentication was successful. */ public Optional<AccessToken> registerAccessToken(final RequestToken requestToken, final String pinCode) { LOG.info("Registering token {} with pin code {}", requestToken, pinCode); final Try<AccessToken> tryAccessToken = Try.of( () -> this.twitter.getOAuthAccessToken(requestToken, pinCode) ); if (tryAccessToken.isFailure()) { LOG.info("Could not get access token! An error was thrown!"); return Optional.empty(); } final AccessToken successAccessToken = tryAccessToken.get(); this.twitter.setOAuthAccessToken(successAccessToken); LOG.info( "Successfully got access token for user @{}! {}", successAccessToken.getScreenName(), successAccessToken ); this.accessToken = successAccessToken; return Optional.of(successAccessToken); } /** * Loads up the underlying Twitter instance with a given {@link AccessToken}. Useful for multiple account * management. * * @param preloadedAccessToken The previously saved {@link AccessToken}. * * @see #registerAccessToken(RequestToken, String) */ public void registerAccessToken(final AccessToken preloadedAccessToken) { this.accessToken = preloadedAccessToken; this.twitter.setOAuthAccessToken(preloadedAccessToken); } }
4,416
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
Twitter4JComponents.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/twitter/twitter4j/Twitter4JComponents.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.twitter.twitter4j; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Scope; import org.springframework.core.env.Environment; import twitter4j.Twitter; import twitter4j.TwitterFactory; import twitter4j.conf.ConfigurationBuilder; import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE; /** * Configuration class for Twitter4J related components. */ @Lazy @Configuration public class Twitter4JComponents { /** * @param environment The Spring environment to fetch authentication keys * @return this application's configuration for connecting to the Twitter API */ @Bean public twitter4j.conf.Configuration configuration(final Environment environment) { final ConfigurationBuilder cb = new ConfigurationBuilder(); final String consumerKey = environment.getProperty("twitter.consumerKey"); final String consumerSecret = environment.getProperty("twitter.consumerSecret"); cb.setOAuthConsumerSecret(consumerSecret); cb.setOAuthConsumerKey(consumerKey); cb.setTweetModeExtended(true); return cb.build(); } /** * @param configuration this application's configuration * @return a configured TwitterFactory to generate twitter instances */ @Bean public TwitterFactory twitterFactory(final twitter4j.conf.Configuration configuration) { return new TwitterFactory(configuration); } /** * @param factory the TwitterFactory to use for configuration * @return an instance of the {@link Twitter} class that is configured with Lyrebird's credentials. */ @Bean @Scope(value = SCOPE_PROTOTYPE) public Twitter twitter(final TwitterFactory factory) { return factory.getInstance(); } }
2,779
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
RateLimited.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/twitter/refresh/RateLimited.java
package moe.lyrebird.model.twitter.refresh; public interface RateLimited { int maxRequestsPer15Minutes(); void refresh(); }
136
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
AutoRefreshService.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/twitter/refresh/AutoRefreshService.java
package moe.lyrebird.model.twitter.refresh; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import moe.lyrebird.model.sessions.SessionManager; import moe.lyrebird.model.util.FXProperties; @Component public class AutoRefreshService { private static final Logger LOGGER = LoggerFactory.getLogger(AutoRefreshService.class); private static final ScheduledExecutorService REFRESHER = Executors.newSingleThreadScheduledExecutor(); private final List<RateLimited> rateLimitedCalls; @Autowired public AutoRefreshService(final SessionManager sessionManager, final List<RateLimited> rateLimitedCalls) { this.rateLimitedCalls = rateLimitedCalls; LOGGER.debug("Loaded the following autorefresh calls {}", rateLimitedCalls); FXProperties.waitForBooleanProp(sessionManager.isLoggedInProperty(), this::startAutoRefreshing); } private void startAutoRefreshing() { LOGGER.debug("Starting autorefreshes..."); rateLimitedCalls.forEach(rateLimitedCall -> { final int secondsBetweenCalls = secondsBetweenCalls(rateLimitedCall); REFRESHER.scheduleAtFixedRate(() -> { try { rateLimitedCall.refresh(); } catch (final Exception e) { stopAutoRefreshing(); } }, 2, secondsBetweenCalls, TimeUnit.SECONDS); LOGGER.debug("Scheduled autorefresh {} every {} seconds", rateLimitedCall, secondsBetweenCalls); }); } private void stopAutoRefreshing() { final List<Runnable> stopped = REFRESHER.shutdownNow(); LOGGER.debug("Stopped autorefreshing for all calls [{}] : {}", rateLimitedCalls, stopped); } private static int secondsBetweenCalls(final RateLimited rateLimited) { final double secBetweenCalls = (15.0 * 60.0) / ((double) rateLimited.maxRequestsPer15Minutes() * 0.8); return (int) Math.max(3, secBetweenCalls); } }
2,239
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
NewTweetService.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/twitter/services/NewTweetService.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.twitter.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import io.vavr.CheckedFunction1; import moe.lyrebird.model.sessions.SessionManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import twitter4j.Status; import twitter4j.StatusUpdate; import twitter4j.Twitter; import twitter4j.UploadedMedia; import java.io.File; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.stream.Collectors; import static io.vavr.API.unchecked; /** * This service handles tasks related to posting a new tweet */ @Component public class NewTweetService { private static final Logger LOG = LoggerFactory.getLogger(NewTweetService.class); private static final Executor TWITTER_EXECUTOR = Executors.newSingleThreadExecutor(); private final SessionManager sessionManager; @Autowired public NewTweetService(final SessionManager sessionManager) { LOG.debug("Initializing {}...", getClass().getSimpleName()); this.sessionManager = sessionManager; } /** * Asynchronously sends a normal tweet. * * @param content The content of the tweet * @param medias The attachments to upload and link in the tweet * * @return A {@link CompletionStage} to follow the status of the asynchronous request */ public CompletionStage<Status> sendTweet(final String content, final List<File> medias) { return prepareNewTweet(content, medias).thenApplyAsync( update -> sessionManager.doWithCurrentTwitter(twitter -> twitter.updateStatus(update)).get(), TWITTER_EXECUTOR ); } /** * Asynchronously sends a reply to a tweet. * * @param content The content of the reply * @param medias The attachments to upload and link in the reply * @param inReplyTo The tweet that this is in reply to * * @return A {@link CompletionStage} to follow the status of the asynchronous request */ public CompletionStage<Status> sendReply(final String content, final List<File> medias, final long inReplyTo) { return prepareNewTweet(content, medias).thenApplyAsync( update -> { LOG.debug("Set inReplyTo for status update {} as : {}", update, inReplyTo); update.setInReplyToStatusId(inReplyTo); return update; }, TWITTER_EXECUTOR ).thenApplyAsync( update -> sessionManager.doWithCurrentTwitter(twitter -> twitter.updateStatus(update)).get(), TWITTER_EXECUTOR ); } /** * Prepares a new tweet by uploading media related. * * @param content The textual content of the tweet * @param medias The medias to embed in it * * @return A {@link CompletionStage} to monitor the request. */ private CompletionStage<StatusUpdate> prepareNewTweet(final String content, final List<File> medias) { return CompletableFuture.supplyAsync( () -> sessionManager.doWithCurrentTwitter(twitter -> uploadMedias(twitter, medias)).get(), TWITTER_EXECUTOR ).thenApplyAsync( uploadedMediasIds -> buildStatus(content, uploadedMediasIds), TWITTER_EXECUTOR ); } /** * Builds a {@link StatusUpdate} from given parameters * * @param content The textual content of this update * @param mediaIds The mediaIds (from Twitter-side) to be embedded in it * * @return The resulting status update to post */ private static StatusUpdate buildStatus(final String content, final List<Long> mediaIds) { LOG.debug("Preparing new tweet with content [\"{}\"] and mediaIds {}", content, mediaIds); final StatusUpdate statusUpdate = new StatusUpdate(content); final Long[] mediaIdsArr = mediaIds.toArray(new Long[0]); final long[] mediaUnboxedArr = new long[mediaIdsArr.length]; for (int i = 0; i < mediaIdsArr.length; i++) { mediaUnboxedArr[i] = mediaIdsArr[i]; } statusUpdate.setMediaIds(mediaUnboxedArr); return statusUpdate; } /** * Uploads the given media files to Twitter * * @param twitter The twitter instance to use for uploading * @param attachments The media files to upload * * @return The uploaded media files Twitter-side ids */ private static List<Long> uploadMedias(final Twitter twitter, final List<File> attachments) { LOG.debug("Uploading media attachments {}", attachments); return attachments.stream() .map(unchecked((CheckedFunction1<File, UploadedMedia>) twitter::uploadMedia)) .map(UploadedMedia::getMediaId) .collect(Collectors.toList()); } }
5,888
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
CachedTwitterInfoService.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/twitter/services/CachedTwitterInfoService.java
package moe.lyrebird.model.twitter.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Component; import moe.lyrebird.model.sessions.SessionManager; import twitter4j.User; @Component @Cacheable(value = "cachedTwitterInfo", sync = true) public class CachedTwitterInfoService { private final SessionManager sessionManager; @Autowired public CachedTwitterInfoService(final SessionManager sessionManager) { this.sessionManager = sessionManager; } public User getUser(final long userId) { return sessionManager.doWithCurrentTwitter(twitter -> twitter.showUser(userId)).getOrNull(); } }
742
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
NewDirectMessageService.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/twitter/services/NewDirectMessageService.java
package moe.lyrebird.model.twitter.services; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import moe.lyrebird.model.sessions.SessionManager; import moe.lyrebird.model.twitter.observables.DirectMessages; import twitter4j.DirectMessage; import twitter4j.User; @Component public class NewDirectMessageService { private static final Logger LOG = LoggerFactory.getLogger(NewDirectMessageService.class); private final SessionManager sessionManager; private final DirectMessages directMessages; @Autowired public NewDirectMessageService(final SessionManager sessionManager, final DirectMessages directMessages) { this.sessionManager = sessionManager; this.directMessages = directMessages; } public CompletableFuture<DirectMessage> sendMessage(final User recipient, final String content) { LOG.debug("Sending direct message to [{}] with content {}", recipient.getScreenName(), content); return CompletableFuture.supplyAsync(() -> sessionManager.doWithCurrentTwitter( twitter -> twitter.sendDirectMessage(recipient.getId(), content)) ).thenApplyAsync( msgReq -> msgReq.onSuccess(dme -> { LOG.debug("Sent direct message! {}", dme); directMessages.addDirectMessage(dme); }).onFailure( err -> LOG.error("Could not send direct message!", err) ).getOrElseThrow((Function<Throwable, RuntimeException>) RuntimeException::new) ).whenCompleteAsync((res, err) -> { if (err != null) { LOG.error("Could not correctly executed the direct message sending request!", err); } }); } }
1,932
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
UserInteraction.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/twitter/services/interraction/UserInteraction.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.twitter.services.interraction; import twitter4j.User; import java.util.function.BiFunction; /** * Convenience enumeration for {@link TwitterBinaryInteraction}s which apply to {@link User}s. */ public enum UserInteraction implements TwitterBinaryInteraction<User> { FOLLOW( TwitterInteractionService::follow, TwitterInteractionService::unfollow, TwitterInteractionService::notYetFollowed ); private final BiFunction<TwitterInteractionService, User, User> onTrue; private final BiFunction<TwitterInteractionService, User, User> onFalse; private final BiFunction<TwitterInteractionService, User, Boolean> shouldDo; UserInteraction( final BiFunction<TwitterInteractionService, User, User> onTrue, final BiFunction<TwitterInteractionService, User, User> onFalse, final BiFunction<TwitterInteractionService, User, Boolean> shouldDo ) { this.onTrue = onTrue; this.onFalse = onFalse; this.shouldDo = shouldDo; } @Override public BiFunction<TwitterInteractionService, User, User> onTrue() { return onTrue; } @Override public BiFunction<TwitterInteractionService, User, User> onFalse() { return onFalse; } @Override public BiFunction<TwitterInteractionService, User, Boolean> shouldDo() { return shouldDo; } }
2,239
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
TwitterInteractionService.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/twitter/services/interraction/TwitterInteractionService.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.twitter.services.interraction; import org.springframework.stereotype.Component; import moe.lyrebird.model.sessions.SessionManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import twitter4j.Relationship; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.User; import static moe.tristan.easyfxml.model.exception.ExceptionHandler.displayExceptionPane; /** * This service is responsible for interactions with Twitter elements. * <p> * Most notably it manages the linking/retweeting of tweets and the following/unfollowing of users. */ @Component public class TwitterInteractionService { private static final Logger LOG = LoggerFactory.getLogger(TwitterInteractionService.class); private final SessionManager sessionManager; public TwitterInteractionService(final SessionManager sessionManager) { this.sessionManager = sessionManager; } /** * Executes a given {@link TwitterBinaryInteraction} on an element. * * @param target The element this interaction will target * @param twitterBinaryInteraction The interaction to execute * @param <T> The type of element this will target * * @return The resulting operation's result which is of the type of the element this is targeting */ public <T> T interact(final T target, final TwitterBinaryInteraction<T> twitterBinaryInteraction) { if (twitterBinaryInteraction.shouldDo().apply(this, target)) { return twitterBinaryInteraction.onTrue().apply(this, target); } else { return twitterBinaryInteraction.onFalse().apply(this, target); } } /** * Determines whether a given tweet is a retweet made by the current user. Twitter's API really is unhelpful on this * side so we mostly take an educated guess here, although it should be enough in most cases. * * @param status the tweet to test against * * @return true if and only if the given status is a retweet made by the current user */ public boolean isRetweetByCurrentUser(final Status status) { if (status.isRetweet()) { final Status retweetedStatus = status.getRetweetedStatus(); return retweetedStatus.isRetweeted() || retweetedStatus.isRetweetedByMe() || sessionManager.isCurrentUser(status.getUser()); } else { return false; } } /** * Likes a given tweet * * @param tweet the tweet to like * * @return the liked version of the tweet */ Status like(final Status tweet) { return sessionManager.doWithCurrentTwitter(twitter -> twitter.createFavorite(tweet.getId())) .onSuccess(resultingStatus -> LOG.debug( "User {} liked tweet {}", getCurrentScreenName(), resultingStatus.getId() )) .onFailure(err -> displayExceptionPane("Could not like tweet!", err.getMessage(), err)) .get(); } /** * Unlikes a tweet * * @param tweet the tweet to unlike * * @return the unliked version of the tweet */ Status unlike(final Status tweet) { return sessionManager.doWithCurrentTwitter(twitter -> twitter.destroyFavorite(tweet.getId())) .onSuccess(resultingStatus -> LOG.debug( "User {} unliked tweet {}", getCurrentScreenName(), resultingStatus.getId() )) .onFailure(err -> displayExceptionPane("Could not unlike tweet!", err.getMessage(), err)) .get(); } /** * Returns whether or not the given tweet has not yet been liked and that thus the interaction with it should be to * like it. * * @param tweet the tweet to check * * @return true if the given tweet is not liked yet but the current user */ boolean notYetLiked(final Status tweet) { return !sessionManager.doWithCurrentTwitter(twitter -> twitter.showStatus(tweet.getId()).isFavorited()) .get(); } /** * Retweets a given tweet * * @param tweet the tweet to retweet * * @return the tweet's retweet-created tweet (a retweet is a tweet from the retweeting user) */ Status retweet(final Status tweet) { return sessionManager.doWithCurrentTwitter(twitter -> twitter.retweetStatus(tweet.getId())) .onSuccess(resultingStatus -> LOG.debug( "User {} retweeted tweet {}", getCurrentScreenName(), resultingStatus.getId() )) .onFailure(err -> displayExceptionPane("Could not retweet tweet!", err.getMessage(), err)) .get(); } /** * Unretweets (deletes the retweet-created tweet for the current user. See {@link #retweet(Status)} for explanation * on that). * * @param tweet the tweet to unretweet * * @return The retweet that was deleted */ Status unretweet(final Status tweet) { final Status original = tweet.isRetweet() ? tweet.getRetweetedStatus() : tweet; return sessionManager.doWithCurrentTwitter( twitter -> twitter.unRetweetStatus(original.getId()) ).onSuccess(resultingStatus -> LOG.debug( "User {} unretweeted tweet {}", getCurrentScreenName(), resultingStatus.getId() )).onFailure(err -> displayExceptionPane( "Could not unretweet tweet!", err.getMessage(), err )).get(); } /** * Checks whether a given tweet has been retweeted by the current user. * <p> * PSA : I don't care that you can retweet your own tweets. This is stupid and you should never do it. Will never * allow a PR "fixing" that pass. * * @param tweet the tweet to check * * @return Whether the given tweet had not yet been retweeted by the current user. */ public boolean notYetRetweeted(final Status tweet) { return !sessionManager.doWithCurrentTwitter(twitter -> { final Status updatedTweet = twitter.showStatus(tweet.getId()); final Status originalStatus = updatedTweet.isRetweet() ? updatedTweet.getRetweetedStatus() : updatedTweet; return originalStatus.isRetweeted(); }).get(); } /** * Follows a given user. * * @param user the user to follow. * * @return the followed user */ User follow(final User user) { return sessionManager.doWithCurrentTwitter(twitter -> twitter.createFriendship(user.getId())) .onSuccess(userFollowed -> LOG.debug( "User {} followed user {}", getCurrentScreenName(), userFollowed.getScreenName() )) .onFailure(err -> displayExceptionPane("Could not follow user!", err.getMessage(), err)) .get(); } /** * Unfollows a user * * @param user the user to unfollow * * @return the unfollowed user */ User unfollow(final User user) { return sessionManager.doWithCurrentTwitter(twitter -> twitter.destroyFriendship(user.getId())) .onSuccess(userUnfollowed -> LOG.debug( "User {} unfollowed user {}", getCurrentScreenName(), userUnfollowed.getScreenName() )) .onFailure(err -> displayExceptionPane("Could not unfollow user!", err.getMessage(), err)) .get(); } /** * Checks if the given user has not yet been followed * * @param user The user for which to check the follow status * * @return true if and only if the given user has not yet been followed by the current user */ public boolean notYetFollowed(final User user) { return !sessionManager.doWithCurrentTwitter(twitter -> twitter.showFriendship( getCurrentScreenName(), user.getScreenName() )).map(Relationship::isSourceFollowingTarget).get(); } /** * @return the updated screen name of the current user */ private String getCurrentScreenName() { return sessionManager.getCurrentTwitter() .mapTry(Twitter::getScreenName) .getOrElseThrow(err -> new IllegalStateException("Current user unavailable!", err)); } }
10,047
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
StatusInteraction.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/twitter/services/interraction/StatusInteraction.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.twitter.services.interraction; import twitter4j.Status; import java.util.function.BiFunction; /** * Convenience enumeration for {@link TwitterBinaryInteraction}s which apply to {@link Status}es. */ public enum StatusInteraction implements TwitterBinaryInteraction<Status> { LIKE( TwitterInteractionService::like, TwitterInteractionService::unlike, TwitterInteractionService::notYetLiked ), RETWEET( TwitterInteractionService::retweet, TwitterInteractionService::unretweet, TwitterInteractionService::notYetRetweeted ); private final BiFunction<TwitterInteractionService, Status, Status> onTrue; private final BiFunction<TwitterInteractionService, Status, Status> onFalse; private final BiFunction<TwitterInteractionService, Status, Boolean> shouldDo; StatusInteraction( final BiFunction<TwitterInteractionService, Status, Status> onTrue, final BiFunction<TwitterInteractionService, Status, Status> onFalse, final BiFunction<TwitterInteractionService, Status, Boolean> shouldDo ) { this.onTrue = onTrue; this.onFalse = onFalse; this.shouldDo = shouldDo; } @Override public BiFunction<TwitterInteractionService, Status, Status> onTrue() { return onTrue; } @Override public BiFunction<TwitterInteractionService, Status, Status> onFalse() { return onFalse; } @Override public BiFunction<TwitterInteractionService, Status, Boolean> shouldDo() { return shouldDo; } }
2,444
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
TwitterBinaryInteraction.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/twitter/services/interraction/TwitterBinaryInteraction.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.twitter.services.interraction; import java.util.function.BiFunction; /** * A binary interaction is a twitter operation that can be executed in two ways depending on a third information. * @param <T> The type over which to execute these operations */ public interface TwitterBinaryInteraction<T> { /** * @return the operation to execute if {@link #shouldDo()} returns true. */ BiFunction<TwitterInteractionService, T, T> onTrue(); /** * @return the operation to execute if {@link #shouldDo()} returns false. */ BiFunction<TwitterInteractionService, T, T> onFalse(); /** * @return whether the {@link #onTrue()} is the relevant one. */ BiFunction<TwitterInteractionService, T, Boolean> shouldDo(); }
1,599
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
UserDetailsService.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/twitter/user/UserDetailsService.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.twitter.user; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Component; import javafx.scene.layout.Pane; import moe.lyrebird.model.sessions.SessionManager; import moe.lyrebird.view.screens.user.UserScreenComponent; import moe.lyrebird.view.screens.user.UserViewController; import moe.tristan.easyfxml.EasyFxml; import moe.tristan.easyfxml.model.exception.ExceptionHandler; import moe.tristan.easyfxml.util.Stages; import io.vavr.control.Try; import twitter4j.User; /** * This service serves as a helper for displaying a given user's detailed view. * * @see UserScreenComponent */ @Component public class UserDetailsService { private static final Logger LOG = LoggerFactory.getLogger(UserDetailsService.class); private final EasyFxml easyFxml; private final SessionManager sessionManager; private final UserScreenComponent userScreenComponent; @Autowired public UserDetailsService(EasyFxml easyFxml, SessionManager sessionManager, UserScreenComponent userScreenComponent) { this.easyFxml = easyFxml; this.sessionManager = sessionManager; this.userScreenComponent = userScreenComponent; } public void openUserDetails(final String screenName) { findUser(screenName) .onSuccess(this::openUserDetails) .onFailure(err -> ExceptionHandler.displayExceptionPane( "Unknown user!", "Can't map this user's screen name (@...) to an actual Twitter user!", err )); } public void openUserDetails(final long targetUserId) { findUser(targetUserId) .onSuccess(this::openUserDetails) .onFailure(err -> ExceptionHandler.displayExceptionPane( "Unknown user!", "Can't map this user's userId to an actual Twitter user!", err )); } /** * Opens the detailed view of a given user. * * @param targetUser the user whose detailed view is requested to be shown */ public void openUserDetails(final User targetUser) { LOG.info("Opening detailed view of user : {} (@{})", targetUser.getName(), targetUser.getScreenName()); easyFxml.load(userScreenComponent, Pane.class, UserViewController.class) .afterControllerLoaded(uvc -> uvc.targetUserProperty().setValue(targetUser)) .getNode() .recover(ExceptionHandler::fromThrowable) .onSuccess(userDetailsPane -> { final String stageTitle = targetUser.getName() + " (@" + targetUser.getScreenName() + ")"; Stages.stageOf(stageTitle, userDetailsPane).thenAcceptAsync(Stages::scheduleDisplaying); }); } @Cacheable("findByScreenNameUserCache") public Try<User> findUser(final String userScreenName) { return sessionManager.doWithCurrentTwitter(twitter -> twitter.showUser(userScreenName)); } @Cacheable("findByUserIdUserCache") public Try<User> findUser(final long userId) { return sessionManager.doWithCurrentTwitter(twitter -> twitter.showUser(userId)); } }
4,223
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
TwitterMediaExtensionFilter.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/twitter/util/TwitterMediaExtensionFilter.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.twitter.util; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Lazy; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import javafx.stage.FileChooser.ExtensionFilter; /** * Preconfigured extension filter helper for Twitter media. */ @Lazy @Component public class TwitterMediaExtensionFilter { private static final Logger LOG = LoggerFactory.getLogger(TwitterMediaExtensionFilter.class); private final ExtensionFilter extensionFilter; public TwitterMediaExtensionFilter(final Environment environment) { this.extensionFilter = buildExtensionFilter(environment); } public ExtensionFilter getExtensionFilter() { return extensionFilter; } /** * Builds the {@link ExtensionFilter} that will match allowed Twitter media types. * * @param environment The Spring {@link Environment} that will be used to fetch the allowed extensions from the * application.properties. * * @return A pre-made extension filter configured for only allowing Twitter-supported attachment types */ private static ExtensionFilter buildExtensionFilter(final Environment environment) { final String allowedExtensionsStr = environment.getRequiredProperty("twitter.media.allowedExtensions"); final List<String> allowedExtensions = Arrays.stream(allowedExtensionsStr.split(",")) .map(ext -> "*." + ext) .collect(Collectors.toList()); LOG.debug("Allowed media formats for tweet attachments are : {}", allowedExtensions); return new ExtensionFilter("Supported media types", allowedExtensions); } }
2,741
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
Timeline.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/twitter/observables/Timeline.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.twitter.observables; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; import moe.lyrebird.model.sessions.SessionManager; import moe.lyrebird.model.twitter.refresh.RateLimited; import moe.lyrebird.model.twitter.services.interraction.TwitterInteractionService; import twitter4j.Paging; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; /** * This class exposes the current user's timeline in an observable way */ @Lazy @Component public class Timeline extends TwitterTimelineBaseModel implements RateLimited { private static final Logger LOG = LoggerFactory.getLogger(Timeline.class); private final TwitterInteractionService interactionService; @Autowired public Timeline( final SessionManager sessionManager, final TwitterInteractionService interactionService ) { super(sessionManager); this.interactionService = interactionService; } @Override protected List<Status> initialLoad(final Twitter twitter) throws TwitterException { return twitter.getHomeTimeline() .stream() .filter(((Predicate<Status>) interactionService::isRetweetByCurrentUser).negate()) .collect(Collectors.toList()); } @Override protected List<Status> backfillLoad(final Twitter twitter, final Paging paging) throws TwitterException { return twitter.getHomeTimeline(paging) .stream() .filter(((Predicate<Status>) interactionService::isRetweetByCurrentUser).negate()) .collect(Collectors.toList()); } @Override protected Logger getLocalLogger() { return LOG; } @Override public int maxRequestsPer15Minutes() { return 15; } }
2,926
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
TwitterTimelineBaseModel.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/twitter/observables/TwitterTimelineBaseModel.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.twitter.observables; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import moe.lyrebird.model.sessions.SessionManager; import twitter4j.Paging; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; /** * This is the base class for reverse-chronologically sorted tweet lists (aka Timelines) backend model. */ public abstract class TwitterTimelineBaseModel { protected final SessionManager sessionManager; private final AtomicBoolean isFirstCall = new AtomicBoolean(true); private final ObservableList<Status> loadedTweets = FXCollections.observableList(new LinkedList<>()); public TwitterTimelineBaseModel(final SessionManager sessionManager) { this.sessionManager = sessionManager; } /** * @return The currently loaded tweets. */ public ObservableList<Status> loadedTweets() { return FXCollections.unmodifiableObservableList(loadedTweets); } /** * Asynchronously requests loading of tweets prior to the given status. * * @param loadUntilThisStatus the status whose prior tweets are requested */ public void loadMoreTweets(final long loadUntilThisStatus) { CompletableFuture.runAsync(() -> { getLocalLogger().debug("Requesting more tweets."); final Paging requestPaging = new Paging(); requestPaging.setMaxId(loadUntilThisStatus); sessionManager.getCurrentTwitter() .mapTry(twitter -> backfillLoad(twitter, requestPaging)) .onSuccess(this::addTweets); getLocalLogger().debug("Finished loading more tweets."); }); } /** * Asynchronously loads the last tweets available */ public void refresh() { CompletableFuture.runAsync(() -> { if (sessionManager.getCurrentTwitter().getOrElse((Twitter) null) == null) { return; } getLocalLogger().debug("Requesting last tweets in timeline."); sessionManager.getCurrentTwitter() .mapTry(this::initialLoad) .onSuccess(this::addTweets) .onFailure(err -> getLocalLogger().error("Could not refresh!", err)) .andThen(() -> isFirstCall.set(false)); }); } /** * Add a given list of tweets to the currently loaded ones. * * @param receivedTweets The tweets to add. */ private void addTweets(final List<Status> receivedTweets) { final int newTweets = receivedTweets.stream().map(this::addTweet).mapToInt(val -> val ? 1 : 0).sum(); getLocalLogger().debug("Loaded {} new tweets.", newTweets); } /** * Adds a single tweet to the list of currently loaded ones. * * @param newTweet The tweet to add. */ private boolean addTweet(final Status newTweet) { if (!this.loadedTweets.contains(newTweet)) { this.loadedTweets.add(newTweet); this.loadedTweets.sort(Comparator.comparingLong(Status::getId).reversed()); if (!isFirstCall.get()) { onNewElementStreamed(newTweet); } return true; } return false; } protected void onNewElementStreamed(final Status newElement) { // do nothing by default } /** * Remove all loaded tweets. */ void clearLoadedTweets() { loadedTweets.clear(); } /** * Performs the initial load of tweets (i.e. {@link #refresh()}). * * @param twitter The twitter instance to use * * @return The list of tweets received from Twitter * @throws TwitterException if there was an issue loading tweets */ protected abstract List<Status> initialLoad(final Twitter twitter) throws TwitterException; /** * Performs a request for loading more tweets (i.e. {@link #loadMoreTweets(long)}). * * @param twitter The twitter instance to use * @param paging Parameters for the request (containing the tweet whose prior tweets are requested for example) * * @return The list of tweets received from Twitter * @throws TwitterException if there was an issue loading tweets */ protected abstract List<Status> backfillLoad(final Twitter twitter, final Paging paging) throws TwitterException; /** * @return The subclass' logger that will be used for logging requests and potential errors */ protected abstract Logger getLocalLogger(); }
5,647
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
DirectMessages.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/twitter/observables/DirectMessages.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.twitter.observables; import java.util.Comparator; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.Predicate; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Component; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.ObservableMap; import moe.lyrebird.model.sessions.SessionManager; import moe.lyrebird.model.twitter.refresh.RateLimited; import twitter4j.DirectMessage; import twitter4j.User; @Component public class DirectMessages implements RateLimited { private static final Logger LOG = LoggerFactory.getLogger(DirectMessages.class); private final SessionManager sessionManager; private final ObservableMap<User, ObservableList<DirectMessage>> messageEvents; public DirectMessages(final SessionManager sessionManager) { this.sessionManager = sessionManager; LOG.debug("Initializing direct messages manager."); this.messageEvents = FXCollections.observableHashMap(); } public ObservableMap<User, ObservableList<DirectMessage>> directMessages() { return messageEvents; } @Override public void refresh() { if (!sessionManager.isLoggedInProperty().getValue()) { LOG.debug("Logged out, not refreshing direct messages."); return; } CompletableFuture.runAsync(() -> { LOG.debug("Requesting last direct messages."); sessionManager.getCurrentTwitter() .mapTry(twitter -> twitter.getDirectMessages(20)) .onSuccess(this::addDirectMessages) .onFailure(err -> LOG.error("Could not load direct messages successfully!", err)); }); } @Override public int maxRequestsPer15Minutes() { return 15; } private void addDirectMessages(final List<DirectMessage> loadedMessages) { final var knownMessages = messageEvents.values() .stream() .flatMap(List::stream) .collect(Collectors.toList()); final var newMessages = loadedMessages.stream() .filter(((Predicate<DirectMessage>) knownMessages::contains).negate()) .collect(Collectors.toList()); LOG.debug("Loaded {} new messages", newMessages.size()); newMessages.forEach(this::addDirectMessage); } public void addDirectMessage(final DirectMessage directMessageEvent) { final long otherId = getOtherId(directMessageEvent); final User other = messageEvents.keySet() .stream() .filter(user -> user.getId() == otherId) .findAny() .orElseGet(() -> showUser(otherId)); final ObservableList<DirectMessage> messagesWithOther = messageEvents.computeIfAbsent( other, k -> FXCollections.observableArrayList() ); messagesWithOther.add(directMessageEvent); messagesWithOther.sort(Comparator.comparingLong(DirectMessage::getId)); } private long getOtherId(final DirectMessage directMessageEvent) { return sessionManager.isCurrentUser(directMessageEvent.getSenderId()) ? directMessageEvent.getRecipientId() : directMessageEvent.getSenderId(); } @Cacheable(value = "userFromUserId", sync = true) public User showUser(final long userId) { return sessionManager.doWithCurrentTwitter( twitter -> twitter.showUser(userId) ).getOrElseThrow( err -> new IllegalStateException("Cannot find user with id " + userId, err) ); } }
4,922
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
UserTimeline.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/twitter/observables/UserTimeline.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.twitter.observables; import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javafx.beans.property.Property; import javafx.beans.property.SimpleObjectProperty; import moe.lyrebird.model.sessions.SessionManager; import twitter4j.Paging; import twitter4j.ResponseList; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.User; /** * This class exposes a user's self timeline in an observable way */ @Lazy @Component @Scope(SCOPE_PROTOTYPE) public class UserTimeline extends TwitterTimelineBaseModel { private static final Logger LOG = LoggerFactory.getLogger(UserTimeline.class); private final Property<User> targetUser = new SimpleObjectProperty<>(null); @Autowired public UserTimeline(final SessionManager sessionManager) { super(sessionManager); this.targetUser.addListener((o, prev, cur) -> { this.clearLoadedTweets(); refresh(); }); } /** * @return the {@link Property} for the user whose self timeline we are interested in */ public Property<User> targetUserProperty() { return targetUser; } @Override protected ResponseList<Status> initialLoad(final Twitter twitter) throws TwitterException { return twitter.getUserTimeline(targetUser.getValue().getId()); } @Override protected ResponseList<Status> backfillLoad(final Twitter twitter, final Paging paging) throws TwitterException { return twitter.getUserTimeline(targetUser.getValue().getId(), paging); } @Override protected Logger getLocalLogger() { return LOG; } }
2,807
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
Mentions.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/twitter/observables/Mentions.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.twitter.observables; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; import moe.lyrebird.model.notifications.Notification; import moe.lyrebird.model.notifications.NotificationService; import moe.lyrebird.model.notifications.format.TwitterNotifications; import moe.lyrebird.model.sessions.SessionManager; import moe.lyrebird.model.twitter.refresh.RateLimited; import twitter4j.Paging; import twitter4j.ResponseList; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; /** * This class exposes the current user's mentions in an observable way */ @Lazy @Component public class Mentions extends TwitterTimelineBaseModel implements RateLimited { private static final Logger LOG = LoggerFactory.getLogger(Mentions.class); private final NotificationService notificationService; public Mentions(final SessionManager sessionManager, final NotificationService notificationService) { super(sessionManager); this.notificationService = notificationService; } @Override protected ResponseList<Status> initialLoad(final Twitter twitter) throws TwitterException { return twitter.getMentionsTimeline(); } @Override protected ResponseList<Status> backfillLoad(final Twitter twitter, final Paging paging) throws TwitterException { return twitter.getMentionsTimeline(paging); } @Override protected void onNewElementStreamed(final Status newElement) { final Notification mentionNotification = TwitterNotifications.fromMention(newElement); notificationService.sendNotification(mentionNotification); } @Override protected Logger getLocalLogger() { return LOG; } @Override public int maxRequestsPer15Minutes() { return 75; } }
2,741
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
FXProperties.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/util/FXProperties.java
package moe.lyrebird.model.util; import java.util.function.Consumer; import javafx.beans.value.ObservableValue; public final class FXProperties { private FXProperties() { } public static <T> void waitForProp(final ObservableValue<T> prop, final Consumer<T> onReady) { if (prop.getValue() == null) { prop.addListener((observable, oldValue, newValue) -> onReady.accept(newValue)); } else { onReady.accept(prop.getValue()); } } public static void waitForBooleanProp(final ObservableValue<Boolean> prop, final Runnable onReady) { if (prop.getValue() != null && prop.getValue()) { onReady.run(); } else { prop.addListener((observable, oldValue, newValue) -> { if (newValue) { onReady.run(); } }); } } }
889
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z
URLMatcher.java
/FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/model/util/URLMatcher.java
/* * Lyrebird, a free open-source cross-platform twitter client. * Copyright (C) 2017-2018, Tristan Deloche * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.lyrebird.model.util; import java.util.List; import java.util.function.Function; import java.util.regex.MatchResult; import java.util.regex.Pattern; import java.util.stream.Collectors; import io.vavr.Tuple; import io.vavr.Tuple3; /** * This class provides helper methods for filtering out URLs in text and extracting them out. */ public final class URLMatcher { private static final String URL_REGEX = "(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"; private static final Pattern URL_PATTERN = Pattern.compile(URL_REGEX); private URLMatcher() { throw new UnsupportedOperationException("Should not be instantiated."); } /** * Transforms all the URLs in an input String. * * @param input The input string * @param replacer The transformation function * * @return The resulting string */ public static String transformUrls(final String input, final Function<String, String> replacer) { return URL_PATTERN.matcher(input).replaceAll(match -> replacer.apply(match.group())); } /** * Extracts all the URLs from the given input String. * * @param input The input string * * @return The list of all URLs matching {@link #URL_REGEX} in the input */ public static List<String> findAllUrls(final String input) { return URL_PATTERN.matcher(input).results().map(MatchResult::group).collect(Collectors.toList()); } public static List<Tuple3<String, Integer, Integer>> findAllUrlsWithPosition(final String input) { return URL_PATTERN.matcher(input).results().map( result -> Tuple.of(result.group(), result.start(), result.end()) ).collect(Collectors.toList()); } /** * Strips/trims all the URLs in the input String * * @param input The input string * * @return The resulting string */ public static String stripAllUrls(final String input) { return transformUrls(input, url -> ""); } public static boolean isUrl(final String input) { return URL_PATTERN.matcher(input).matches(); } }
2,966
Java
.java
Tristan971/Lyrebird
34
9
10
2017-02-05T19:44:00Z
2020-09-27T21:13:06Z