Search in sources :

Example 1 with Device

use of com.google.samples.apps.iosched.server.gcm.db.models.Device in project iosched by google.

the class SendMessageServlet method doPost.

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Extract URL components
    String result = req.getPathInfo();
    if (result == null) {
        send(resp, 400, "Bad request (check request format)");
        return;
    }
    String[] components = result.split("/");
    if (components.length != 3) {
        send(resp, 400, "Bad request (check request format)");
        return;
    }
    String target = components[1];
    String action = components[2];
    // Let's see what this user is authorized to do
    AuthInfo authInfo = AuthHelper.processAuthorization(req);
    // If no auth info or non-admin trying to run non-whitelisted actions, no access.
    if (authInfo == null || action == null || (!UNPRIVILEGED_ACTIONS.contains(action) && !authInfo.permAdmin)) {
        send(resp, 403, "Not authorized");
        return;
    }
    // Extract extraData
    String payload = readBody(req);
    // Request decoding complete. Log request parameters
    LOG.info("Authorized User: " + authInfo.clientName + "\nTarget: " + target + "\nAction: " + action + "\nExtra Data: " + payload);
    MessageSender sender = new MessageSender(getServletConfig());
    // what's the audience of the message?
    if ("global".equals(target)) {
        // Only admins can spam the world
        if (!authInfo.permAdmin) {
            LOG.info("Attempt to send global message, but no admin perm.");
            send(resp, 403, "Not authorized");
            return;
        }
        List<Device> allDevices = DeviceStore.getAllDevices();
        if (allDevices == null || allDevices.isEmpty()) {
            send(resp, 404, "No devices registered");
        } else {
            int resultCount = allDevices.size();
            LOG.info("Selected " + resultCount + " devices");
            sender.multicastSend(allDevices, action, payload);
            send(resp, 200, "Message queued: " + resultCount + " devices");
        }
    } else {
        // If target is SELF, the GCM Group ID will be the auth key in header
        if (SELF.equals(target)) {
            // do we have permission to send message to self?
            if (!authInfo.permSendSelfMessage) {
                LOG.info("Attempt to send self message, but no self message perm.");
                send(resp, 403, "Not authorized");
                return;
            }
            // the target is the auth key (it represents the group)
            target = authInfo.authKey;
        } else {
            // sending message to a specific user. Only admin can do it.
            if (!authInfo.permAdmin) {
                LOG.info("Attempt to send message to specific target, but no admin perm.");
                send(resp, 403, "Not authorized");
                return;
            }
        }
        List<Device> userDevices = DeviceStore.findDevicesByGcmGroupId(target);
        if (userDevices == null || userDevices.isEmpty()) {
            send(resp, 404, "User not found");
        } else {
            int resultCount = userDevices.size();
            LOG.info("Selected " + resultCount + " devices");
            sender.multicastSend(userDevices, action, payload);
            send(resp, 200, "Message queued: " + resultCount + " devices");
        }
    }
}
Also used : AuthInfo(com.google.samples.apps.iosched.server.gcm.AuthHelper.AuthInfo) MessageSender(com.google.samples.apps.iosched.server.gcm.device.MessageSender) Device(com.google.samples.apps.iosched.server.gcm.db.models.Device)

Example 2 with Device

use of com.google.samples.apps.iosched.server.gcm.db.models.Device in project iosched by google.

the class FcmRegistrationEndpoint method unregister.

/**
 * Remove a registration of a user's device. When a user signs out of a client they should
 * unregister. This will prevent messages from being sent to the wrong user if multiple users
 * are using the same device.
 *
 * @param deviceId FCM token representing the device.
 * @return Result containing a message about the un-registration.
 * @throws BadRequestException Thrown when there is no device ID in the request.
 */
@ApiMethod(path = "unregister", httpMethod = HttpMethod.POST)
public void unregister(User user, @Named(PARAMETER_DEVICE_ID) String deviceId) throws BadRequestException, UnauthorizedException, com.google.api.server.spi.response.NotFoundException, ForbiddenException {
    // Check to see if deviceId.
    if (Strings.isNullOrEmpty(deviceId)) {
        // Drop request.
        throw new BadRequestException("Invalid request: Request must contain " + PARAMETER_DEVICE_ID);
    }
    // Check that user making requests is non null.
    if (user == null) {
        throw new UnauthorizedException("Invalid credentials");
    }
    try {
        Device device = ofy().load().type(Device.class).id(deviceId).safe();
        // Check that the user trying to unregister the token is the same one that registered it.
        if (!device.getUserId().equals(user.getId())) {
            throw new ForbiddenException("Not authorized to unregister token");
        }
        DeviceStore.unregister(deviceId);
    } catch (NotFoundException e) {
        throw new com.google.api.server.spi.response.NotFoundException("Device ID: " + deviceId + " not found");
    }
}
Also used : ForbiddenException(com.google.api.server.spi.response.ForbiddenException) Device(com.google.samples.apps.iosched.server.gcm.db.models.Device) UnauthorizedException(com.google.api.server.spi.response.UnauthorizedException) BadRequestException(com.google.api.server.spi.response.BadRequestException) NotFoundException(com.googlecode.objectify.NotFoundException) ApiMethod(com.google.api.server.spi.config.ApiMethod)

