Java Code Examples for org.springframework.messaging.simp.annotation.SendToUser

The following examples show how to use org.springframework.messaging.simp.annotation.SendToUser. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@MessageMapping("/create/empty")
@SendToUser(broadcast = false)
public int createEmptyPlaylist(Principal p) {
    Locale locale = localeResolver.resolveLocale(p.getName());
    DateTimeFormatter dateFormat = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.SHORT).withLocale(locale);

    Instant now = Instant.now();
    Playlist playlist = new Playlist();
    playlist.setUsername(p.getName());
    playlist.setCreated(now);
    playlist.setChanged(now);
    playlist.setShared(false);
    playlist.setName(dateFormat.format(now.atZone(ZoneId.systemDefault())));

    playlistService.createPlaylist(playlist);

    return playlist.getId();
}
 
Example 2
@MessageMapping("/create/starred")
@SendToUser(broadcast = false)
public int createPlaylistForStarredSongs(Principal p) {
    Locale locale = localeResolver.resolveLocale(p.getName());
    DateTimeFormatter dateFormat = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.SHORT).withLocale(locale);

    Instant now = Instant.now();
    Playlist playlist = new Playlist();
    playlist.setUsername(p.getName());
    playlist.setCreated(now);
    playlist.setChanged(now);
    playlist.setShared(false);

    ResourceBundle bundle = ResourceBundle.getBundle("org.airsonic.player.i18n.ResourceBundle", locale);
    playlist.setName(bundle.getString("top.starred") + " " + dateFormat.format(now.atZone(ZoneId.systemDefault())));

    playlistService.createPlaylist(playlist);
    List<MusicFolder> musicFolders = settingsService.getMusicFoldersForUser(p.getName());
    List<MediaFile> songs = mediaFileDao.getStarredFiles(0, Integer.MAX_VALUE, p.getName(), musicFolders);
    playlistService.setFilesInPlaylist(playlist.getId(), songs);

    return playlist.getId();
}
 
Example 3
@MessageMapping("/create/playqueue")
@SendToUser(broadcast = false)
public int createPlaylistForPlayQueue(Principal p, Integer playerId) throws Exception {
    Player player = playerService.getPlayerById(playerId);
    Locale locale = localeResolver.resolveLocale(p.getName());
    DateTimeFormatter dateFormat = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.SHORT).withLocale(locale);

    Instant now = Instant.now();
    Playlist playlist = new Playlist();
    playlist.setUsername(p.getName());
    playlist.setCreated(now);
    playlist.setChanged(now);
    playlist.setShared(false);
    playlist.setName(dateFormat.format(now.atZone(ZoneId.systemDefault())));

    playlistService.createPlaylist(playlist);
    playlistService.setFilesInPlaylist(playlist.getId(), player.getPlayQueue().getFiles());

    return playlist.getId();
}
 
Example 4
private DestinationHelper getDestinationHelper(MessageHeaders headers, MethodParameter returnType) {
	SendToUser m1 = AnnotatedElementUtils.findMergedAnnotation(returnType.getExecutable(), SendToUser.class);
	SendTo m2 = AnnotatedElementUtils.findMergedAnnotation(returnType.getExecutable(), SendTo.class);
	if ((m1 != null && !ObjectUtils.isEmpty(m1.value())) || (m2 != null && !ObjectUtils.isEmpty(m2.value()))) {
		return new DestinationHelper(headers, m1, m2);
	}

	SendToUser c1 = AnnotatedElementUtils.findMergedAnnotation(returnType.getDeclaringClass(), SendToUser.class);
	SendTo c2 = AnnotatedElementUtils.findMergedAnnotation(returnType.getDeclaringClass(), SendTo.class);
	if ((c1 != null && !ObjectUtils.isEmpty(c1.value())) || (c2 != null && !ObjectUtils.isEmpty(c2.value()))) {
		return new DestinationHelper(headers, c1, c2);
	}

	return (m1 != null || m2 != null ?
			new DestinationHelper(headers, m1, m2) : new DestinationHelper(headers, c1, c2));
}
 
