Ejemplo n.º 1
0
/**
 * json_builder_add_string_value:
 * @builder: a #JsonBuilder
 * @value: the value of the member or element
 *
 * If called after json_builder_set_member_name(), sets @value as member of the
 * most recent opened object, otherwise @value is added as element of the most
 * recent opened array.
 *
 * See also: json_builder_add_value()
 *
 * Return value: (transfer none): the #JsonBuilder, or %NULL if the call was inconsistent
 */
JsonBuilder *
json_builder_add_string_value (JsonBuilder *builder,
                               const gchar *value)
{
  JsonBuilderState *state;

  g_return_val_if_fail (JSON_IS_BUILDER (builder), NULL);
  g_return_val_if_fail (!g_queue_is_empty (builder->priv->stack), NULL);
  g_return_val_if_fail (json_builder_is_valid_add_mode (builder), NULL);

  state = g_queue_peek_head (builder->priv->stack);

  switch (state->mode)
    {
    case JSON_BUILDER_MODE_MEMBER:
      json_object_set_string_member (state->data.object, state->member_name, value);
      g_free (state->member_name);
      state->member_name = NULL;
      state->mode = JSON_BUILDER_MODE_OBJECT;
      break;

    case JSON_BUILDER_MODE_ARRAY:
      json_array_add_string_element (state->data.array, value);
      break;

    default:
      g_assert_not_reached ();
    }

  return builder;
}
Ejemplo n.º 2
0
void
snarf_alert_add_tags(snarf_alert_t *alert, char *tags)
{
    gchar **taglist  = NULL;
    char  **p        = NULL;
    int     tagcount = 0;
    char   *tag      = NULL;

    JsonObject * rootobj = json_node_get_object (alert->msg);
    JsonObject * envelopeobj = json_object_get_object_member(rootobj,"envelope");

    JsonArray *analysis_tags=json_array_new();

    taglist = g_strsplit_set(tags, ", \t\n\v\f\r", 0);
    for (p = taglist, tagcount = 0; p && *p; p++)
    {
	tag=*p;
	if (!strlen(tag))
	{
	    continue;
	}
 	json_array_add_string_element(analysis_tags,tag);
    }

    json_object_set_array_member(envelopeobj,"analysis_tags",analysis_tags);

}
Ejemplo n.º 3
0
JsonNode*
cometd_new_handshake_message(const cometd* h)
{
  gint64 seed = ++(h->conn->msg_id_seed);

  JsonNode*   root = json_node_new(JSON_NODE_OBJECT);
  JsonObject* obj  = json_object_new();

  json_object_set_int_member   (obj, COMETD_MSG_ID_FIELD,          seed);
  json_object_set_string_member(obj, COMETD_MSG_CHANNEL_FIELD,     COMETD_CHANNEL_META_HANDSHAKE);
  json_object_set_string_member(obj, COMETD_MSG_VERSION_FIELD,     COMETD_VERSION);
  json_object_set_string_member(obj, COMETD_MSG_MIN_VERSION_FIELD, COMETD_MIN_VERSION);

  // construct advice - TODO: these values should not be hardcoded
  JsonObject* advice = json_object_new();
  json_object_set_int_member(advice, "timeout",  60000);
  json_object_set_int_member(advice, "interval", 0);
  json_object_set_object_member(obj, COMETD_MSG_ADVICE_FIELD, advice);

  // construct supported transports
  JsonArray* json_transports = json_array_new();

  GList* entry = h->config->transports;
  while (entry){
    cometd_transport* t = entry->data;
    json_array_add_string_element(json_transports, t->name);
    entry = g_list_next(entry);
  }
  json_object_set_array_member(obj, "supportedConnectionTypes", json_transports);

  // call extensions with message - TODO: implement extensions first
  json_node_take_object(root, obj);

  return root;
}
Ejemplo n.º 4
0
static char *
file_list_to_json (GList *files)
{
    JsonNode *root;
    JsonArray *array;
    GList *ptr;
    char *file;
    JsonGenerator *gen;
    char *json_data;
    gsize len;

    root = json_node_new (JSON_NODE_ARRAY);
    array = json_array_new ();

    for (ptr = files; ptr; ptr = ptr->next) {
        file = ptr->data;
        json_array_add_string_element (array, file);
    }
    json_node_set_array (root, array);

    gen = json_generator_new ();
    json_generator_set_root (gen, root);
    json_data = json_generator_to_data (gen, &len);
    json_node_free (root);
    g_object_unref (gen);

    return json_data;
}
Ejemplo n.º 5
0
static void
on_web_socket_open (WebSocketConnection *connection,
                    CockpitWebService *self)
{
  CockpitSocket *socket;
  JsonArray *capabilities;
  GBytes *command;
  JsonObject *object;
  JsonObject *info;

  g_info ("New connection to session from %s", cockpit_creds_get_rhost (self->creds));

  socket = cockpit_socket_lookup_by_connection (&self->sockets, connection);
  g_return_if_fail (socket != NULL);

  object = json_object_new ();
  json_object_set_string_member (object, "command", "init");
  json_object_set_int_member (object, "version", 1);
  json_object_set_string_member (object, "channel-seed", socket->id);
  json_object_set_string_member (object, "host", "localhost");
  json_object_set_string_member (object, "csrf-token", cockpit_creds_get_csrf_token (self->creds));

  capabilities = json_array_new ();
  json_array_add_string_element (capabilities, "multi");
  json_array_add_string_element (capabilities, "credentials");
  json_array_add_string_element (capabilities, "binary");
  json_object_set_array_member (object, "capabilities", capabilities);

  info = json_object_new ();
  json_object_set_string_member (info, "version", PACKAGE_VERSION);
  json_object_set_string_member (info, "build", COCKPIT_BUILD_INFO);
  json_object_set_object_member (object, "system", info);

  command = cockpit_json_write_bytes (object);
  json_object_unref (object);

  web_socket_connection_send (connection, WEB_SOCKET_DATA_TEXT, self->control_prefix, command);
  g_bytes_unref (command);

  /* Do we have an authorize password? if so tell the frontend */
  if (cockpit_creds_get_password (self->creds))
    send_socket_hints (self, "credential", "password");

  g_signal_connect (connection, "message",
                    G_CALLBACK (on_web_socket_message), self);
}
static void
trg_tracker_announce_edited(GtkCellRendererText * renderer,
                            gchar * path,
                            gchar * new_text, gpointer user_data)
{
    TrgTrackersTreeViewPrivate *priv =
        TRG_TRACKERS_TREE_VIEW_GET_PRIVATE(user_data);
    GtkTreeModel *model =
        gtk_tree_view_get_model(GTK_TREE_VIEW(user_data));
    gint64 torrentId =
        trg_trackers_model_get_torrent_id(TRG_TRACKERS_MODEL(model));
    JsonArray *torrentIds = json_array_new();
    JsonArray *trackerModifiers = json_array_new();

    gint64 trackerId;
    JsonNode *req;
    JsonObject *args;
    GtkTreeIter iter;
    gchar *icon;

    gtk_tree_model_get_iter_from_string(model, &iter, path);
    gtk_list_store_set(GTK_LIST_STORE(model), &iter, TRACKERCOL_ANNOUNCE,
                       new_text, -1);
    gtk_tree_model_get(model, &iter, TRACKERCOL_ID, &trackerId,
                       TRACKERCOL_ICON, &icon, -1);

    json_array_add_int_element(torrentIds, torrentId);

    req = torrent_set(torrentIds);
    args = node_get_arguments(req);

    if (!g_strcmp0(icon, GTK_STOCK_ADD)) {
        json_array_add_string_element(trackerModifiers, new_text);
        json_object_set_array_member(args, "trackerAdd", trackerModifiers);
    } else {
        json_array_add_int_element(trackerModifiers, trackerId);
        json_array_add_string_element(trackerModifiers, new_text);
        json_object_set_array_member(args, "trackerReplace",
                                     trackerModifiers);
    }

    g_free(icon);

    dispatch_async(priv->client, req, on_trackers_update, user_data);
}
Ejemplo n.º 7
0
static gboolean
cockpit_channel_ensure_capable (CockpitChannel *channel,
                                JsonObject *options)
{
  gchar **capabilities = NULL;
  JsonObject *close_options = NULL; // owned by channel
  gboolean missing = FALSE;
  gboolean ret = FALSE;
  gint len;
  gint i;

  if (!cockpit_json_get_strv (options, "capabilities", NULL, &capabilities))
    {
      g_message ("got invalid capabilities field in open message");
      cockpit_channel_close (channel, "protocol-error");
      goto out;
    }

  if (!capabilities)
    {
      ret = TRUE;
      goto out;
    }

  len = g_strv_length (capabilities);
  for (i = 0; i < len; i++)
    {
      if (channel->priv->capabilities == NULL ||
          !strv_contains(channel->priv->capabilities, capabilities[i]))
        {
          g_message ("unsupported capability required: %s", capabilities[i]);
          missing = TRUE;
        }
    }

  if (missing)
    {
      JsonArray *arr = json_array_new (); // owned by closed options

      if (channel->priv->capabilities != NULL)
        {
          len = g_strv_length (channel->priv->capabilities);
          for (i = 0; i < len; i++)
            json_array_add_string_element (arr, channel->priv->capabilities[i]);
        }

      close_options = cockpit_channel_close_options (channel);
      json_object_set_array_member (close_options, "capabilities", arr);
      cockpit_channel_close (channel, "not-supported");
    }

  ret = !missing;

out:
  g_free (capabilities);
  return ret;
}
Ejemplo n.º 8
0
static JsonArray *
strv_to_json_array (gchar **strv)
{
  gint i;
  JsonArray *array = json_array_new ();
  g_assert (strv != NULL);
  for (i = 0; strv[i] != NULL; i++)
    json_array_add_string_element (array, strv[i]);
  return array;
}
Ejemplo n.º 9
0
Archivo: ui.c Proyecto: automata/imgflo
static void
ui_connection_handle_message(UiConnection *self,
                const gchar *protocol, const gchar *command, JsonObject *payload,
                SoupWebsocketConnection *ws)
{
    if (g_strcmp0(protocol, "graph") == 0) {
        handle_graph_message(self, command, payload, ws);
    } else if (g_strcmp0(protocol, "network") == 0) {
        handle_network_message(self, command, payload, ws);
    } else if (g_strcmp0(protocol, "component") == 0 && g_strcmp0(command, "list") == 0) {

        // Our special Processor component
        JsonObject *processor = library_processor_component();
        send_response(ws, "component", "component", processor);

        // Components for all available GEGL operations
        guint no_ops = 0;
        gchar **operation_names = gegl_list_operations(&no_ops);
        if (no_ops == 0) {
            g_warning("No GEGL operations found");
        }
        for (int i=0; i<no_ops; i++) {
            const gchar *op = operation_names[i];
            if (g_strcmp0(op, "gegl:seamless-clone-compose") == 0) {
                // FIXME: reported by GEGL but cannot be instantiated...
                continue;
            }
            JsonObject *component = library_component(op);

            send_response(ws, "component", "component", component);
        }

    } else if (g_strcmp0(protocol, "runtime") == 0 && g_strcmp0(command, "getruntime") == 0) {

        JsonObject *runtime = json_object_new();
        json_object_set_string_member(runtime, "version", "0.4"); // protocol version
        json_object_set_string_member(runtime, "type", "imgflo");

        JsonArray *capabilities = json_array_new();
        json_array_add_string_element(capabilities, "protocol:component");
        json_object_set_array_member(runtime, "capabilities", capabilities);

        send_response(ws, "runtime", "runtime", runtime);

    } else {
        g_printerr("Unhandled message: protocol='%s', command='%s'", protocol, command);
    }
}
Ejemplo n.º 10
0
static void
skypeweb_xfer_send_init(PurpleXfer *xfer)
{
	PurpleConnection *pc = purple_account_get_connection(purple_xfer_get_account(xfer));
	SkypeWebAccount *sa = purple_connection_get_protocol_data(pc);
	gchar *basename = g_path_get_basename(purple_xfer_get_local_filename(xfer));
	gchar *id, *post, *headers;
	SkypeWebFileTransfer *swft = purple_xfer_get_protocol_data(xfer);
	JsonObject *obj = json_object_new();
	JsonObject *permissions = json_object_new();
	JsonArray *userpermissions = json_array_new();
	
	purple_xfer_set_filename(xfer, basename);
	purple_xfer_ref(xfer);
	
	json_object_set_string_member(obj, "type", "sharing/file");
	json_object_set_string_member(obj, "filename", basename);
	
	if (SKYPEWEB_BUDDY_IS_MSN(swft->from)) {
		id = g_strconcat("1:", swft->from, NULL);
	} else {
		id = g_strconcat("8:", swft->from, NULL);
	}
	json_array_add_string_element(userpermissions, "read");
	json_object_set_array_member(permissions, id, userpermissions);
	json_object_set_object_member(obj, "permissions", permissions);
	
	post = skypeweb_jsonobj_to_string(obj);
	//POST to api.asm.skype.com  /v1/objects
	//{"type":"sharing/file","permissions":{"8:eionrobb":["read"]},"filename":"GiantLobsterMoose.txt"}
	
	headers = g_strdup_printf("POST /v1/objects HTTP/1.0\r\n"
			"Connection: close\r\n"
			"Authorization: skype_token %s\r\n" //slightly different to normal!
			"Host: " SKYPEWEB_XFER_HOST "\r\n"
			"Content-Length: %d\r\n"
			"Content-Type: application/json\r\n"
			"\r\n\r\n%s",
			sa->skype_token, 
			strlen(post), post);
	
	skypeweb_fetch_url_request(sa, "https://" SKYPEWEB_XFER_HOST, TRUE, NULL, FALSE, headers, FALSE, -1, skypeweb_got_object_for_file, swft);
	
	g_free(post);
	json_object_unref(obj);
	g_free(id);
	g_free(basename);
}
Ejemplo n.º 11
0
GHashTable *
cockpit_package_listing (JsonArray **json)
{
  JsonArray *root = NULL;
  GHashTable *listing;
  CockpitPackage *package;
  GHashTable *ids;
  JsonObject *object;
  JsonArray *id;
  GList *names, *l;
  GList *packages;
  const gchar *name;
  JsonNode *node;
  JsonArray *array;
  guint i, length;

  listing = g_hash_table_new_full (g_str_hash, g_str_equal,
                                   NULL, cockpit_package_unref);

  build_package_listing (listing);

  /* Add aliases to the listing */
  packages = g_hash_table_get_values (listing);
  packages = g_list_sort (packages, compar_packages);
  g_list_foreach (packages, (GFunc)cockpit_package_ref, NULL);
  for (l = packages; l != NULL; l = g_list_next (l))
    {
      package = l->data;

      node = json_object_get_member (package->manifest, "alias");
      if (node)
        {
          /*
           * Process and remove "alias" from the manifest, as it results in
           * confusing and duplicated information for the front end.
           */
          package->alias = node = json_node_copy (node);
          json_object_remove_member (package->manifest, "alias");

          if (JSON_NODE_HOLDS_ARRAY (node))
            {
              array = json_node_get_array (node);
              length = json_array_get_length (array);
              for (i = 0; i < length; i++)
                add_alias_to_listing (listing, package, json_array_get_element (array, i));
            }
          else
            {
              add_alias_to_listing (listing, package, node);
            }
        }
    }
  g_list_free_full (packages, (GDestroyNotify)cockpit_package_unref);

  /* Now wrap up the checksums */
  finish_checksums (listing);

  /* Add checksums to the listing */
  packages = g_hash_table_get_values (listing);
  g_list_foreach (packages, (GFunc)cockpit_package_ref, NULL);
  for (l = packages; l != NULL; l = g_list_next (l))
    {
      package = l->data;
      if (package->checksum && !g_hash_table_contains (listing, package->checksum))
        {
          g_hash_table_replace (listing, package->checksum, cockpit_package_ref (package));
          g_debug ("%s: package has checksum: %s", package->name, package->checksum);
        }
    }
  g_list_free_full (packages, (GDestroyNotify)cockpit_package_unref);

  /* Build JSON packages block */
  if (json)
    {
      *json = root = json_array_new ();
      ids = g_hash_table_new (g_direct_hash, g_direct_equal);
      names = g_hash_table_get_keys (listing);
      names = g_list_sort (names, (GCompareFunc)strcmp);

      for (l = names; l != NULL; l = g_list_next (l))
        {
          name = l->data;
          package = g_hash_table_lookup (listing, name);
          id = g_hash_table_lookup (ids, package);
          if (!id)
            {
              object = json_object_new ();
              id = json_array_new();

              /* The actual package name always comes first */
              json_object_set_array_member (object, "id", id);
              json_array_add_string_element (id, package->name);
              g_hash_table_insert (ids, package, id);

              json_object_set_object_member (object, "manifest", json_object_ref (package->manifest));
              json_array_add_object_element (root, object);
            }

          /* Other ways to refer to the package */
          if (!g_str_equal (name, package->name))
              json_array_add_string_element (id, name);
        }

      g_list_free (names);
      g_hash_table_destroy (ids);
    }

  return listing;
}
Ejemplo n.º 12
0
JsonNode*
cometd_new_handshake_message(const cometd* h)
{
                                                                                                                                                                                      
  gint64 seed = ++(h->conn->msg_id_seed);
  

  /////////////////Data Concatenation/////////////                                                                                                                                                                                               

  JsonObject* dataObject = json_object_new();
  JsonNode*   dataNode = json_node_new(JSON_NODE_OBJECT);
  JsonNode*   dataRoot = json_node_init_object(dataNode, dataObject);

  dataObject = json_node_get_object(dataRoot);

  json_object_set_string_member(dataObject, "login", "test2");
  json_object_set_string_member(dataObject, "password", "password");

  ////////////////Data Concatenation////////////                                                                                                                                                                                                 

  /////////////////Auth/////////////////                                                                                                                                                                                                         

  // I begin from the most inner JsonObject of my Json File                                                                                                                                                                                      

  //here i initialize my Root JsonNode with an object in it and a JsonObject to be able to get the object from the JsonNode                                                                                                                      

  JsonObject* authObject = json_object_new();
  JsonNode*   authNode = json_node_new(JSON_NODE_OBJECT);
  JsonNode*   authRoot = json_node_init_object(authNode, authObject);

  // Here i retrieve the initialized JsonObject that is inside my JsonNode                                                                                                                                                                       
  authObject = json_node_get_object(authRoot);

  // And here some few insertion of strings in the object                                                                                                                                                                                        
  json_object_set_string_member(authObject, "action", "authenticate");
  json_object_set_string_member(authObject, "type", "GmY-HuzW.KZyH.simple");
  json_object_set_string_member(authObject, "resource", "zetapushTuto");
  json_object_set_member(authObject, "data", dataRoot);

  ///////////////Auth/////////////////                                                                                                                                                                                                           



  //////////////First Concatenation : Authentication///////////////                                                                                                                                                                              
  //Here i make the authentication of my first JsonObject with a upper membrane.                                                                                                                                                                 

  JsonObject *extMembrane = json_object_new();
  JsonNode   *contactMembrane = json_node_new(JSON_NODE_OBJECT);
  JsonNode   *secondRootMembrane = json_node_init_object(contactMembrane, extMembrane);

  extMembrane = json_node_get_object(secondRootMembrane);

  json_object_set_member(extMembrane, "authentication", authRoot);
  /////////////First Concatenation////////////////                                                                                                                                                                                               

  ////////////Second Concatenation : Ext///////////////                                                                                                                                                                                          
  // Here i finnaly concatenante my last JsonObject and encapsulate the overall file inside the root JsonNode                                                                                                                                    
  JsonObject *rootObjectMembrane = json_object_new();
  JsonNode   *initRootMembrane = json_node_new(JSON_NODE_OBJECT);
  JsonNode   *rootMembrane = json_node_init_object(initRootMembrane, rootObjectMembrane);

   rootObjectMembrane = json_node_get_object(rootMembrane);

   json_object_set_member(rootObjectMembrane, "ext", secondRootMembrane);


  // I still needs to create a object under Ext JsonNode, then an JsonArray to supportedConnectionTypes                                                                                                                                          
  //Then add the advice object with "timeout" and "interval"                                                                                                                                                                                     

  json_object_set_int_member(rootObjectMembrane, "id", seed);
  json_object_set_string_member(rootObjectMembrane, "version", "1.0");
  json_object_set_string_member(rootObjectMembrane, "minimumVersion", "1.0");
  json_object_set_string_member(rootObjectMembrane, "channel", "/meta/handshake");

  JsonArray* json_transports = json_array_new();
  GList* entry = h->config->transports;
  while (entry){
    cometd_transport* t = entry->data;
    json_array_add_string_element(json_transports, t->name);
    entry = g_list_next(entry);
}

  //json_array_add_string_element(json_transports, "long-polling");
  json_object_set_array_member(rootObjectMembrane, "supportedConnectionTypes", json_transports);

  //////////Advice////////                                                                                                                                                                                                                       
  JsonObject *adviceMembrane = json_object_new();
  JsonNode   *adviceNodeMembrane = json_node_new(JSON_NODE_OBJECT);
  JsonNode   *adviceRootMembrane = json_node_init_object(adviceNodeMembrane, adviceMembrane);
  gint64 interval = 0;
  gint64 timeout = 60000;
  adviceMembrane = json_node_get_object(adviceRootMembrane);
  json_object_set_int_member(adviceMembrane, "timeout", timeout);
  json_object_set_int_member(adviceMembrane, "interval", interval);
  json_object_set_member(rootObjectMembrane, "advice", adviceRootMembrane);

  /////////Advice////////                                                                                                                                                                                                                        



   ////////////Second Concatenation//////////////
  
  // call extensions with message - TODO: implement extensions first
  //json_node_take_object(root, obj);
  return rootMembrane;
}
Ejemplo n.º 13
0
static int 
pb_send_im(PurpleConnection *pc, const gchar *who, const gchar *message, PurpleMessageFlags flags)
{
	PushBulletAccount *pba = pc->proto_data;
	gchar *stripped, *postdata;
	gchar *guid;
	
	if (g_str_has_prefix(message, "?OTR"))
		return 0;
	
	if (PB_IS_SMS(who))
	{
		JsonObject *root = json_object_new();
		JsonObject *data = json_object_new();
		JsonArray *addresses = json_array_new();
		
		json_array_add_string_element(addresses, who);
		json_object_set_array_member(data, "addresses", addresses);
		
		guid = pb_get_next_id(pba);
		json_object_set_string_member(data, "guid", guid);
		json_object_set_string_member(data, "target_device_iden", pba->main_sms_device);
		json_object_set_boolean_member(data, "encrypted", FALSE);
		
		stripped = g_strstrip(purple_markup_strip_html(message));
		json_object_set_string_member(data, "message", stripped);
		g_free(stripped);
		
		json_object_set_object_member(root, "data", data);
		
		postdata = pb_jsonobj_to_string(root);
		pb_fetch_url(pba, "https://api.pushbullet.com/v3/create-text", postdata, NULL, NULL);
		g_free(postdata);
		
		json_object_unref(root);
		
		g_hash_table_insert(pba->sent_messages_hash, guid, guid);
		return 1;
	}
	
	if (!strchr(who, '@')) {
		return -1;
	}
	
	//<IMG ID="5"> - embedded image i.e. MMS
	
	/* Image flow:
	POST to https://api.pushbullet.com/v3/start-upload {"name":"imagename.jpg","size":12345,"type":"image/jpeg"}
	=> {"id":"abcde","piece_size":5242880,"piece_urls":["https://upload.pushbullet.com/upload-piece/12345/0"]}
	
	POST data in chunks to the pieces_urls
	
	POST to https://api.pushbullet.com/v3/finish-upload {"id":"abcde"} (from earlier)
	=> {"file_name":"imagename.jpg","file_type":"image/jpeg","file_url":"..urltoimage..."}
	
	POST to https://api.pushbullet.com/v2/pushes {"type":"file","file_name":"filename.jpg","file_url":"..urltoimage...","file_type":"image/jpeg","email":"touser"}
	*/
	
	{
		JsonObject *root = json_object_new();
		
		guid = pb_get_next_id(pba);
		json_object_set_string_member(root, "guid", guid);
		json_object_set_string_member(root, "type", "note");
		json_object_set_string_member(root, "title", "");
		json_object_set_string_member(root, "url", "");
		json_object_set_string_member(root, "email", who);
		
		stripped = g_strstrip(purple_markup_strip_html(message));
		json_object_set_string_member(root, "body", stripped);
		g_free(stripped);
		
		postdata = pb_jsonobj_to_string(root);
		pb_fetch_url(pba, "https://api.pushbullet.com/v2/pushes", postdata, NULL, NULL);
		g_free(postdata);
		
		json_object_unref(root);
		
		g_hash_table_insert(pba->sent_messages_hash, guid, guid);
		return 1;
	}
	
	return -1;
}
Ejemplo n.º 14
0
void trg_tree_view_persist(TrgTreeView * tv, guint flags)
{
    JsonObject *props = trg_prefs_get_tree_view_props(tv);
    GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(tv));
    GList *cols, *li;
    JsonArray *widths, *columns;
    gint sort_column_id;
    GtkSortType sort_type;

    if (flags & TRG_TREE_VIEW_PERSIST_SORT) {
        gtk_tree_sortable_get_sort_column_id(GTK_TREE_SORTABLE
                                             ((flags &
                                               TRG_TREE_VIEW_SORTABLE_PARENT)
                                              ?
                                              gtk_tree_model_filter_get_model
                                              (GTK_TREE_MODEL_FILTER
                                               (model)) : model),
                                             &sort_column_id, &sort_type);

        if (json_object_has_member(props, TRG_PREFS_KEY_TV_SORT_COL))
            json_object_remove_member(props, TRG_PREFS_KEY_TV_SORT_COL);

        if (json_object_has_member(props, TRG_PREFS_KEY_TV_SORT_TYPE))
            json_object_remove_member(props, TRG_PREFS_KEY_TV_SORT_TYPE);

        json_object_set_int_member(props, TRG_PREFS_KEY_TV_SORT_COL,
                                   (gint64) sort_column_id);
        json_object_set_int_member(props, TRG_PREFS_KEY_TV_SORT_TYPE,
                                   (gint64) sort_type);
    }

    if (flags & TRG_TREE_VIEW_PERSIST_LAYOUT) {
        cols = gtk_tree_view_get_columns(GTK_TREE_VIEW(tv));

        if (json_object_has_member(props, TRG_PREFS_KEY_TV_WIDTHS))
            json_object_remove_member(props, TRG_PREFS_KEY_TV_WIDTHS);

        widths = json_array_new();
        json_object_set_array_member(props, TRG_PREFS_KEY_TV_WIDTHS,
                                     widths);

        if (json_object_has_member(props, TRG_PREFS_KEY_TV_COLUMNS))
            json_object_remove_member(props, TRG_PREFS_KEY_TV_COLUMNS);

        columns = json_array_new();
        json_object_set_array_member(props, TRG_PREFS_KEY_TV_COLUMNS,
                                     columns);

        for (li = cols; li; li = g_list_next(li)) {
            GtkTreeViewColumn *col = (GtkTreeViewColumn *) li->data;
            trg_column_description *desc =
                g_object_get_data(G_OBJECT(li->data),
                                  GDATA_KEY_COLUMN_DESC);

            json_array_add_string_element(columns, desc->id);
            json_array_add_int_element(widths,
                                       gtk_tree_view_column_get_width
                                       (col));
        }

        g_list_free(cols);
    }
}
Ejemplo n.º 15
0
JsonNode *torrent_get(gint64 id)
{
    JsonNode *root = base_request(METHOD_TORRENT_GET);
    JsonObject *args = node_get_arguments(root);
    JsonArray *fields = json_array_new();

    if (id == TORRENT_GET_TAG_MODE_UPDATE) {
        json_object_set_string_member(args, PARAM_IDS,
                                      FIELD_RECENTLY_ACTIVE);
    } else if (id >= 0) {
        JsonArray *ids = json_array_new();
        json_array_add_int_element(ids, id);
        json_object_set_array_member(args, PARAM_IDS, ids);
    }

    json_array_add_string_element(fields, FIELD_ETA);
    json_array_add_string_element(fields, FIELD_PEERS);
    json_array_add_string_element(fields, FIELD_PEERSFROM);
    json_array_add_string_element(fields, FIELD_FILES);
    json_array_add_string_element(fields, FIELD_PEERS_SENDING_TO_US);
    json_array_add_string_element(fields, FIELD_PEERS_GETTING_FROM_US);
    json_array_add_string_element(fields, FIELD_PEERS_CONNECTED);
    /*json_array_add_string_element(fields, FIELD_HAVEVALID);
       json_array_add_string_element(fields, FIELD_HAVEUNCHECKED); */
    json_array_add_string_element(fields, FIELD_RATEUPLOAD);
    json_array_add_string_element(fields, FIELD_RATEDOWNLOAD);
    json_array_add_string_element(fields, FIELD_STATUS);
    json_array_add_string_element(fields, FIELD_ISFINISHED);
    json_array_add_string_element(fields, FIELD_ISPRIVATE);
    json_array_add_string_element(fields, FIELD_ADDED_DATE);
    json_array_add_string_element(fields, FIELD_DOWNLOADEDEVER);
    json_array_add_string_element(fields, FIELD_UPLOADEDEVER);
    json_array_add_string_element(fields, FIELD_SIZEWHENDONE);
    json_array_add_string_element(fields, FIELD_QUEUE_POSITION);
    json_array_add_string_element(fields, FIELD_ID);
    json_array_add_string_element(fields, FIELD_NAME);
    json_array_add_string_element(fields, FIELD_PERCENTDONE);
    json_array_add_string_element(fields, FIELD_COMMENT);
    json_array_add_string_element(fields, FIELD_TOTAL_SIZE);
    json_array_add_string_element(fields, FIELD_LEFT_UNTIL_DONE);
    json_array_add_string_element(fields, FIELD_ANNOUNCE_URL);
    json_array_add_string_element(fields, FIELD_ERROR_STRING);
    json_array_add_string_element(fields, FIELD_SWARM_SPEED);
    json_array_add_string_element(fields, FIELD_TRACKER_STATS);
    json_array_add_string_element(fields, FIELD_DOWNLOAD_DIR);
    json_array_add_string_element(fields, FIELD_HASH_STRING);
    json_array_add_string_element(fields, FIELD_DONE_DATE);
    json_array_add_string_element(fields, FIELD_HONORS_SESSION_LIMITS);
    json_array_add_string_element(fields, FIELD_UPLOAD_LIMIT);
    json_array_add_string_element(fields, FIELD_UPLOAD_LIMITED);
    json_array_add_string_element(fields, FIELD_DOWNLOAD_LIMIT);
    json_array_add_string_element(fields, FIELD_DOWNLOAD_LIMITED);
    json_array_add_string_element(fields, FIELD_BANDWIDTH_PRIORITY);
    json_array_add_string_element(fields, FIELD_SEED_RATIO_LIMIT);
    json_array_add_string_element(fields, FIELD_SEED_RATIO_MODE);
    json_array_add_string_element(fields, FIELD_PEER_LIMIT);
    json_array_add_string_element(fields, FIELD_ACTIVITY_DATE);
    json_array_add_string_element(fields, FIELD_ERRORSTR);
    json_array_add_string_element(fields, FIELD_WANTED);
    json_array_add_string_element(fields, FIELD_PRIORITIES);
    json_array_add_string_element(fields, FIELD_RECHECK_PROGRESS);
    json_object_set_array_member(args, PARAM_FIELDS, fields);
    return root;
}
Ejemplo n.º 16
0
/* Params utils */
static gboolean
melo_jsonrpc_add_node (JsonNode *node, JsonObject *schema,
                       JsonObject *obj, JsonArray *array)
{
  GType vtype = G_TYPE_INVALID;
  const gchar *s_name;
  const gchar *s_type;
  JsonNodeType type;

  /* Get name and type from schema */
  s_name = json_object_get_string_member (schema, "name");
  s_type = json_object_get_string_member (schema, "type");
  if (!s_name || !s_type)
    return FALSE;

  /* Get type */
  type = json_node_get_node_type (node);
  if (type == JSON_NODE_VALUE)
    vtype = json_node_get_value_type (node);

  /* Check type:
   * We check only first letter of the type string.
   */
  switch (s_type[0]) {
    case 'b':
      /* Boolean: check type */
      if (vtype != G_TYPE_BOOLEAN)
        return FALSE;

      /* Add to object / array */
      if (obj || array) {
        gboolean v;
        v = json_node_get_boolean (node);
        if (obj)
          json_object_set_boolean_member (obj, s_name, v);
        else
          json_array_add_boolean_element (array, v);
        break;
      }
      break;
    case 'i':
      /* Integer: check type */
      if (vtype != G_TYPE_INT64)
        return FALSE;

      /* Add to object / array */
      if (obj || array) {
        gint64 v;
        v = json_node_get_int (node);
        if (obj)
          json_object_set_int_member (obj, s_name, v);
        else
          json_array_add_int_element (array, v);
      }
      break;
    case 'd':
      /* Double: check type */
      if (vtype != G_TYPE_DOUBLE)
        return FALSE;

      /* Add to object / array */
      if (obj || array) {
        gdouble v;
        v = json_node_get_double (node);
        if (obj)
          json_object_set_double_member (obj, s_name, v);
        else
          json_array_add_double_element (array, v);
      }
      break;
    case 's':
      /* String: check type */
      if (vtype != G_TYPE_STRING)
        return FALSE;

      /* Add to object / array */
      if (obj || array) {
        const gchar *v;
        v = json_node_get_string (node);
        if (obj)
          json_object_set_string_member (obj, s_name, v);
        else
          json_array_add_string_element (array, v);
      }
      break;
    case 'o':
      /* Object: check type */
      if (type != JSON_NODE_OBJECT)
        return FALSE;

      /* Add to object / array */
      if (obj || array) {
        JsonObject *v;
        v = json_node_dup_object (node);
        if (obj)
          json_object_set_object_member (obj, s_name, v);
        else
          json_array_add_object_element (array, v);
      }
      break;
    case 'a':
      /* Array: check type */
      if (type != JSON_NODE_ARRAY)
        return FALSE;

      /* Add to object / array */
      if (obj || array) {
        JsonArray *v;
        v = json_node_dup_array (node);
        if (obj)
          json_object_set_array_member (obj, s_name, v);
        else
          json_array_add_array_element (array, v);
      }
      break;
    default:
      return FALSE;
  }
  return TRUE;
}
Ejemplo n.º 17
0
Archivo: ui.c Proyecto: imgflo/imgflo
static void
ui_connection_handle_message(UiConnection *self,
                const gchar *protocol, const gchar *command, JsonObject *payload,
                SoupWebsocketConnection *ws)
{
    if (g_strcmp0(protocol, "graph") == 0) {
        handle_graph_message(self, command, payload, ws);
    } else if (g_strcmp0(protocol, "network") == 0) {
        handle_network_message(self, command, payload, ws);
    } else if (g_strcmp0(protocol, "component") == 0 && g_strcmp0(command, "list") == 0) {
        gint no_components = 0;
        gchar **operation_names = library_list_components(self->component_lib, &no_components);
        for (int i=0; i<no_components; i++) {
            const gchar *op = operation_names[i];
            if (op) {
                JsonObject *component = library_get_component(self->component_lib, op);
                send_response(ws, "component", "component", component);
            }
        }
        g_strfreev(operation_names);
    } else if (g_strcmp0(protocol, "component") == 0 && g_strcmp0(command, "source") == 0) {
        const gchar *name = json_object_get_string_member(payload, "name");
        gchar *actual_name = library_set_source(self->component_lib,
            name,
            json_object_get_string_member(payload, "code")
        );
        if (actual_name) {
            JsonObject *component = library_get_component(self->component_lib, name);
            send_response(ws, "component", "component", component);
        } else {
            // TODO: error response
        }
        g_free(actual_name);
    } else if (g_strcmp0(protocol, "component") == 0 && g_strcmp0(command, "getsource") == 0) {
        const gchar *name = json_object_get_string_member(payload, "name");


        JsonObject *source_info = json_object_new();
        // TODO: generalize for subgraphs-as-components
        if (g_strcmp0(name, self->main_network) == 0) {

            json_object_set_string_member(source_info, "name", "main"); // FIXME: dont hardcode
            json_object_set_string_member(source_info, "library", "default"); // FIXME: dont hardcode

            Network *n = g_hash_table_lookup(self->network_map, self->main_network);
            g_assert(n);
            JsonObject *g = graph_save_json(n->graph);
            gsize len = 0;
            gchar *code = json_stringify(g, &len);
            g_assert(len);
            json_object_set_string_member(source_info, "language", "json");
            json_object_set_string_member(source_info, "code", code);
        } else {
            json_object_set_string_member(source_info, "name", name);
            gchar *code = library_get_source(self->component_lib, name);
            json_object_set_string_member(source_info, "library", "imgflo");
            json_object_set_string_member(source_info, "language", "c");
            json_object_set_string_member(source_info, "code", code);
        }

        send_response(ws, "component", "source", source_info);

    } else if (g_strcmp0(protocol, "runtime") == 0 && g_strcmp0(command, "getruntime") == 0) {

        JsonObject *runtime = json_object_new();
        json_object_set_string_member(runtime, "version", "0.4"); // protocol version
        json_object_set_string_member(runtime, "type", "imgflo");
        json_object_set_string_member(runtime, "graph", self->main_network);

        JsonArray *capabilities = json_array_new();
        json_array_add_string_element(capabilities, "protocol:component");
        json_array_add_string_element(capabilities, "protocol:graph");
        json_array_add_string_element(capabilities, "protocol:runtime");
        json_array_add_string_element(capabilities, "protocol:network");
        json_array_add_string_element(capabilities, "component:getsource");
        json_array_add_string_element(capabilities, "component:setsource");
        json_object_set_array_member(runtime, "capabilities", capabilities);

        send_response(ws, "runtime", "runtime", runtime);

        if (self->main_network) {
            send_ports(g_hash_table_lookup(self->network_map, self->main_network), ws);
        }

    } else if (g_strcmp0(protocol, "runtime") == 0 && g_strcmp0(command, "packet") == 0) {
        gchar *graph_id = g_strdup(json_object_get_string_member(payload, "graph"));
        const gchar *port = json_object_get_string_member(payload, "port");
        const gchar *event = json_object_get_string_member(payload, "event");
        if (!graph_id) {
            // NoFlo RemoteSubGraph currently does not send graph info
            graph_id = g_strdup(self->main_network);
        }
        Network *network = (graph_id) ? g_hash_table_lookup(self->network_map, graph_id) : NULL;
        g_free(graph_id);
        g_return_if_fail(network);

        if (g_strcmp0(event, "data") == 0) {
            GValue data = G_VALUE_INIT;
            json_node_get_value(json_object_get_member(payload, "payload"), &data);
            network_send_packet(network, port, &data);
        } else {
            // TODO: support connect/disconnect?
            imgflo_warning("Unknown runtime:packet event: %s", event);
        }
    } else {
        imgflo_warning("Unhandled message: protocol='%s', command='%s'", protocol, command);
    }
}
Ejemplo n.º 18
0
/**
 * push_gcm_client_deliver_async:
 * @client: (in): A #PushGcmClient.
 * @identities: (element-type PushGcmIdentity*): A #GList of #PushGcmIdentity.
 * @message: A #PushGcmMessage.
 * @cancellable: (allow-none): A #GCancellable or %NULL.
 * @callback: A #GAsyncReadyCallback.
 * @user_data: User data for @callback.
 *
 * Asynchronously deliver a #PushGcmMessage to one or more GCM enabled
 * devices.
 */
