Esempio n. 1
0
 @Override
 public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
   Channel channel = ctx.getChannel();
   if (!sessions.removeSession(channel.getId())) {
     Log.error("删除Session失败! sockId: " + channel.getId());
   }
 }
Esempio n. 2
0
  private Message handleDisconnectMessage(
      final ChannelFactory<?> channelFactory, CommandMessage message) {
    Channel client = getChannel(channelFactory, (String) message.getClientId());
    if (client == null) return handleUnknownClientMessage(message);

    removeChannel(client.getId(), false);

    AcknowledgeMessage reply = new AcknowledgeMessage(message);
    reply.setDestination(message.getDestination());
    reply.setClientId(client.getId());
    return reply;
  }
  private void ban(MessageContext context, String args) {
    if (args.isEmpty()) {
      return;
    }
    String[] split = args.split(" ");
    List<String> banned = new ArrayList<>();
    List<String> failed = new ArrayList<>();
    Channel channel = context.getChannel();
    for (String userStr : split) {
      User user = findUser(context, userStr);
      String userId = user.getId();
      if (user == NO_USER) {
        userId = userStr;
      }

      if (banChecked(channel, context.getAuthor(), user, context.getServer())) {
        banned.add(userId + " " + user.getUsername());
      } else {
        failed.add(userId + " " + user.getUsername());
      }
    }

    if (channel.getId() != null) {
      StringJoiner joiner = new StringJoiner("\n");
      for (String s : banned) {
        String[] pair = s.split(" ", 2);
        joiner.add(loc.localize("commands.mod.ban.response", pair[1], pair[0]));
      }
      apiClient.sendMessage(joiner.toString(), channel);
    }
  }
Esempio n. 4
0
  public void removeChannel(Channel channel) {
    SQLiteDatabase database = getWritableDatabase();

    clearChannel(channel, database);
    database.delete("Channel", "id = ?", new String[] {Long.toString(channel.getId())});

    database.close();
  }
 public ChannelOrderLog(MerchantOrder order, Channel channel, String content) {
   this.orderId = order.getId();
   this.content = content;
   this.creatorId = channel.getId();
   this.createdDate = new Date();
   this.creatorName = channel.getName();
   this.creatorType = MerchantOrder.UserType.CHANNEL;
 }
Esempio n. 6
0
  private Message handlePublishMessage(
      final ChannelFactory<?> channelFactory, final AsyncMessage message, final Channel channel) {

    GraniteContext context = GraniteContext.getCurrentInstance();

    // Get and check destination.
    Destination destination =
        context
            .getServicesConfig()
            .findDestinationById(message.getClass().getName(), message.getDestination());

    if (destination == null) return getInvalidDestinationError(message);

    if (message.getMessageId() == null) message.setMessageId(UUIDUtil.randomUUID());
    message.setTimestamp(System.currentTimeMillis());
    if (channel != null) message.setClientId(channel.getId());

    GravityInvocationContext invocationContext =
        new GravityInvocationContext(message, destination) {
          @Override
          public Object invoke() throws Exception {
            // Publish...
            Channel fromChannel = channel;
            if (fromChannel == null)
              fromChannel = getChannel(channelFactory, (String) message.getClientId());
            if (fromChannel == null) return handleUnknownClientMessage(message);

            ServiceAdapter adapter = adapterFactory.getServiceAdapter(message);

            AsyncMessage reply = (AsyncMessage) adapter.invoke(fromChannel, message);

            reply.setDestination(message.getDestination());
            reply.setClientId(fromChannel.getId());

            return reply;
          }
        };

    // Check security 1 (destination).
    if (destination.getSecurizer() instanceof GravityDestinationSecurizer) {
      try {
        ((GravityDestinationSecurizer) destination.getSecurizer()).canPublish(invocationContext);
      } catch (Exception e) {
        return new ErrorMessage(message, e, true);
      }
    }

    // Check security 2 (security service).
    GraniteConfig config = context.getGraniteConfig();
    try {
      if (config.hasSecurityService() && config.getSecurityService().acceptsContext())
        return (Message) config.getSecurityService().authorize(invocationContext);

      return (Message) invocationContext.invoke();
    } catch (Exception e) {
      return new ErrorMessage(message, e, true);
    }
  }