Example 5
private DestinationHelper getDestinationHelper(MessageHeaders headers, MethodParameter returnType) {
	SendToUser m1 = AnnotatedElementUtils.findMergedAnnotation(returnType.getExecutable(), SendToUser.class);
	SendTo m2 = AnnotatedElementUtils.findMergedAnnotation(returnType.getExecutable(), SendTo.class);
	if ((m1 != null && !ObjectUtils.isEmpty(m1.value())) || (m2 != null && !ObjectUtils.isEmpty(m2.value()))) {
		return new DestinationHelper(headers, m1, m2);
	}

	SendToUser c1 = AnnotatedElementUtils.findMergedAnnotation(returnType.getDeclaringClass(), SendToUser.class);
	SendTo c2 = AnnotatedElementUtils.findMergedAnnotation(returnType.getDeclaringClass(), SendTo.class);
	if ((c1 != null && !ObjectUtils.isEmpty(c1.value())) || (c2 != null && !ObjectUtils.isEmpty(c2.value()))) {
		return new DestinationHelper(headers, c1, c2);
	}

	return (m1 != null || m2 != null ?
			new DestinationHelper(headers, m1, m2) : new DestinationHelper(headers, c1, c2));
}
 
Example 6
@MessageMapping("/files/append")
@SendToUser(broadcast = false)
public int appendToPlaylist(PlaylistFilesModificationRequest req) {
    // in this context, modifierIds are mediafile ids
    List<MediaFile> files = Stream
            .concat(playlistService.getFilesInPlaylist(req.getId(), true).stream(),
                    req.getModifierIds().stream().map(mediaFileService::getMediaFile).filter(Objects::nonNull))
            .collect(Collectors.toList());

    playlistService.setFilesInPlaylist(req.getId(), files);

    return req.getId();
}
 
Example 7
@MessageMapping("/files/remove")
@SendToUser(broadcast = false)
public int remove(PlaylistFilesModificationRequest req) {
    // in this context, modifierIds are indices
    List<MediaFile> files = playlistService.getFilesInPlaylist(req.getId(), true);
    List<Integer> indices = req.getModifierIds();
    Collections.sort(indices);
    for (int i = 0; i < indices.size(); i++) {
        // factor in previous indices we've deleted so far
        files.remove(indices.get(i) - i);
    }
    playlistService.setFilesInPlaylist(req.getId(), files);

    return req.getId();
}
 
Example 8
@MessageMapping("/files/moveup")
@SendToUser(broadcast = false)
public int up(PlaylistFilesModificationRequest req) {
    // in this context, modifierIds has one element that is the index of the file
    List<MediaFile> files = playlistService.getFilesInPlaylist(req.getId(), true);
    if (req.getModifierIds().size() == 1 && req.getModifierIds().get(0) > 0) {
        Collections.swap(files, req.getModifierIds().get(0), req.getModifierIds().get(0) - 1);
        playlistService.setFilesInPlaylist(req.getId(), files);
    }

    return req.getId();
}
 
Example 9
@MessageMapping("/files/movedown")
@SendToUser(broadcast = false)
public int down(PlaylistFilesModificationRequest req) {
    // in this context, modifierIds has one element that is the index of the file
    List<MediaFile> files = playlistService.getFilesInPlaylist(req.getId(), true);
    if (req.getModifierIds().size() == 1 && req.getModifierIds().get(0) < files.size() - 1) {
        Collections.swap(files, req.getModifierIds().get(0), req.getModifierIds().get(0) + 1);
        playlistService.setFilesInPlaylist(req.getId(), files);
    }

    return req.getId();
}
 
