Пример #1
0
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();

    String message_type = req.getParameter("type");
    String user_name = user.getNickname();

    String userId = user.getUserId();

    if (message_type.compareTo("message") == 0) {
      String message = req.getParameter("text");
      String chat_message = chatMessage(user_name, message);
      sendChannelMessageToAll(user_name, chat_message);
      addMessageToCache(chat_message);
    } else if (message_type.compareTo("get_token") == 0) {
      // generate and give token to user
      ChannelService channelService = ChannelServiceFactory.getChannelService();
      String token = channelService.createChannel(userId);
      addToCacheList(_tokenKey, userId);

      resp.setCharacterEncoding("UTF-8");
      resp.setContentType("text/html");
      PrintWriter out = resp.getWriter();
      out.print(tokenMessage(user_name, token));
    } else if (message_type.compareTo("leave") == 0) {
      removeFromCacheList(_tokenKey, userId);
    }
  }
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    String[] parts = req.getRequestURI().split("/");
    String secret = parts[parts.length - 1];
    String sessionId = parts[parts.length - 2];

    PoorSession session = PoorSessionManager.findSessionById(sessionId);
    if (session == null) {
      resp.sendError(404, "Wrong credentials");
      return;
    }

    Query query = new Query("User").addFilter("external-secret", FilterOperator.EQUAL, secret);
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    PreparedQuery preparedQuery = datastore.prepare(query);
    Entity entity = preparedQuery.asSingleEntity();

    if (entity == null) {
      resp.sendError(404, "Wrong credentials");
      return;
    }

    String userId = entity.getProperty("email").toString();
    log.info("Logging in user " + userId + "with session " + sessionId + " and secret " + secret);

    PoorSessionManager.loginSession(session, userId);

    // send success signal to the ext login page
    ChannelService channelService = ChannelServiceFactory.getChannelService();
    channelService.sendMessage(new ChannelMessage(sessionId, "success"));

    resp.getWriter().write("Your browser is now logged in");
  }
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    HttpSession session = req.getSession(true);
    String sessionId = session.getId();

    ChannelService channelService = ChannelServiceFactory.getChannelService();
    String token = channelService.createChannel(sessionId);

    StringBuilder sessionMap = new StringBuilder();
    Enumeration<String> attributeNames = session.getAttributeNames();
    while (attributeNames.hasMoreElements()) {
      String name = attributeNames.nextElement();
      sessionMap
          .append(name)
          .append(" => ")
          .append(session.getAttribute(name).toString())
          .append("<br/>");
    }

    resp.setContentType("text/html");
    new SkimpyTemplate(getServletContext().getResourceAsStream("/injectable.html"))
        .add("sessionId", sessionId)
        .add("token", token)
        .add("session-vars", sessionMap.toString())
        .write(resp.getWriter());
  }
Пример #4
0
  private void sendChannelMessageToAll(String author, String message) {
    ChannelService channelService = ChannelServiceFactory.getChannelService();
    List<String> keys = getListFromCacahe(_tokenKey);

    for (String k : keys) {
      channelService.sendMessage(new ChannelMessage(k, message));
    }
  }
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    String[] parts = req.getRequestURI().split("/");
    if (parts.length != 4) {
      resp.sendError(404);
      return;
    }

    ChannelService channelService = ChannelServiceFactory.getChannelService();
    ChannelPresence presence = channelService.parsePresence(req);
    GameChannelId channelId = GameChannelId.parse(presence.clientId());

    // get match
    Match match =
        WordgameStore.getMatch(
            channelId.getGameId(), channelId.getMatchId(), channelId.getPlayerId());
    Player opponent = match.getOpponent();

    if (parts[3].equals("connected")) {
      // set the state of this player as connected
      match.getPlayer().setConnected();
      WordgameStore.storePlayer(channelId.getGameId(), channelId.getMatchId(), match.getPlayer());

      if (opponent != null) {

        if (opponent.getStatus() != Status.NOT_CONNECTED) {
          // notify the opponent about this player
          String opponentChannel =
              GameChannelId.getChannelId(channelId.getGameId(), channelId.getMatchId(), opponent);

          String msg = WordgameProtocol.notifyOpponentConnected(match.getPlayer());
          channelService.sendMessage(new ChannelMessage(opponentChannel, msg));
        }

        // notify this player about the opponent
        String msg = WordgameProtocol.notifyOpponentConnected(opponent);
        channelService.sendMessage(new ChannelMessage(presence.clientId(), msg));
      }
      return;
    }

    if (parts[3].equals("disconnected-DISABLED")) {

      // remove player from game
      WordgameStore.removePlayer(channelId.getGameId(), channelId.getMatchId(), match.getPlayer());

      // notify opponent
      if (opponent != null && opponent.getStatus() != Status.NOT_CONNECTED) {
        String opponentChannel =
            GameChannelId.getChannelId(channelId.getGameId(), channelId.getMatchId(), opponent);
        String partedMsg = WordgameProtocol.notifyParted();
        channelService.sendMessage(new ChannelMessage(opponentChannel, partedMsg));
      }
      return;
    }
  }