void
push_gcm_client_deliver_async (PushGcmClient       *client,
                               GList               *identities,
                               PushGcmMessage      *message,
                               GCancellable        *cancellable,
                               GAsyncReadyCallback  callback,
                               gpointer             user_data)
{
   PushGcmClientPrivate *priv;
   GSimpleAsyncResult *simple;
   SoupMessage *request;
   const gchar *registration_id;
   const gchar *collapse_key;
   JsonGenerator *g;
   JsonObject *obj;
   JsonObject *data;
   JsonObject *mdata;
   JsonArray *ar;
   JsonNode *node;
   GList *iter;
   GList *list;
   gchar *str;
   gsize length;
   guint time_to_live;

   ENTRY;

   g_return_if_fail(PUSH_IS_GCM_CLIENT(client));
   g_return_if_fail(identities);
   g_return_if_fail(PUSH_IS_GCM_MESSAGE(message));
   g_return_if_fail(!cancellable || G_IS_CANCELLABLE(cancellable));
   g_return_if_fail(callback);

   priv = client->priv;

   request = soup_message_new("POST", PUSH_GCM_CLIENT_URL);
   ar = json_array_new();

   for (iter = identities; iter; iter = iter->next) {
      g_assert(PUSH_IS_GCM_IDENTITY(iter->data));
      registration_id = push_gcm_identity_get_registration_id(iter->data);
      json_array_add_string_element(ar, registration_id);
   }

   str = g_strdup_printf("key=%s", priv->auth_token);
   soup_message_headers_append(request->request_headers, "Authorization", str);
   g_free(str);

   soup_message_headers_append(request->request_headers,
                               "Accept",
                               "application/json");

   data = json_object_new();

   if ((collapse_key = push_gcm_message_get_collapse_key(message))) {
      json_object_set_string_member(data, "collapse_key", collapse_key);
   }

   json_object_set_boolean_member(data,
                                  "delay_while_idle",
                                  push_gcm_message_get_delay_while_idle(message));

   json_object_set_boolean_member(data,
                                  "dry_run",
                                  push_gcm_message_get_dry_run(message));

   if ((time_to_live = push_gcm_message_get_time_to_live(message))) {
      json_object_set_int_member(data, "time_to_live", time_to_live);
   }

   if ((mdata = push_gcm_message_get_data(message))) {
      json_object_set_object_member(data, "data", mdata);
   }

   obj = json_object_new();
   json_object_set_array_member(obj, "registration_ids", ar);
   json_object_set_object_member(obj, "data", data);

   node = json_node_new(JSON_NODE_OBJECT);
   json_node_set_object(node, obj);
   json_object_unref(obj);

   g = json_generator_new();
   json_generator_set_pretty(g, TRUE);
   json_generator_set_indent(g, 2);
   json_generator_set_root(g, node);
   str = json_generator_to_data(g, &length);
   json_node_free(node);
   g_object_unref(g);

   g_print("REQUEST: \"%s\"\n", str);

   soup_message_set_request(request,
                            "application/json",
                            SOUP_MEMORY_TAKE,
                            str,
                            length);

   simple = g_simple_async_result_new(G_OBJECT(client), callback, user_data,
                                      push_gcm_client_deliver_async);

   /*
    * Keep the list of identities around until we receive our result.
    * We need them to key with the resulting array.
    */
   list = g_list_copy(identities);
   g_list_foreach(list, (GFunc)g_object_ref, NULL);
   g_object_set_data_full(G_OBJECT(simple),
                          "identities",
                          list,
                          _push_gcm_identities_free);

   soup_session_queue_message(SOUP_SESSION(client),
                              request,
                              push_gcm_client_deliver_cb,
                              simple);

   EXIT;
}
Ejemplo n.º 19
0
} END_TEST