Example 10
@MessageMapping("/files/rearrange")
@SendToUser(broadcast = false)
public int rearrange(PlaylistFilesModificationRequest req) {
    // in this context, modifierIds are indices
    List<MediaFile> files = playlistService.getFilesInPlaylist(req.getId(), true);
    MediaFile[] newFiles = new MediaFile[files.size()];
    for (int i = 0; i < req.getModifierIds().size(); i++) {
        newFiles[i] = files.get(req.getModifierIds().get(i));
    }
    playlistService.setFilesInPlaylist(req.getId(), Arrays.asList(newFiles));

    return req.getId();
}
 
Example 11
/**
 * Updated tags for a given music file.
 *
 * @return "UPDATED" if the new tags were updated, "SKIPPED" if no update was necessary.
 *         Otherwise the error message is returned.
 */
@MessageMapping("/edit")
@SendToUser(broadcast = false)
public String setTags(@Validated TagData data) {
    try {
        MediaFile file = mediaFileService.getMediaFile(data.getMediaFileId());
        MetaDataParser parser = metaDataParserFactory.getParser(file.getFile());

        if (!parser.isEditingSupported()) {
            return "Tag editing of " + FilenameUtils.getExtension(file.getPath()) + " files is not supported.";
        }

        if (StringUtils.equals(data.getArtist(), file.getArtist())
                && StringUtils.equals(data.getAlbum(), file.getAlbumName())
                && StringUtils.equals(data.getTitle(), file.getTitle())
                && ObjectUtils.equals(data.getYear(), file.getYear())
                && StringUtils.equals(data.getGenre(), file.getGenre())
                && ObjectUtils.equals(data.getTrack(), file.getTrackNumber())) {
            return "SKIPPED";
        }

        MetaData newMetaData = parser.getMetaData(file.getFile());

        // Note: album artist is intentionally not set, as it is not user-changeable.
        newMetaData.setArtist(data.getArtist());
        newMetaData.setAlbumName(data.getAlbum());
        newMetaData.setTitle(data.getTitle());
        newMetaData.setYear(data.getYear());
        newMetaData.setGenre(data.getGenre());
        newMetaData.setTrackNumber(data.getTrack());
        parser.setMetaData(file, newMetaData);
        mediaFileService.refreshMediaFile(file);
        mediaFileService.refreshMediaFile(mediaFileService.getParentOf(file));
        return "UPDATED";

    } catch (Exception x) {
        LOG.warn("Failed to update tags for " + data.getMediaFileId(), x);
        return x.getMessage();
    }
}
 
Example 12
@MessageMapping("/sidebar")
@SendToUser
public boolean setShowSideBar(Principal p, boolean show) {
    UserSettings userSettings = settingsService.getUserSettings(p.getName());
    if (show != userSettings.getShowSideBar()) {
        userSettings.setShowSideBar(show);
        userSettings.setChanged(Instant.now());
        settingsService.updateUserSettings(userSettings);
    }
    return show;
}
 
Example 13
@MessageMapping("/viewAsList")
@SendToUser
public boolean setViewAsList(Principal p, boolean viewAsList) {
    UserSettings userSettings = settingsService.getUserSettings(p.getName());
    if (viewAsList != userSettings.getViewAsList()) {
        userSettings.setViewAsList(viewAsList);
        userSettings.setChanged(Instant.now());
        settingsService.updateUserSettings(userSettings);
    }
    return viewAsList;
}
 
Example 14
/**
 * Downloads and saves the cover art at the given URL.
 *
 * @return The error string if something goes wrong, <code>"OK"</code> otherwise.
 */
@MessageMapping("/set")
@SendToUser(broadcast = false)
public String setCoverArtImage(CoverArtSetRequest req) {
    try {
        MediaFile mediaFile = mediaFileService.getMediaFile(req.getAlbumId());
        saveCoverArt(mediaFile.getPath(), req.getUrl());
        return "OK";
    } catch (Exception e) {
        LOG.warn("Failed to save cover art for album {}", req.getAlbumId(), e);
        return e.toString();
    }
}
 