Esempio n. 7
0
  public void handleMessage(IrcMessage message) {
    try {
      SQLiteDatabase database = getWritableDatabase();

      String channelName = message.getLogicalChannel();
      List<Channel> channels = getChannels(database);

      int biggestOrder = 0;
      Channel found = null;
      for (Channel ch : channels) {
        biggestOrder = Math.max(biggestOrder, ch.getOrder() + 1);
        if (ch.getName().equals(channelName)) {
          found = ch;
          break;
        }
      }

      long channelId;
      if (found == null) {
        ContentValues values = new ContentValues();
        values.put("name", channelName);
        values.put("orderIndex", biggestOrder);
        channelId = database.insert("Channel", null, values);
      } else {
        channelId = found.getId();
      }

      ContentValues messageValues = new ContentValues();
      messageValues.put("channelId", channelId);
      messageValues.put("message", message.getMessage());
      messageValues.put("nick", message.getNick());
      messageValues.put("serverTimestamp", message.getServerTimestamp().getTime());
      messageValues.put("externalId", message.getExternalId());

      Cursor cur =
          database.query(
              "IrcMessage",
              new String[] {"externalId", "message"},
              "externalId = ?",
              new String[] {message.getExternalId()},
              null,
              null,
              null,
              "1");
      if (cur.isAfterLast()) {
        messageValues.put("shown", 0);
        database.insert("IrcMessage", null, messageValues);
      } else {
        // already in database, update if necessary
        database.update(
            "IrcMessage", messageValues, "externalId = ?", new String[] {message.getExternalId()});
      }
      cur.close();
      database.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Esempio n. 8
0
  public void updateChannel(Channel channel) {
    SQLiteDatabase database = getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put("name", channel.getName());
    values.put("orderIndex", channel.getOrder());

    database.update("Channel", values, "id = ?", new String[] {Long.toString(channel.getId())});
    database.close();
  }
Esempio n. 9
0
 public void setChannelAsShown(Channel channel) {
   SQLiteDatabase database = getWritableDatabase();
   ContentValues values = new ContentValues();
   values.put("shown", true);
   database.update(
       "IrcMessage",
       values,
       "shown = ? AND channelId = ?",
       new String[] {"0", "" + channel.getId()});
   database.close();
 }
Esempio n. 10
0
  public void stop(boolean now) throws Exception {
    log.info("Stopping Gravity (now=%s)...", now);
    synchronized (this) {
      if (adapterFactory != null) {
        try {
          adapterFactory.stopAll();
        } catch (Exception e) {
          log.error(e, "Error while stopping adapter factory");
        }
        adapterFactory = null;
      }

      if (serverChannel != null) {
        try {
          removeChannel(serverChannel.getId(), false);
        } catch (Exception e) {
          log.error(e, "Error while removing server channel: %s", serverChannel);
        }
        serverChannel = null;
      }

      if (channelsTimer != null) {
        try {
          channelsTimer.cancel();
        } catch (Exception e) {
          log.error(e, "Error while cancelling channels timer");
        }
        channelsTimer = null;
      }

      if (gravityPool != null) {
        try {
          if (now) gravityPool.shutdownNow();
          else gravityPool.shutdown();
        } catch (Exception e) {
          log.error(e, "Error while stopping thread pool");
        }
        gravityPool = null;
      }

      if (udpReceiverFactory != null) {
        try {
          udpReceiverFactory.stop();
        } catch (Exception e) {
          log.error(e, "Error while stopping udp receiver factory");
        }
        udpReceiverFactory = null;
      }

      started = false;
    }
    log.info("Gravity sucessfully stopped.");
  }
Esempio n. 11
0
  private Message handleUnsubscribeMessage(
      final ChannelFactory<?> channelFactory, CommandMessage message) {
    Channel channel = getChannel(channelFactory, (String) message.getClientId());
    if (channel == null) return handleUnknownClientMessage(message);

    AsyncMessage reply = null;

    ServiceAdapter adapter = adapterFactory.getServiceAdapter(message);

    reply = (AcknowledgeMessage) adapter.manage(channel, message);

    postManage(channel);

    if (!(reply instanceof ErrorMessage)) {
      // Remove subscription message in distributed data (clustering).
      try {
        DistributedData gdd = graniteConfig.getDistributedDataFactory().getInstance();
        if (gdd != null) {
          String subscriptionId =
              (String) message.getHeader(AsyncMessage.DESTINATION_CLIENT_ID_HEADER);
          log.debug(
              "Removing subscription message from channel info: %s - %s",
              channel.getId(), subscriptionId);
          gdd.removeSubcription(channel.getId(), subscriptionId);
        }
      } catch (Exception e) {
        log.error(
            e,
            "Could not remove subscription from distributed data: %s - %s",
            channel.getId(),
            message.getHeader(AsyncMessage.DESTINATION_CLIENT_ID_HEADER));
      }
    }

    reply.setDestination(message.getDestination());
    reply.setClientId(channel.getId());
    reply.getHeaders().putAll(message.getHeaders());

    return reply;
  }
Esempio n. 12
0
  private Message handlePingMessage(ChannelFactory<?> channelFactory, CommandMessage message) {

    Channel channel = createChannel(channelFactory, (String) message.getClientId());

    AsyncMessage reply = new AcknowledgeMessage(message);
    reply.setClientId(channel.getId());
    Map<String, Object> advice = new HashMap<String, Object>();
    advice.put(RECONNECT_INTERVAL_MS_KEY, Long.valueOf(gravityConfig.getReconnectIntervalMillis()));
    advice.put(RECONNECT_MAX_ATTEMPTS_KEY, Long.valueOf(gravityConfig.getReconnectMaxAttempts()));
    advice.put(ENCODE_MESSAGE_BODY_KEY, Boolean.valueOf(gravityConfig.isEncodeMessageBody()));
    reply.setBody(advice);
    reply.setDestination(message.getDestination());

    log.debug("handshake.handle: reply=%s", reply);

    return reply;
  }
Esempio n. 13
0
  private List<IrcMessage> getMessagesForChannel(SQLiteDatabase database, Channel channel) {
    Cursor cursor =
        database.query(
            "IrcMessage",
            new String[] {
              "message", "nick", "serverTimestamp", "shown", "externalId", "clearedFromFeed", "id"
            },
            "channelId = ?",
            new String[] {Long.toString(channel.getId())},
            null,
            null,
            "serverTimestamp DESC",
            "100");
    cursor.moveToFirst();
    List<IrcMessage> list = new ArrayList<IrcMessage>();

    int colMessage = cursor.getColumnIndex("message");
    int colNick = cursor.getColumnIndex("nick");
    int colServerTimestamp = cursor.getColumnIndex("serverTimestamp");
    int colExternalId = cursor.getColumnIndex("externalId");
    int colShown = cursor.getColumnIndex("shown");
    int colClearedFromFeed = cursor.getColumnIndex("clearedFromFeed");
    int colId = cursor.getColumnIndex("id");

    while (!cursor.isAfterLast()) {
      IrcMessage message = new IrcMessage();
      message.setMessage(cursor.getString(colMessage));
      message.setNick(cursor.getString(colNick));
      message.setServerTimestamp(cursor.getLong(colServerTimestamp));
      message.setExternalId(cursor.getString(colExternalId));
      message.setChannel(channel.getName());
      message.setShown(cursor.getInt(colShown) == 0 ? false : true);
      message.setClearedFromFeed(cursor.getInt(colClearedFromFeed) == 0 ? false : true);
      message.setId(cursor.getLong(colId));

      list.add(message);
      cursor.moveToNext();
    }

    cursor.close();
    Collections.reverse(list);
    return list;
  }
 private void setDnTrackChannel(MessageContext context, String args) {
   if (context.getServer() == null || context.getServer() == NO_SERVER) {
     return;
   }
   String serverId = context.getServer().getId();
   TempServerConfig config = serverStorage.get(serverId);
   if (config == null) {
     config = new TempServerConfig(serverId);
     serverStorage.put(serverId, config);
   }
   Channel channel = context.getChannel();
   if (args.equalsIgnoreCase("off")) {
     config.setDnTrackChannel(null);
     apiClient.sendMessage(loc.localize("commands.mod.dntrack.response.none"), channel);
   } else {
     config.setDnTrackChannel(channel.getId());
     apiClient.sendMessage(loc.localize("commands.mod.dntrack.response.set"), channel);
   }
   saveServerConfig(config);
 }
 private void joinLeave(MessageContext context, String args) {
   if (args.isEmpty()) {
     return;
   }
   args = args.toLowerCase();
   String[] split = args.split(" ");
   String cid = split[0];
   JoinLeave target = JoinLeave.BOTH;
   if (split.length != 1) {
     String jlStr = split[1].toLowerCase();
     for (JoinLeave joinLeave : JoinLeave.values()) {
       if (joinLeave.name().toLowerCase().startsWith(jlStr)) {
         target = joinLeave;
         break;
       }
     }
   }
   if ("default".equals(cid)) {
     cid = context.getServer().getId();
   } else if ("this".equals(cid)) {
     cid = context.getChannel().getId();
   }
   Channel channel = apiClient.getChannelById(cid);
   if (channel != NO_CHANNEL) {
     if (target == JoinLeave.JOIN) {
       bot.getEventListener().joinMessageRedirect.put(context.getServer().getId(), cid);
     }
     if (target == JoinLeave.LEAVE) {
       bot.getEventListener().leaveMessageRedirect.put(context.getServer().getId(), cid);
     }
     if (target == JoinLeave.BOTH) {
       bot.getEventListener().joinMessageRedirect.put(context.getServer().getId(), cid);
       bot.getEventListener().leaveMessageRedirect.put(context.getServer().getId(), cid);
     }
     apiClient.sendMessage(
         loc.localize("commands.mod.jl.response", channel.getName(), channel.getId()),
         context.getChannel());
   } else {
     apiClient.sendMessage(loc.localize("commands.mod.jl.response.invalid"), context.getChannel());
   }
 }
Esempio n. 16
0
 public void clearChannel(Channel channel, SQLiteDatabase database) {
   database.delete("IrcMessage", "channelId = ?", new String[] {Long.toString(channel.getId())});
 }
Esempio n. 17
0
 @Override
 public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
   Channel channel = ctx.getChannel();
   sessions.createSession(channel.getId(), frontendId, channel);
 }