You are here

function nodejs_message_handler in Node.js integration 7

Same name and namespace in other branches
  1. 6 nodejs.module \nodejs_message_handler()

Menu callback: handles all messages from Node.js server.

1 string reference to 'nodejs_message_handler'
nodejs_menu in ./nodejs.module
Implements hook_menu().

File

./nodejs.module, line 536

Code

function nodejs_message_handler() {
  if (!isset($_POST['serviceKey']) || !nodejs_is_valid_service_key($_POST['serviceKey'])) {
    drupal_json_output(array(
      'error' => 'Invalid service key.',
    ));
    drupal_exit();
  }
  if (!isset($_POST['messageJson'])) {
    drupal_json_output(array(
      'error' => 'No message.',
    ));
    drupal_exit();
  }
  $message = drupal_json_decode($_POST['messageJson']);
  $response = array();
  switch ($message['messageType']) {
    case 'authenticate':
      $response = nodejs_auth_check($message);
      break;
    case 'userOffline':
      if (empty($message['uid'])) {
        $response['error'] = 'Missing uid for userOffline message.';
      }
      else {
        if (!preg_match('/^\\d+$/', $message['uid'])) {
          $response['error'] = 'Invalid (!/^\\d+$/) uid for userOffline message.';
        }
        else {
          nodejs_user_set_offline($message['uid']);
          $response['message'] = "User {$message['uid']} set offline.";
        }
      }
      break;
    default:
      $handlers = array();
      foreach (module_implements('nodejs_message_callback') as $module) {
        $function = $module . '_nodejs_message_callback';
        if (is_array($function($message['messageType']))) {
          $handlers += $function($message['messageType']);
        }
      }
      foreach ($handlers as $callback) {
        $callback($message, $response);
      }
  }
  drupal_alter('nodejs_message_response', $response, $message);
  drupal_json_output($response ? $response : array(
    'error' => 'Not implemented',
  ));
  drupal_exit();
}