Example 15
@MessageMapping("/info")
@SendToUser(broadcast = false)
public ArtistInfo getArtistInfo(Principal principal, ArtistInfoRequest req) {
    MediaFile mediaFile = mediaFileService.getMediaFile(req.getMediaFileId());
    List<SimilarArtist> similarArtists = getSimilarArtists(principal.getName(), req.getMediaFileId(), req.getMaxSimilarArtists());
    ArtistBio artistBio = lastFmService.getArtistBio(mediaFile, localeResolver.resolveLocale(principal.getName()));
    List<MediaFileEntry> topSongs = getTopSongs(principal.getName(), mediaFile, req.getMaxTopSongs());

    return new ArtistInfo(similarArtists, artistBio, topSongs);
}
 
Example 16
@Override
public boolean supportsReturnType(MethodParameter returnType) {
	return (returnType.hasMethodAnnotation(SendTo.class) ||
			AnnotatedElementUtils.hasAnnotation(returnType.getDeclaringClass(), SendTo.class) ||
			returnType.hasMethodAnnotation(SendToUser.class) ||
			AnnotatedElementUtils.hasAnnotation(returnType.getDeclaringClass(), SendToUser.class) ||
			!this.annotationRequired);
}
 
Example 17
Source Project: Project   Source File: SpittrMessageController.java    License: Apache License 2.0 5 votes vote down vote up
@MessageMapping("/spittle")
@SendToUser("/queue/notifications")
public Notification handleSpittle(Principal principal, SpittleForm form) {
	System.out.println("访问spittle");
	Spittle spittle = new Spittle(principal.getName(), form.getText(), new Date());
	spittleRepo.save(spittle);
	feedService.broadcastSpittle(spittle);
	return new Notification("Saved Spittle for user: " + principal.getName());
}
 
Example 18
@Override
public boolean supportsReturnType(MethodParameter returnType) {
	return (returnType.hasMethodAnnotation(SendTo.class) ||
			AnnotatedElementUtils.hasAnnotation(returnType.getDeclaringClass(), SendTo.class) ||
			returnType.hasMethodAnnotation(SendToUser.class) ||
			AnnotatedElementUtils.hasAnnotation(returnType.getDeclaringClass(), SendToUser.class) ||
			!this.annotationRequired);
}
 
Example 19
@Override
public boolean supportsReturnType(MethodParameter returnType) {
	if (returnType.getMethodAnnotation(SendTo.class) != null ||
			returnType.getMethodAnnotation(SendToUser.class) != null) {
		return true;
	}
	return (!this.annotationRequired);
}
 
Example 20
@MessageMapping("/save")
@SendToUser
public int savePlayQueue(@DestinationVariable int playerId, PlayQueueRequest req, SimpMessageHeaderAccessor headers) throws Exception {
    Player player = getPlayer(playerId, headers);
    return playQueueService.savePlayQueue(player, req.getIndex(), req.getOffset());
}
 
Example 21
@MessageMapping("/writable")
@SendToUser(broadcast = false)
public List<Playlist> getWritablePlaylists(Principal p) {
    return playlistService.getWritablePlaylistsForUser(p.getName());
}
 
Example 22
@MessageMapping("/files/{id}")
@SendToUser(broadcast = false)
public List<MediaFileEntry> getPlaylistEntries(Principal p, @DestinationVariable int id) {
    return mediaFileService.toMediaFileEntryList(playlistService.getFilesInPlaylist(id, true), p.getName(), true, true, null, null, null);
}
 
Example 23
@MessageMapping("/search")
@SendToUser(broadcast = false)
public List<LastFmCoverArt> searchCoverArt(CoverArtSearchRequest req) {
    return lastFmService.searchCoverArt(req.getArtist(), req.getAlbum());
}
 