/* FIXME: more tests required for:
 *
 * - array containing an array (of various types).
 * - array containing an object (containing various types).
 */
START_TEST(test_cc_oci_json_arr_to_string) {
	gchar *str;
	JsonArray *array;
	gboolean ret;

	ck_assert (! cc_oci_json_arr_to_string (NULL, false));
	ck_assert (! cc_oci_json_arr_to_string (NULL, true));

	array = json_array_new ();

	/* empty array, non-pretty */
	str = cc_oci_json_arr_to_string (array, false);
	ck_assert (str);
	ck_assert (! g_strcmp0 (str, "[]"));
	g_free (str);

	/* empty array, pretty */
	str = cc_oci_json_arr_to_string (array, true);
	ck_assert (str);

	ret = g_regex_match_simple (
			/* pair of braces containing optional
			 * whitespace.
			 */
			"[\\s*]",
			str, 0, 0);
	ck_assert (ret);

	g_free (str);

	json_array_add_null_element (array);
	json_array_add_null_element (array);
	json_array_add_boolean_element (array, false);
	json_array_add_boolean_element (array, true);
	json_array_add_int_element (array, 123);
	json_array_add_double_element (array, 3.1412);
	json_array_add_string_element (array, "foo bar");

	str = cc_oci_json_arr_to_string (array, false);
	ck_assert (str);

	ret = g_regex_match_simple (
			"[\\s*"                  /* opening bracket */
			"\\s*null\\s*,"          /* null */
			"\\s*null\\s*,"          /* null */
			"\\s*false\\s*,"         /* false */
			"\\s*true\\s*,"          /* true */
			"\\s*123\\s*,"           /* int */
			"\\s*3\\.1412\\s*,"      /* double */
			"\\s*\"foo\\ bar\"\\s*," /* string */
			"\\s*]",                 /* closing bracket */
			str, 0, 0);
	ck_assert (ret);
	g_free (str);

	/* clean up */
	json_array_unref (array);

} END_TEST