Пример #6
0
 /**
  * Sends a message to all specified users
  *
  * @param userKeys : list of users to send the message to. msg : message to be sent.
  */
 private static void sendMessageByKey(List<String> userKeys, Message msg) {
   String encodedMessage = encodeMessage(msg);
   for (String user : userKeys) {
     String key = user;
     try {
       System.out.println("Sending to user: "******"Failed to push the message " + msg + " to client " + key, e);
     }
   }
 }
Пример #7
0
 @Override
 public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
   ChannelService channelService = ChannelServiceFactory.getChannelService();
   ChannelPresence presence = channelService.parsePresence(request);
   Objectify ofy = ObjectifyService.begin();
   User user;
   try {
     // System.out.println(presence.clientId() + " connected");
     user =
         UserHelper.getUserWithEmail(ChannelApiHelper.getUserForAppkey(presence.clientId()), ofy);
   } catch (Exception e) {
     return;
   }
   user.isConnected = true;
   ofy.put(user);
   sendConnectionToContacts(ofy.get(user.getContacts()).values().iterator(), user.getEmail());
 }
Пример #8
0
  public LoginInfo login(String requestUri) {
    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();
    LoginInfo loginInfo = new LoginInfo();
    ChannelService channelService = ChannelServiceFactory.getChannelService();

    if (user != null) {
      loginInfo.setLoggedIn(true);
      loginInfo.setEmailAddress(user.getEmail());
      loginInfo.setNickname(user.getNickname());
      loginInfo.setLogoutUrl(userService.createLogoutURL(requestUri));
      String token = channelService.createChannel(loginInfo.getEmailAddress());
      loginInfo.setToken(token);
    } else {
      loginInfo.setLoggedIn(false);
      loginInfo.setLoginUrl(userService.createLoginURL(requestUri));
    }

    return loginInfo;
  }
Пример #9
0
 public static void sendMessage(NotificationMessage message) {
   try {
     List<BrowserClient> clients = ofy().load().type(BrowserClient.class).list();
     ChannelService channelService = ChannelServiceFactory.getChannelService();
     ObjectMapper mapper = new ObjectMapper();
     String payload = mapper.writeValueAsString(message);
     List<BrowserClient> oldClients = new ArrayList<>();
     long maxClientAge = new Date().getTime() - 1000 * 60 * 60 * 2;
     for (BrowserClient client : clients) {
       if (client.getCreatedDate().getTime() > maxClientAge) {
         ChannelMessage channelMessage = new ChannelMessage(client.getToken(), payload);
         channelService.sendMessage(channelMessage);
       } else {
         oldClients.add(client);
       }
     }
     if (oldClients.size() > 0) {
       ofy().delete().entities(oldClients).now();
     }
   } catch (IOException e) {
     log.log(Level.SEVERE, "Could not convert message to json", e);
   }
 }
Пример #10
0
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    ChannelService channelService = ChannelServiceFactory.getChannelService();
    ChannelPresence presence = channelService.parsePresence(request);

    String[] parts = presence.clientId().split(">");
    String email = parts[0];

    Player player = ofy().load().type(Player.class).id(email).get();

    if (player == null) {
      throw new IllegalArgumentException("Player not found");
    }

    if (presence.isConnected()) {
      player.getChannels().add(presence.clientId());
      System.out.println(presence.clientId() + " connected");
    } else {
      player.getChannels().remove(presence.clientId());
      System.out.println(presence.clientId() + " disconncted");
    }

    ofy().save().entity(player).now();
  }
Пример #11
0
 public static void sendMessageToPlayer(String clientId, JSONObject message) {
   if (clientId != null && !clientId.isEmpty()) {
     channelService.sendMessage(new ChannelMessage(clientId, message.toString()));
   }
 }
Пример #12
0
 public static String getChannelToken(String clientId) {
   // Key includes appid; KeyFactory.keyToString(myKey) will not work for backend.
   return channelService.createChannel(clientId);
 }
Пример #13
0
  private void sendMessage(String querytitle, Message message) {

    ChannelService channelService = ChannelServiceFactory.getChannelService();
    channelService.sendMessage(new ChannelMessage(querytitle, new Gson().toJson(message)));
  }