Example 24
@MessageMapping("/directory/get")
@SendToUser(broadcast = false)
public Object get(Principal user, MediaDirectoryRequest req, SimpMessageHeaderAccessor headers) throws Exception {
    List<MediaFile> mediaFiles = getMediaFiles(req.getIds(), req.getPaths());

    if (mediaFiles.isEmpty()) {
        return ImmutableMap.of("contentType", "notFound");
    }

    MediaFile dir = mediaFiles.get(0);
    if (dir.isFile()) {
        dir = mediaFileService.getParentOf(dir);
    }

    // Redirect if root directory.
    if (mediaFileService.isRoot(dir)) {
        return ImmutableMap.of("contentType", "home");
    }

    if (!securityService.isFolderAccessAllowed(dir, user.getName())) {
        return ImmutableMap.of("contentType", "accessDenied");
    }

    List<MediaFile> children = getChildren(mediaFiles);

    List<MediaFile> files = new ArrayList<>();
    List<MediaFile> subDirs = new ArrayList<>();
    for (MediaFile child : children) {
        if (child.isFile()) {
            files.add(child);
        } else {
            subDirs.add(child);
        }
    }
    MediaFileDirectoryEntry entry = new MediaFileDirectoryEntry(mediaFileService.toMediaFileEntryList(Collections.singletonList(dir), user.getName(), true, true, null, null, null).get(0));
    entry.setFiles(mediaFileService.toMediaFileEntryList(files, user.getName(), true, false, null, null, null));
    entry.setSubDirs(mediaFileService.toMediaFileEntryList(subDirs, user.getName(), false, false, null, null, null));
    entry.setAncestors(mediaFileService.toMediaFileEntryList(getAncestors(dir), user.getName(), false, false, null, null, null));
    entry.setLastPlayed(dir.getLastPlayed());
    entry.setPlayCount(dir.getPlayCount());
    entry.setComment(dir.getComment());
    if (dir.isAlbum()) {
        List<MediaFile> siblingAlbums = getSiblingAlbums(dir);
        entry.setSiblingAlbums(mediaFileService.toMediaFileEntryList(siblingAlbums, user.getName(), false, false, null, null, null));
        entry.setAlbum(guessAlbum(children));
        entry.setArtist(guessArtist(children));
        entry.setMusicBrainzReleaseId(guessMusicBrainzReleaseId(children));
    }

    Integer userRating = Optional.ofNullable(ratingService.getRatingForUser(user.getName(), dir)).orElse(0);
    Double averageRating = Optional.ofNullable(ratingService.getAverageRating(dir)).orElse(0.0D);

    entry.setUserRating(10 * userRating);
    entry.setAverageRating(10.0D * averageRating);

    if (isVideoOnly(children)) {
        entry.setContentType("video");
    } else if (dir.isAlbum()) {
        entry.setContentType("album");
    } else {
        entry.setContentType("artist");
    }

    return entry;
}
 
Example 25
/**
 * Returns lyrics for the given song and artist.
 *
 * @return The lyrics, never <code>null</code> .
 */
@MessageMapping("/get")
@SendToUser(broadcast = false)
public LyricsInfo getLyrics(LyricsGetRequest req) {
    return getLyrics(req.getArtist(), req.getSong());
}
 
Example 26
@Override
public boolean supportsReturnType(MethodParameter returnType) {
	return (returnType.hasMethodAnnotation(SubscribeMapping.class) &&
			!returnType.hasMethodAnnotation(SendTo.class) &&
			!returnType.hasMethodAnnotation(SendToUser.class));
}
 
Example 27
public DestinationHelper(MessageHeaders headers, @Nullable SendToUser sendToUser, @Nullable SendTo sendTo) {
	Map<String, String> variables = getTemplateVariables(headers);
	this.placeholderResolver = variables::get;
	this.sendTo = sendTo;
	this.sendToUser = sendToUser;
}
 
Example 28
@Nullable
public SendToUser getSendToUser() {
	return this.sendToUser;
}
 
Example 29
@SendToUser
@SuppressWarnings("unused")
String handleAndSendToUserDefaultDest() {
	return PAYLOAD;
}
 
Example 30
@SendToUser(broadcast = false)
@SuppressWarnings("unused")
String handleAndSendToUserDefaultDestInSession() {
	return PAYLOAD;
}