Skip to content

Instantly share code, notes, and snippets.

@javadev
Created July 19, 2018 07:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save javadev/ee9125159334076db8f9c1420f5ed54a to your computer and use it in GitHub Desktop.
Save javadev/ee9125159334076db8f9c1420f5ed54a to your computer and use it in GitHub Desktop.
jhipster:
fcm:
serverKey: AAAAgPXvlB0:APA91bH5EjaPnNt_V___tEJGX4WtFZE_yYwDNK1cmKQr3wzas3jahiSht0r3d1hVhdLCliBRiIhklqvfxoc-0pcdhZXeeYMMmRICV5NAo2YGTJxaOqm4_OyjXssHZGvvCtXM03n7Vm87
serverUrl: "https://fcm.googleapis.com/"
senderId: 553881932829
package no.lavoapp.service;
import no.lavoapp.domain.User;
import no.lavoapp.domain.Video;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class EventService {
private NotificationService notificationService;
@Autowired
public EventService(NotificationService notificationService) {
this.notificationService = notificationService;
}
@Async
public void videoResponseCreated(User originator, Video video) {
notificationService.videoResponse(originator, video);
}
@Async
public void videoCreated(User originator, Video video) {
notificationService.videoCreated(originator, video);
}
@Async
public void sendNotificationForVideo(Video video) {
notificationService.sendNotificationForVideo(video);
}
}
package no.lavoapp.service.external;
import io.reactivex.Observable;
import no.lavoapp.config.JHipsterProperties;
import no.lavoapp.domain.Device;
import no.lavoapp.domain.Notification;
import no.lavoapp.domain.external.FcmNotification;
import no.lavoapp.domain.external.FcmNotificationMultiPayload;
import no.lavoapp.domain.external.FcmNotificationSinglePayload;
import no.lavoapp.domain.external.FcmResponse;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class FcmService {
private final String SERVER_KEY;
private final String SERVER_URL;
private final String SENDER_ID;
private final Logger log = LoggerFactory.getLogger(FcmService.class);
private FcmInterface fcmInterface;
@Inject
public FcmService(JHipsterProperties jHipsterProperties) {
SERVER_KEY = jHipsterProperties.getFcm().getServerKey();
SERVER_URL = jHipsterProperties.getFcm().getServerUrl();
SENDER_ID = jHipsterProperties.getFcm().getSenderId();
}
/*
* Отсылка нотификации
*/
public Observable<FcmResponse> sendNotificationToDevice(Notification notification, Device device) {
if (fcmInterface == null) { fcmInterface = createFcmService(); }
return fcmInterface.sendNotification(new FcmNotificationSinglePayload(device.getDeviceId(),
new FcmNotification(notification)));
}
public Observable<FcmResponse> sendNotificationsToDevices(List<Device> devices, Notification notification) {
if (fcmInterface == null) {fcmInterface = createFcmService(); }
List<String> deviceStrings = devices.stream().map(Device::getDeviceId).collect(Collectors.toList());
return fcmInterface.sendNotifications(new FcmNotificationMultiPayload(deviceStrings,
new FcmNotification(notification)));
}
private FcmInterface createFcmService() {
return ServiceFactory.createRetrofitService(FcmInterface.class, new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", "key=" + SERVER_KEY)
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
}, SERVER_URL);
}
}
package no.lavoapp.service.impl;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import no.lavoapp.domain.Device;
import no.lavoapp.domain.User;
import no.lavoapp.domain.Video;
import no.lavoapp.domain.enumeration.NotificationState;
import no.lavoapp.domain.enumeration.NotificationType;
import no.lavoapp.domain.external.FcmResponse;
import no.lavoapp.repository.DeviceRepository;
import no.lavoapp.repository.UserRepository;
import no.lavoapp.repository.VideoRepository;
import no.lavoapp.service.NotificationService;
import no.lavoapp.domain.Notification;
import no.lavoapp.repository.NotificationRepository;
import no.lavoapp.repository.search.NotificationSearchRepository;
import no.lavoapp.service.UserService;
import no.lavoapp.service.dto.NotificationDTO;
import no.lavoapp.service.external.FcmService;
import no.lavoapp.service.mapper.NotificationMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.time.ZonedDateTime;
import static java.util.Objects.requireNonNull;
import static org.elasticsearch.index.query.QueryBuilders.*;
/**
* Service Implementation for managing Notification.
*/
@Service
@Transactional
public class NotificationServiceImpl implements NotificationService{
private final Logger log = LoggerFactory.getLogger(NotificationServiceImpl.class);
@Inject
private NotificationRepository notificationRepository;
@Inject
private NotificationMapper notificationMapper;
@Inject
private NotificationSearchRepository notificationSearchRepository;
@Inject
private FcmService fcmService;
@Inject
private DeviceRepository deviceRepository;
@Inject
private UserRepository userRepository;
@Inject
private VideoRepository videoRepository;
@Inject
private UserService userService;
/**
* Save a notification.
*
* @param notificationDTO the entity to save
* @return the persisted entity
*/
public NotificationDTO save(NotificationDTO notificationDTO) {
log.debug("Request to save Notification : {}", notificationDTO);
Notification notification = notificationMapper.notificationDTOToNotification(notificationDTO);
User user = userRepository.findOneByLogin(notificationDTO.getReceiverLogin()).get();
notification.setCreatedDate(ZonedDateTime.now());
notification.setOriginator(userService.getUserWithAuthorities());
notification.setUser(user);
notification.setState(NotificationState.WAITING);
for (Device device : deviceRepository.findByUser(user)) {
fcmService.sendNotificationToDevice(notification, device)
.subscribe(attachObserver(notification));
}
notification = notificationRepository.save(notification);
NotificationDTO result = notificationMapper.notificationToNotificationDTO(notification);
notificationSearchRepository.save(notification);
return result;
}
/**
* Get all the notifications.
*
* @param pageable the pagination information
* @return the list of entities
*/
@Transactional(readOnly = true)
public Page<NotificationDTO> findAll(Pageable pageable) {
log.debug("Request to get all Notifications");
Page<Notification> result = notificationRepository.findAll(pageable);
return result.map(notification -> notificationMapper.notificationToNotificationDTO(notification));
}
/**
* Get one notification by id.
*
* @param id the id of the entity
* @return the entity
*/
@Transactional(readOnly = true)
public NotificationDTO findOne(Long id) {
log.debug("Request to get Notification : {}", id);
Notification notification = notificationRepository.findOne(id);
NotificationDTO notificationDTO = notificationMapper.notificationToNotificationDTO(notification);
return notificationDTO;
}
/**
* Delete the notification by id.
*
* @param id the id of the entity
*/
public void delete(Long id) {
log.debug("Request to delete Notification : {}", id);
notificationRepository.delete(id);
notificationSearchRepository.delete(id);
}
/**
* Search for the notification corresponding to the query.
*
* @param query the query of the search
* @return the list of entities
*/
@Transactional(readOnly = true)
public Page<NotificationDTO> search(String query, Pageable pageable) {
log.debug("Request to search for a page of Notifications for query {}", query);
Page<Notification> result = notificationSearchRepository.search(queryStringQuery(query), pageable);
return result.map(notification -> notificationMapper.notificationToNotificationDTO(notification));
}
/**
* Send notification to the parent of the video
* @param video
*/
public void videoResponse(User originator, Video video) {
requireNonNull(video);
requireNonNull(originator);
if (video.getParent() == null) return;
log.debug("Request to send notification to parent of response: {}", video.getParent());
Video parentVideo = videoRepository.findOne(video.getParent().getId()); // this to ensure the user is attached
create(NotificationType.VIDEO_RESPONSE, video, originator, parentVideo.getUser());
}
/**
* Save and send notification to the followers of the newly created video
* @param video
*/
public void videoCreated(User originator, Video video) {
requireNonNull(video);
requireNonNull(originator);
if (video.getUser() == null) {
log.warn("Request to send notifications to followers failed, video.getUser() is null");
return;
}
log.debug("Request to create a new notification to followers of user: {}", video.getUser().getLogin());
userRepository.followers(video.getUser())
.forEach(follower -> create(NotificationType.FOLLOWER_VIDEO, video, originator, follower));
}
/**
* Send notifications for video
* @param video
* !!! Пример отсылки нотификаци для видео
*/
public void sendNotificationForVideo(Video video) {
notificationRepository.findByVideoAndState(video, NotificationState.WAITING).forEach(notification ->
deviceRepository.findByUser(notification.getUser()).forEach(device ->
fcmService.sendNotificationToDevice(notification, device).subscribe(attachObserver(notification))
));
}
/**
* Create a new notification for video, device and user
* @param video
* @param originator
* @param receiver
* @return the notification
*/
public Notification create(NotificationType type, Video video, User originator, User receiver) {
log.debug("Request to create a new notification, video: {}, originator: {}, receiver: {}",
video, originator.getLogin(), receiver.getLogin());
Notification notification = new Notification();
notification.setTitle("New video: " + video.getTitle());
String body = "" + originator.getNickName();
switch (type) {
case FOLLOWER_VIDEO:
body += " has posted a new video";
break;
case VIDEO_RESPONSE:
body += " has posted a response to your video";
break;
case NEW_FOLLOWER:
break;
case SHARED_VIDEO:
break;
}
notification.setBody(body);
notification.setType(type);
notification.setCreatedDate(ZonedDateTime.now());
notification.setUser(receiver);
notification.setOriginator(originator);
notification.setVideo(video);
notification.setState(NotificationState.WAITING);
notification = notificationRepository.save(notification);
notificationSearchRepository.save(notification);
return notification;
}
private Observer<FcmResponse> attachObserver(Notification notification) {
return new Observer<FcmResponse>() {
@Override
public void onSubscribe(Disposable d) {}
@Override
public void onNext(FcmResponse fcmResponse) {
log.debug("Saving the fcmResponse on notification object {}", fcmResponse);
notification.setMessageId(fcmResponse.getResults().get(0).getMessageId());
notification.setState(NotificationState.SENT);
notificationRepository.save(notification);
notificationSearchRepository.save(notification);
}
@Override
public void onError(Throwable e) {
log.debug("Received an error from FCM: {}", e.getMessage());
}
@Override
public void onComplete() {}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment