@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());
  }
Ejemplo n.º 2
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");
  }
Ejemplo n.º 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;
    }
  }
Ejemplo n.º 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);
     }
   }
 }
Ejemplo n.º 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());
 }
Ejemplo n.º 8
0
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/html");

    String username = req.getUserPrincipal().getName();

    String token = ChannelServiceFactory.getChannelService().createChannel(username);
    String tokenized =
        CharStreams.toString(
                new InputStreamReader(getServletContext().getResourceAsStream(PATH), ENCODING))
            .replace("TOKEN", token);

    DatastoreService store = DatastoreServiceFactory.getDatastoreService();
    Entity player = ensurePlayerExists(username, store);
    Entity map = ensureMapExists(player, store);

    OutputStream out = resp.getOutputStream();
    out.write(ENCODING.encode(tokenized).array());
    out.flush();
  }
Ejemplo n.º 9
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;
  }
Ejemplo n.º 10
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);
   }
 }
Ejemplo n.º 11
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();
  }
Ejemplo n.º 12
0
 private static ChannelService getChannelService() {
   // NB: This is really cheap, but if it became expensive, we could stuff
   // it in a thread local.
   return ChannelServiceFactory.getChannelService();
 }
Ejemplo n.º 13
0
public class ChannelServiceDelegate extends HttpServlet {
  private static final long serialVersionUID = 1L;
  private static final PlayerController playerController = ControllerFactory.getPlayerController();
  private static final UserController userController = ControllerFactory.getUserController();
  private static final ChannelService channelService = ChannelServiceFactory.getChannelService();

  public static String getChannelToken(String clientId) {
    // Key includes appid; KeyFactory.keyToString(myKey) will not work for backend.
    return channelService.createChannel(clientId);
  }

  public static void notifyPlayerJoin(
      Key roundKey, Key playerKey, String playerName, Color playerColor) {
    // TODO: Validate player; bypassing validation for now due to datastore latency.
    JSONObject message = new JSONObject();
    JSONObject extendedMessage = new JSONObject();
    try {
      message.put(Message.ACTION, Action.JOIN_GAME);
      message.put(Message.ACTOR, playerName);
      message.put(Message.ACTOR_KEY, KeyFactory.keyToString(playerKey));

      extendedMessage.put(Message.ACTION, Action.JOIN_GAME);
      extendedMessage.put(Message.ACTOR, playerName);
      extendedMessage.put(Message.ACTOR_COLOR, playerColor);
      extendedMessage.put(Message.ACTOR_KEY, KeyFactory.keyToString(playerKey));
    } catch (JSONException e) {
    }
    sendMessageToRound(roundKey, message);
    sendMessageToAdmins(extendedMessage);
    // Log Action
    playerController.logAction(Action.JOIN_GAME, roundKey, playerKey, null, playerColor, null);
  }

  public static void sendMessageToAdmins(JSONObject message) {
    Set<UserEntity> admins = userController.getAdmins();
    if (admins != null) {
      try {
        message.put("admin", "true");
      } catch (JSONException e) {
        e.printStackTrace();
      }
      for (UserEntity admin : admins) {
        sendMessageToUser(admin.getUsername(), message);
      }
    }
  }

  public static void sendMessageToMutualNeighbors(
      Key playerOneKey, Key playerTwoKey, JSONObject message) {
    Set<PlayerEntity> neighbors =
        playerController.getMutualNeighborsInfo(playerOneKey, playerTwoKey);
    if (neighbors != null) {
      for (PlayerEntity neighbor : neighbors) {
        // Don't message the bots.
        if (neighbor.getUserKey() != null) {
          sendMessageToPlayer(neighbor.getName(), message);
        }
      }
    }
  }

  public static void sendMessageToNeighbors(Key playerKey, JSONObject message) {
    Set<PlayerEntity> neighbors = playerController.getNeighborsInfo(playerKey);
    if (neighbors != null) {
      for (PlayerEntity neighbor : neighbors) {
        // Don't message the bots.
        if (neighbor.getUserKey() != null) {
          sendMessageToPlayer(neighbor.getName(), message);
        }
      }
    }
  }

  public static void sendMessageToPlayer(String clientId, JSONObject message) {
    if (clientId != null && !clientId.isEmpty()) {
      channelService.sendMessage(new ChannelMessage(clientId, message.toString()));
    }
  }

  public static void sendMessageToRound(Key roundKey, JSONObject message) {
    Set<PlayerEntity> players = playerController.getPlayersByRoundKey(roundKey);
    if (players != null) {
      for (PlayerEntity player : players) {
        // Don't message the bots.
        if (player.getUserKey() != null) {
          sendMessageToPlayer(player.getName(), message);
        }
      }
    }
  }

  public static void sendMessageToUser(String clientId, JSONObject message) {
    if (clientId != null && !clientId.isEmpty()) {
      channelService.sendMessage(new ChannelMessage(clientId, message.toString()));
    }
  }
}
Ejemplo n.º 14
0
  private void sendMessage(String querytitle, Message message) {

    ChannelService channelService = ChannelServiceFactory.getChannelService();
    channelService.sendMessage(new ChannelMessage(querytitle, new Gson().toJson(message)));
  }
Ejemplo n.º 15
0
 public AppEngineGuiceModule withChannelService() {
   this.channelService = ChannelServiceFactory.getChannelService();
   return this;
 }