Example 3 with Device

use of com.google.samples.apps.iosched.server.gcm.db.models.Device in project iosched by google.

the class FcmSendEndpoint method sendFeedPing.

/**
 * Ping all users' devices to update UI indicating that the feed has been updated.
 *
 * @param context Servlet context (injected by Endpoints)
 * @param user User making the request (injected by Endpoints)
 */
@ApiMethod(name = "sendFeedPing", path = "feed", clientIds = { Ids.SERVICE_ACCOUNT_CLIENT_ID })
public void sendFeedPing(ServletContext context, User user) throws UnauthorizedException {
    validateServiceAccount(user);
    MessageSender sender = new MessageSender(context);
    List<Device> devices = DeviceStore.getAllDevices();
    sender.multicastSend(devices, "feed_update", null);
}
Also used : MessageSender(com.google.samples.apps.iosched.server.gcm.device.MessageSender) Device(com.google.samples.apps.iosched.server.gcm.db.models.Device) ApiMethod(com.google.api.server.spi.config.ApiMethod)

Example 4 with Device

use of com.google.samples.apps.iosched.server.gcm.db.models.Device in project iosched by google.

the class DeviceStore method register.

/**
 * Registers a device.
 *
 * @param deviceId device's registration id.
 */
public static void register(String deviceId, String userId) {
    LOG.info("Registering device.\nGroup ID: " + userId + "\nGCM ID: " + deviceId);
    Device oldDevice = findDeviceByDeviceId(deviceId);
    if (oldDevice == null) {
        // Existing device not found (as expected)
        Device newDevice = new Device();
        newDevice.setDeviceId(deviceId);
        newDevice.setUserId(userId);
        ofy().save().entity(newDevice);
    } else {
        // Existing device found
        LOG.warning(deviceId + " is already registered");
        if (userId == null || !userId.equals(oldDevice.getUserId())) {
            LOG.info("User ID has changed from '" + oldDevice.getUserId() + "' to '" + userId + "'");
            oldDevice.setUserId(userId);
            ofy().save().entity(oldDevice);
        }
    }
}
Also used : Device(com.google.samples.apps.iosched.server.gcm.db.models.Device)

Example 5 with Device

use of com.google.samples.apps.iosched.server.gcm.db.models.Device in project iosched by google.

the class FcmSendEndpoint method sendSelfSync.

/**
 * Clients can initiate a sync on all of a user's devices. This will usually be called
 * when a client pushes a user data update to the server and wants other clients to
 * sync that change.
 *
 * @param context Servlet context (injected by Endpoints)
 * @param user User requesting the sync (injected by Endpoints)
 */
@ApiMethod(name = "sendSelfSync", path = "self")
public void sendSelfSync(ServletContext context, User user) throws UnauthorizedException {
    if (user == null) {
        throw new UnauthorizedException(INVALID_CREDENTIALS_MSG);
    }
    MessageSender sender = new MessageSender(context);
    String userId = user.getId();
    List<Device> devices = DeviceStore.findDevicesByUserId(userId);
    sender.multicastSend(devices, ACTION_SYNC_USER, null);
}
Also used : MessageSender(com.google.samples.apps.iosched.server.gcm.device.MessageSender) Device(com.google.samples.apps.iosched.server.gcm.db.models.Device) UnauthorizedException(com.google.api.server.spi.response.UnauthorizedException) ApiMethod(com.google.api.server.spi.config.ApiMethod)

Aggregations

Device (com.google.samples.apps.iosched.server.gcm.db.models.Device)11 ApiMethod (com.google.api.server.spi.config.ApiMethod)6 MessageSender (com.google.samples.apps.iosched.server.gcm.device.MessageSender)6 UnauthorizedException (com.google.api.server.spi.response.UnauthorizedException)3 BadRequestException (com.google.api.server.spi.response.BadRequestException)1 ForbiddenException (com.google.api.server.spi.response.ForbiddenException)1 NotFoundException (com.google.api.server.spi.response.NotFoundException)1 Queue (com.google.appengine.api.taskqueue.Queue)1 TaskOptions (com.google.appengine.api.taskqueue.TaskOptions)1 AuthInfo (com.google.samples.apps.iosched.server.gcm.AuthHelper.AuthInfo)1 NotFoundException (com.googlecode.objectify.NotFoundException)1 ArrayList (java.util.ArrayList)1