Example #1
0
/*
 * For backwards compatibility we need to normalize some host params
 * so they can be matched against.
 *
 * Some sessions shouldn't be shared by multiple channels, such as those that
 * explicitly specify a host-key or specific user. This changed over time
 * so modify things to make it a simple match.
 *
 * If the given user is the current user, remove it. Preserves the current
 * behavior.
 *
 */
static void
cockpit_router_normalize_host_params (JsonObject *options)
{
  const gchar *sharable = NULL;
  const gchar *user = NULL;
  gboolean needs_private = FALSE;

  if (!cockpit_json_get_string (options, "session", NULL, &sharable))
    sharable = NULL;

  if (!cockpit_json_get_string (options, "user", NULL, &user))
    user = NULL;

  if (!sharable)
    {
      /* Fallback to older ways of indicating this */
      if (user || json_object_has_member (options, "host-key"))
        needs_private = TRUE;

      if (json_object_has_member (options, "temp-session"))
        {
          if (needs_private && !cockpit_json_get_bool (options, "temp-session",
                                                       TRUE, &needs_private))
            needs_private = TRUE;
          json_object_remove_member (options, "temp-session");
        }
    }

  if (g_strcmp0 (user, g_get_user_name ()) == 0)
    json_object_remove_member (options, "user");

  if (needs_private)
    json_object_set_string_member (options, "session", "private");
}
static JsonObject *trg_prefs_get_tree_view_props(TrgTreeView * tv)
{
    TrgTreeViewPrivate *priv = TRG_TREE_VIEW_GET_PRIVATE(tv);
    JsonObject *root = trg_prefs_get_root(priv->prefs);
    const gchar *className = priv->configId
        && strlen(priv->configId) >
        0 ? priv->configId : G_OBJECT_TYPE_NAME(tv);
    JsonObject *obj;
    JsonObject *tvProps = NULL;

    if (!json_object_has_member(root, TRG_PREFS_KEY_TREE_VIEWS)) {
        obj = json_object_new();
        json_object_set_object_member(root, TRG_PREFS_KEY_TREE_VIEWS, obj);
    } else {
        obj =
            json_object_get_object_member(root, TRG_PREFS_KEY_TREE_VIEWS);
    }

    if (!json_object_has_member(obj, className)) {
        tvProps = json_object_new();
        json_object_set_object_member(obj, className, tvProps);
    } else {
        tvProps = json_object_get_object_member(obj, className);
    }

    return tvProps;
}
Example #3
0
static dt_gphoto_album_t *_json_new_album(JsonObject *obj)
{
  // handle on writable albums (in Google Photo only albums created by the API are writeable via the API)

  if(json_object_has_member(obj, "isWriteable"))
    if(json_object_get_boolean_member(obj, "isWriteable"))
    {
      dt_gphoto_album_t *album = gphoto_album_init();
      if(album == NULL) goto error;

      const char *id = json_object_get_string_member(obj, "id");
      const char *name = json_object_get_string_member(obj, "title");
      const int size = json_object_has_member(obj, "mediaItemsCount")
        ? json_object_get_int_member(obj, "mediaItemsCount")
        : 0;

      if(id == NULL || name == NULL)
      {
        gphoto_album_destroy(album);
        goto error;
      }

      album->id = g_strdup(id);
      album->name = g_strdup(name);
      album->size = size;

      return album;
    }

 error:
  return NULL;
}
static void
list_command_completed (gpointer data)
{
	FrCommandUnarchiver *unar_comm = FR_COMMAND_UNARCHIVER (data);
	JsonParser          *parser;
	GError              *error = NULL;

	parser = json_parser_new ();
	if (json_parser_load_from_stream (parser, unar_comm->stream, NULL, &error)) {
		JsonObject *root;

		root = json_node_get_object (json_parser_get_root (parser));

		if (json_object_get_int_member (root, "lsarFormatVersion") == LSAR_SUPPORTED_FORMAT) {
			JsonArray *content;
			int        i;

			content = json_object_get_array_member (root, "lsarContents");
			for (i = 0; i < json_array_get_length (content); i++) {
				JsonObject *entry;
				FileData   *fdata;
				const char *filename;

				entry = json_array_get_object_element (content, i);
				fdata = file_data_new ();
				fdata->size = json_object_get_int_member (entry, "XADFileSize");
				fdata->modified = mktime_from_string (json_object_get_string_member (entry, "XADLastModificationDate"));
				if (json_object_has_member (entry, "XADIsEncrypted"))
					fdata->encrypted = json_object_get_int_member (entry, "XADIsEncrypted") == 1;

				filename = json_object_get_string_member (entry, "XADFileName");
				if (*filename == '/') {
					fdata->full_path = g_strdup (filename);
					fdata->original_path = fdata->full_path;
				}
				else {
					fdata->full_path = g_strconcat ("/", filename, NULL);
					fdata->original_path = fdata->full_path + 1;
				}

				fdata->link = NULL;
				if (json_object_has_member (entry, "XADIsDirectory"))
					fdata->dir = json_object_get_int_member (entry, "XADIsDirectory") == 1;
				if (fdata->dir)
					fdata->name = _g_path_get_dir_name (fdata->full_path);
				else
					fdata->name = g_strdup (_g_path_get_basename (fdata->full_path));
				fdata->path = _g_path_remove_level (fdata->full_path);

				fr_archive_add_file (FR_ARCHIVE (unar_comm), fdata);
			}
		}
	}

	g_object_unref (parser);
}
Example #5
0
File: json.c Project: GNOME/gegl
/* json_op_class */
static const gchar *
metadata_get_property(JsonObject *root, const gchar *prop) {
  if (json_object_has_member(root, "properties")) {
      JsonObject *properties = json_object_get_object_member(root, "properties");
      if (json_object_has_member(properties, prop)) {
        return json_object_get_string_member(properties, prop);
      }
  }
  return NULL;
}
Example #6
0
void
cb_mini_tweet_parse (CbMiniTweet *t,
                     JsonObject  *obj)
{
  GDateTime *time;
  JsonObject *extended_object;
  const char *tweet_text;

  if (json_object_has_member (obj, "extended_tweet"))
    extended_object = json_object_get_object_member (obj, "extended_tweet");
  else
    extended_object = obj;

  time = cb_utils_parse_date (json_object_get_string_member (obj, "created_at"));

  t->id = json_object_get_int_member (obj, "id");
  if (json_object_has_member (extended_object, "full_text"))
    tweet_text = json_object_get_string_member (extended_object, "full_text");
  else
    tweet_text = json_object_get_string_member (extended_object, "text");

  if (json_object_has_member (extended_object, "display_text_range"))
    {
      /* We only remove the prefix */
      guint start = (guint)json_array_get_int_element (
                          json_object_get_array_member (extended_object, "display_text_range"),
                          0);
      guint i;
      const char *p = tweet_text;

      /* Skip ahead */
      for (i = 0; i < start; i ++)
        p = g_utf8_next_char (p);

      t->text = g_strdup (p);
      t->display_range_start = start;
    }
  else
    {
      t->text = g_strdup (tweet_text);
      t->display_range_start= 0;
    }

  t->created_at = g_date_time_to_unix (time);
  cb_user_identity_parse (&t->author, json_object_get_object_member (obj, "user"));

  g_date_time_unref (time);
}
JsonNode *trg_prefs_get_value(TrgPrefs * p, const gchar * key, int type,
                              int flags)
{
    TrgPrefsPrivate *priv = p->priv;
    JsonNode *res;

    if (priv->profile && (flags & TRG_PREFS_PROFILE)) {
        if ((res =
             trg_prefs_get_value_inner(priv->profile, key, type, flags)))
            return res;
    } else if (priv->connectionObj && (flags & TRG_PREFS_CONNECTION)) {
        if ((res =
             trg_prefs_get_value_inner(priv->connectionObj, key, type,
                                       flags)))
            return res;
    } else {
        if ((res =
             trg_prefs_get_value_inner(priv->userObj, key, type, flags)))
            return res;
    }

    if (priv->defaultsObj
        && json_object_has_member(priv->defaultsObj, key))
        return json_object_get_member(priv->defaultsObj, key);

    return NULL;
}
static GType
object_peek_type (JsonNode *node)
{
   JsonObject *obj;
   const gchar *type_str;

   if (!node ||
       !JSON_NODE_HOLDS_OBJECT(node) ||
       !(obj = json_node_get_object(node)) ||
       !json_object_has_member(obj, "type") ||
       !JSON_NODE_HOLDS_VALUE(json_object_get_member(obj, "type")) ||
       !(type_str = json_object_get_string_member(obj, "type"))) {
      return FALSE;
   }

   if (!g_strcmp0(type_str, "note")) {
      return CATCH_TYPE_NOTE;
   } else if (!g_strcmp0(type_str, "image")) {
      return CATCH_TYPE_IMAGE;
   } else if (!g_strcmp0(type_str, "audio")) {
      return CATCH_TYPE_AUDIO;
   } else if (!g_strcmp0(type_str, "comment")) {
      return CATCH_TYPE_COMMENT;
   } else if (!g_strcmp0(type_str, "attachment")) {
      return CATCH_TYPE_ATTACHMENT;
   } else if (!g_strcmp0(type_str, "checkitem")) {
      return CATCH_TYPE_CHECK_ITEM;
   }

   return G_TYPE_NONE;
}
Example #9
0
static void
skypeweb_got_self_details(SkypeWebAccount *sa, JsonNode *node, gpointer user_data)
{
	JsonObject *userobj;
	const gchar *old_alias;
	const gchar *displayname = NULL;
	const gchar *username;
	
	if (node == NULL || json_node_get_node_type(node) != JSON_NODE_OBJECT)
		return;
	userobj = json_node_get_object(node);
	
	username = json_object_get_string_member(userobj, "username");
	g_free(sa->username); sa->username = g_strdup(username);
	
	old_alias = purple_account_get_private_alias(sa->account);
	if (!old_alias || !*old_alias) {
		if (json_object_has_member(userobj, "displayname"))
			displayname = json_object_get_string_member(userobj, "displayname");
		if (!displayname || g_str_equal(displayname, username))
			displayname = json_object_get_string_member(userobj, "firstname");
	
		if (displayname)
			purple_account_set_private_alias(sa->account, displayname);
	}
	
	if (!PURPLE_CONNECTION_IS_CONNECTED(sa->pc)) {
		skypeweb_do_all_the_things(sa);
	}
}
Example #10
0
static JsonObject *gphoto_parse_response(dt_gphoto_context_t *ctx, GString *response)
{
  GError *error = NULL;
  gboolean ret = json_parser_load_from_data(ctx->json_parser, response->str, response->len, &error);

  if(ret)
  {
    JsonNode *root = json_parser_get_root(ctx->json_parser);
    // we should always have a dict
    g_return_val_if_fail((json_node_get_node_type(root) == JSON_NODE_OBJECT), NULL);

    JsonObject *rootdict = json_node_get_object(root);
    if(json_object_has_member(rootdict, "error"))
    {
      JsonObject *errorstruct = json_object_get_object_member(rootdict, "error");
      g_return_val_if_fail((errorstruct != NULL), NULL);
      const gchar *errormessage = json_object_get_string_member(errorstruct, "message");
      g_return_val_if_fail((errormessage != NULL), NULL);
      g_string_assign(ctx->errmsg, errormessage);
      return NULL;
    }

    return rootdict;
  }
  else // not a json response, can be the upload-token
  {
    ctx->response = g_string_new(response->str);
    return NULL;
  }
}
/**
 * server_new_from_json:
 * @object: JSON object with server definition
 *
 * Looks at the type and then uses a subclassed function to build the
 * server.
 *
 * Return value: A new Server object or NULL if error
 */
Server *
server_new_from_json (JsonObject * object)
{
	g_return_val_if_fail(object != NULL, NULL);

	if (!json_object_has_member(object, "Protocol")) {
		return NULL;
	}

	JsonNode * proto_node = json_object_get_member(object, "Protocol");
	if (JSON_NODE_TYPE(proto_node) != JSON_NODE_VALUE) {
		return NULL;
	}
	if (json_node_get_value_type(proto_node) != G_TYPE_STRING) {
		return NULL;
	}

	const gchar * proto = json_node_get_string(proto_node);
	Server * newserver = NULL;

	if (g_strcmp0(proto, "ICA") == 0 || g_strcmp0(proto, "ica") == 0) {
		newserver = citrix_server_new_from_json(object);
	}
	else if (g_strcmp0(proto, "freerdp") == 0 || g_strcmp0(proto, "rdp") == 0 || g_strcmp0(proto, "RDP") == 0 || g_strcmp0(proto, "FreeRDP") == 0) {
		newserver = rdp_server_new_from_json(object);
	}
	else if (g_strcmp0(proto, "x2go") == 0 || g_strcmp0(proto, "X2go") == 0 || g_strcmp0(proto, "X2Go") == 0 || g_strcmp0(proto, "X2GO") == 0 || g_strcmp0(proto, "x2GO") == 0 || g_strcmp0(proto, "x2gO") == 0) {
		newserver = x2go_server_new_from_json(object);
	}

	return newserver;
}
Example #12
0
static gboolean
router_rule_match (RouterRule *rule,
                   JsonObject *object)
{
  RouterMatch *match;
  const gchar *value;
  JsonNode *node;
  guint i;

  for (i = 0; rule->matches && rule->matches[i].name != NULL; i++)
    {
      match = &rule->matches[i];
      if (match->glob)
        {
          if (!cockpit_json_get_string (object, match->name, NULL, &value) || !value ||
              !g_pattern_match (match->glob, strlen (value), value, NULL))
            return FALSE;
        }
      else if (match->node)
        {
          node = json_object_get_member (object, match->name);
          if (!node || !cockpit_json_equal (match->node, node))
            return FALSE;
        }
      else
        {
          if (!json_object_has_member (object, match->name))
            return FALSE;
        }
    }

  return TRUE;
}
Example #13
0
/*
 * cockpit_channel_fail:
 * @self: a channel
 * @problem: the problem
 *
 * Close the channel with a @problem. In addition a "message" field
 * will be set on the channel, using the @format argument to bulid
 * the message. The message will also be logged.
 *
 * See cockpit_channel_close() for further info.
 */
void
cockpit_channel_fail (CockpitChannel *self,
                      const gchar *problem,
                      const gchar *format,
                      ...)
{
  JsonObject *options;
  gchar *message;
  va_list va;

  g_return_if_fail (problem != NULL);
  g_return_if_fail (COCKPIT_IS_CHANNEL (self));

  va_start (va, format);
  message = g_strdup_vprintf (format, va);
  va_end (va);

  options = cockpit_channel_close_options (self);
  if (!json_object_has_member (options, "message"))
    json_object_set_string_member (options, "message", message);
  g_message ("%s: %s", self->priv->id, message);
  g_free (message);

  cockpit_channel_close (self, problem);
}
Example #14
0
gint64 torrent_get_queue_position(JsonObject * args)
{
    if (json_object_has_member(args, FIELD_QUEUE_POSITION))
        return json_object_get_int_member(args, FIELD_QUEUE_POSITION);
    else
        return -1;
}
Example #15
0
JsonArray *get_torrents_removed(JsonObject * response)
{
    if (G_UNLIKELY(json_object_has_member(response, FIELD_REMOVED)))
        return json_object_get_array_member(response, FIELD_REMOVED);
    else
        return NULL;
}
Example #16
0
gint64 torrent_get_error(JsonObject * t)
{
    if (!json_object_has_member(t, FIELD_ERROR))
        return 0;
    else
        return json_object_get_int_member(t, FIELD_ERROR);
}
Example #17
0
/**
 * Returns a cometd_advice pointer that should be free'd by the caller.
 * Returns NULL if advice cannot be found.
 *
 * See also: http://svn.cometd.com/trunk/bayeux/bayeux.html#toc_32
 */
cometd_advice*
cometd_msg_advice(JsonNode* node)
{
    g_return_val_if_fail(JSON_NODE_HOLDS_OBJECT (node), NULL);

    JsonObject* obj = json_node_get_object(node);
    cometd_advice* advice = NULL;
    JsonObject* advice_obj = NULL;

    if (json_object_has_member(obj, COMETD_MSG_ADVICE_FIELD))
        advice_obj = json_object_get_object_member(obj, COMETD_MSG_ADVICE_FIELD);

    if (!advice_obj)
        return NULL;

    const char* reconnect = json_object_get_string_member(advice_obj,
                            "reconnect");
    const guint64 interval = json_object_get_int_member(advice_obj, "interval");

    if (reconnect || interval)
    {
        advice = cometd_advice_new();
        advice->interval = interval;

        if (strcmp("none", reconnect) == 0) {
            advice->reconnect = COMETD_RECONNECT_NONE;
        } else if (strcmp("handshake", reconnect) == 0) {
            advice->reconnect = COMETD_RECONNECT_HANDSHAKE;
        } else if (strcmp("retry", reconnect) == 0) {
            advice->reconnect = COMETD_RECONNECT_RETRY;
        }
    }

    return advice;
}
Example #18
0
static gboolean
catch_space_load_from_json (CatchResource  *resource,
                             JsonNode       *node,
                             GError        **error)
{
   CatchSpace *space = (CatchSpace *)resource;
   JsonObject *obj;

   ENTRY;

   g_return_val_if_fail(CATCH_IS_SPACE(space), FALSE);
   g_return_val_if_fail(node != NULL, FALSE);

   if (CATCH_RESOURCE_CLASS(catch_space_parent_class)->load_from_json) {
      if (!CATCH_RESOURCE_CLASS(catch_space_parent_class)->
          load_from_json(resource, node, error)) {
         RETURN(FALSE);
      }
   }

   if (JSON_NODE_HOLDS_OBJECT(node) &&
       (obj = json_node_get_object(node))) {
      if (json_object_has_member(obj, "name") &&
          JSON_NODE_HOLDS_VALUE(json_object_get_member(obj, "name"))) {
         catch_space_set_name(CATCH_SPACE(resource),
                               json_object_get_string_member(obj, "name"));
      }
   }

   RETURN(TRUE);
}
Example #19
0
File: json.c Project: GNOME/gegl
static guint
install_properties(JsonOpClass *json_op_class)
{
    GObjectClass *object_class = G_OBJECT_CLASS (json_op_class);
    JsonObject *root = json_op_class->json_root;
    guint prop = 1;

    // Exported ports
    if (json_object_has_member(root, "inports")) {
        JsonObject *inports = json_object_get_object_member(root, "inports");
        GList *inport_names = json_object_get_members(inports);
        GList *l;
        for (l = inport_names; l != NULL; l = l->next) {
            const gchar *name = l->data;
            JsonObject *conn = json_object_get_object_member(inports, name);
            const gchar *proc = json_object_get_string_member(conn, "process");
            const gchar *port = json_object_get_string_member(conn, "port");
            JsonObject *processes = json_object_get_object_member(root, "processes");
            JsonObject *p = json_object_get_object_member(processes, proc);
            const gchar *component = json_object_get_string_member(p, "component");

            {
              GParamSpec *target_spec = NULL;
              gchar *opname = component2geglop(component);
              // HACK: should avoid instantiating node to determine prop
              GeglNode *n = gegl_node_new();
              g_assert(n);
              gegl_node_set(n, "operation", opname, NULL);
              target_spec = gegl_node_find_property(n, port);
              if (target_spec) {
                GParamSpec *spec = copy_param_spec(target_spec, name);
                PropertyTarget *t = property_target_new(g_strdup(proc), g_strdup(port));
                g_hash_table_insert(json_op_class->properties, GINT_TO_POINTER(prop), t);
                g_object_class_install_property (object_class, prop, spec);
                prop++;
              }
              g_object_unref(n);
              g_free(opname);
            }
        }

        g_list_free(inport_names);
    }

/*
    if (json_object_has_member(root, "outports")) {
        JsonObject *outports = json_object_get_object_member(root, "outports");
        GList *outport_names = json_object_get_members(outports);
        for (int i=0; i<g_list_length(outport_names); i++) {
            const gchar *name = g_list_nth_data(outport_names, i);
            JsonObject *conn = json_object_get_object_member(outports, name);
            const gchar *proc = json_object_get_string_member(conn, "process");
            const gchar *port = json_object_get_string_member(conn, "port");
            graph_add_port(self, GraphOutPort, name, proc, port);
        }
    }
*/
  return prop-1;
}
static gboolean
ipcam_event_input_msg_handler_update_param(IpcamEventInputMsgHandler *handler, const gchar *name, JsonObject *value_obj)
{
    IpcamIConfig *iconfig;
    g_object_get(G_OBJECT(handler), "app", &iconfig, NULL);
    GList *members, *item;
    Schedules *sche = g_new(Schedules, 1);
    GVariant *value = NULL;
    gboolean ret = FALSE;

    members = json_object_get_members(value_obj);
    for (item = g_list_first(members); item; item = g_list_next(item))
    {
        const gchar *sub_name = item->data;
        if (g_str_equal(sub_name, "enable"))
        {
            value = g_variant_new_boolean(json_object_get_boolean_member(value_obj, sub_name));
        }
        else if (g_str_equal(sub_name, "schedules"))
        {
            gint i = 0;
            JsonObject *sub_obj = json_object_get_object_member(value_obj, sub_name);
            for (i = ENUM_MON; i < ENUM_WEEKDAY_LAST; i++)
            {
                if (json_object_has_member(sub_obj, weekday_name[i]))
                {
                    sche->schedule[i] = (gchar *)json_object_get_string_member(sub_obj, weekday_name[i]);
                }
                else
                {
                    sche->schedule[i] = g_malloc0(1);
                }
            }
            if (IS_64BIT_MACHINE)
            {
                value = g_variant_new_uint64(GPOINTER_TO_SIZE(sche));
            }
            else
            {
                value = g_variant_new_uint32(GPOINTER_TO_SIZE(sche));
            }
        }
        else
        {
            g_warn_if_reached();
        }

        if (value)
        {
            ret = ipcam_iconfig_update(iconfig, IPCAM_EVENT_INPUT_TYPE, name, sub_name, value);
            g_variant_unref(value);
            value = NULL;
        }
    }
    g_free(sche);
    g_list_free(members);

    return ret;
}
Example #21
0
static guint
json_array_size (JsonObject *object, const char *name)
{
  if (!json_object_has_member (object, name))
    return 0;

  return json_array_get_length (json_object_get_array_member (object, name));
}
Example #22
0
/* TODO: We might want to put this into a utils.c later */
static gboolean
usable_json_value (JsonObject *object, const char *name)
{
  if (!json_object_has_member (object, name))
    return FALSE;

  return !json_object_get_null_member (object, name);
}
/**
 * couchdb_struct_field_has_field:
 * @sf: A #CouchdbStructField object
 * @field: Name of the field to check
 *
 * Check whether a given field exists in the given #CouchdbStructField object.
 *
 * Return value: TRUE if the field exists, FALSE if not.
 */
gboolean
couchdb_struct_field_has_field (CouchdbStructField *sf, const char *field)
{
	g_return_val_if_fail (sf != NULL, FALSE);
	g_return_val_if_fail (field != NULL, FALSE);

	return json_object_has_member (sf->json_object, field);
}
static void
pb_got_phone_threads(PushBulletAccount *pba, JsonNode *node, gpointer user_data)
{
	PurpleAccount *account = pba->account;
	JsonObject *rootobj = json_node_get_object(node);
	JsonObject *data = json_object_get_object_member(rootobj, "data");
	JsonArray *threads = json_object_get_array_member(data, "threads");
	gint i;
	guint len;
	gchar *device = user_data;
	gint last_message_timestamp = purple_account_get_int(account, "last_message_timestamp", 0);
	gint newest_phone_message_id = purple_account_get_int(account, "newest_phone_message_id", 0);
	
	for(i = 0, len = json_array_get_length(threads); i < len; i++)
	{
		JsonObject *thread = json_array_get_object_element(threads, i);
		const gchar *id = json_object_get_string_member(thread, "id");
		JsonArray *recipients = json_object_get_array_member(thread, "recipients");
		const gchar *from = NULL;
		
		if (json_array_get_length(recipients) > 0) {
			JsonObject *first_recipient = json_array_get_object_element(recipients, 0);
			from = json_object_get_string_member(first_recipient, "number");
			
			if (json_object_has_member(first_recipient, "thumbnail")) {
				pb_set_base64_icon_for_buddy(json_object_get_string_member(first_recipient, "thumbnail"), purple_find_buddy(account, from));
			}
		}
		if (from == NULL) {
			continue;
		}
		if (json_object_has_member(thread, "latest"))
		{
			JsonObject *latest = json_object_get_object_member(thread, "latest");
			gint64 timestamp = json_object_get_int_member(latest, "timestamp");
			gint msgid = atoi(json_object_get_string_member(latest, "id"));
			
			if (timestamp > last_message_timestamp || msgid > newest_phone_message_id) {
				pb_get_phone_thread_by_id(pba, device, id, from);
			}
		}
		
	}
	
	g_free(device);
}
static void
got_token_cb (SoupSession *session, SoupMessage *msg, gpointer user_data)
{
    /* parses the authentication token from the response
     */
    RBAudioscrobblerAccount *account;
    JsonParser *parser;

    account = RB_AUDIOSCROBBLER_ACCOUNT (user_data);

    parser = json_parser_new ();

    if (msg->response_body->data != NULL &&
            json_parser_load_from_data (parser, msg->response_body->data, msg->response_body->length, NULL)) {
        JsonObject *root_object;

        root_object = json_node_get_object (json_parser_get_root (parser));
        if (json_object_has_member (root_object, "token")) {
            char *url;

            account->priv->auth_token = g_strdup (json_object_get_string_member (root_object, "token"));
            rb_debug ("granted auth token \"%s\"", account->priv->auth_token);

            /* send the user to the web page using the token */
            url = g_strdup_printf ("%s?api_key=%s&token=%s",
                                   rb_audioscrobbler_service_get_auth_url (account->priv->service),
                                   rb_audioscrobbler_service_get_api_key (account->priv->service),
                                   account->priv->auth_token);
            rb_debug ("sending user to %s", url);
            gtk_show_uri (NULL, url, GDK_CURRENT_TIME, NULL);

            /* add timeout which will ask for session key */
            account->priv->session_key_timeout_id =
                g_timeout_add_seconds (SESSION_KEY_REQUEST_TIMEOUT,
                                       request_session_key_timeout_cb,
                                       account);

            g_free (url);
        } else {
            rb_debug ("error retrieving auth token: %s",
                      json_object_get_string_member (root_object, "message"));

            /* go back to being logged out */
            rb_audioscrobbler_account_logout (account);
        }
    } else {
        /* treat as connection error */
        rb_debug ("empty or invalid response retrieving auth token. treating as connection error");

        cancel_session (account);

        account->priv->login_status = RB_AUDIOSCROBBLER_ACCOUNT_LOGIN_STATUS_CONNECTION_ERROR;
        g_signal_emit (account, rb_audioscrobbler_account_signals[LOGIN_STATUS_CHANGED],
                       0, account->priv->login_status);
    }

    g_object_unref (parser);
}
Example #26
0
static int
json_object_get_member_size (JsonObject *obj,
                             const char *member_name)
{
  if (!obj || !json_object_has_member (obj, member_name))
    return 0;

  return (int)json_array_get_length (json_object_get_array_member (obj, member_name));
}
void trg_prefs_load(TrgPrefs * p)
{
    TrgPrefsPrivate *priv = p->priv;
    JsonParser *parser = json_parser_new();
    JsonNode *root;
    guint n_profiles;
    JsonArray *profiles;

    gboolean parsed = json_parser_load_from_file(parser, priv->file, NULL);

    if (!parsed) {
        trg_prefs_empty_init(p);
        g_object_unref(parser);
        return;
    }

    root = json_parser_get_root(parser);
    if (root) {
        priv->user = json_node_copy(root);
        priv->userObj = json_node_get_object(priv->user);
    }

    g_object_unref(parser);

    if (!root) {
        trg_prefs_empty_init(p);
        return;
    }

    if (!json_object_has_member(priv->userObj, TRG_PREFS_KEY_PROFILES)) {
        profiles = json_array_new();
        json_object_set_array_member(priv->userObj, TRG_PREFS_KEY_PROFILES,
                                     profiles);
    } else {
        profiles = json_object_get_array_member(priv->userObj,
                                                TRG_PREFS_KEY_PROFILES);
    }

    n_profiles = json_array_get_length(profiles);

    if (n_profiles < 1) {
        priv->profile = trg_prefs_new_profile_object();
        json_array_add_object_element(profiles, priv->profile);
        trg_prefs_set_int(p, TRG_PREFS_KEY_PROFILE_ID, 0,
                          TRG_PREFS_GLOBAL);
    } else {
        gint profile_id = trg_prefs_get_int(p, TRG_PREFS_KEY_PROFILE_ID,
                                            TRG_PREFS_GLOBAL);
        if (profile_id >= n_profiles)
            trg_prefs_set_int(p, TRG_PREFS_KEY_PROFILE_ID, profile_id = 0,
                              TRG_PREFS_GLOBAL);

        priv->profile =
            json_array_get_object_element(profiles, profile_id);
    }
}
Example #28
0
static void onTaskReadyCallback(GObject * source, GAsyncResult * res,
                                gpointer userData)
{
    GError *err = NULL;
    //WlDictQuery *query=WL_DICT_QUERY(source);
    TaskData *td = g_task_get_task_data(G_TASK(res));
    gchar *responseBody = g_task_propagate_pointer(G_TASK(res), &err);
    if (err) {                  /* Error */
        if (td->cb)
            td->cb(td->from, td->to, td->src, NULL, td->cbData, err);
        return;
    }

    JsonParser *parser = json_parser_new();
    if (!json_parser_load_from_data(parser, responseBody, -1, &err)) {
        if (td->cb)
            td->cb(td->from, td->to, td->src, NULL, td->cbData, err);
        g_message("%s", responseBody);
        return;
    }
    JsonNode *rootNode = json_parser_get_root(parser);
    JsonObject *rootObj = json_node_get_object(rootNode);
    const gchar *from = json_object_get_string_member(rootObj, "from");
    const gchar *to = json_object_get_string_member(rootObj, "to");

    if (json_object_has_member(rootObj, "error_code")) {
        /* 查询出错 */
        const gchar *error_msg =
            json_object_get_string_member(rootObj, "error_msg");
        const gchar *error_code =
            json_object_get_string_member(rootObj, "error_code");
        if (td->cb) {
            GError *error =
                g_error_new(G_IO_ERROR, atoi(error_code), "%s", error_msg);
            td->cb(wl_dict_lang_get_enum(from), wl_dict_lang_get_enum(to),
                   json_object_get_string_member(rootObj, "query"), NULL,
                   td->cbData, error);
            g_error_free(error);
        }
        g_object_unref(parser);
        return;
    }

    JsonArray *results =
        json_object_get_array_member(rootObj, "trans_result");
    gint i, len = json_array_get_length(results);
    for (i = 0; i < len; i++) {
        JsonObject *resEle = json_array_get_object_element(results, i);
        const gchar *src = json_object_get_string_member(resEle, "src");
        const gchar *dst = json_object_get_string_member(resEle, "dst");
        if (td->cb)
            td->cb(wl_dict_lang_get_enum(from),
                   wl_dict_lang_get_enum(to), src, dst, td->cbData, NULL);
    }
    g_object_unref(parser);
}
void trg_tree_view_setup_columns(TrgTreeView * tv)
{
    TrgTreeViewPrivate *priv = TRG_TREE_VIEW_GET_PRIVATE(tv);
    JsonObject *props = trg_prefs_get_tree_view_props(tv);
    GList *columns, *widths, *cli, *wli;

    if (!json_object_has_member(props, TRG_PREFS_KEY_TV_COLUMNS)
        || !json_object_has_member(props, TRG_PREFS_KEY_TV_WIDTHS)) {
        GList *li;
        for (li = priv->columns; li; li = g_list_next(li)) {
            trg_column_description *desc =
                (trg_column_description *) li->data;
            if (desc && !(desc->flags & TRG_COLUMN_EXTRA))
                trg_tree_view_add_column(tv, desc, -1);
        }
        return;
    }

    columns =
        json_array_get_elements(json_object_get_array_member
                                (props, TRG_PREFS_KEY_TV_COLUMNS));
    widths =
        json_array_get_elements(json_object_get_array_member
                                (props, TRG_PREFS_KEY_TV_WIDTHS));

    for (cli = columns, wli = widths; cli && wli;
         cli = g_list_next(cli), wli = g_list_next(wli)) {
        trg_column_description *desc = trg_tree_view_find_column(tv,
                                                                 json_node_get_string
                                                                 ((JsonNode
                                                                   *)
                                                                  cli->
                                                                  data));
        if (desc) {
            gint64 width = json_node_get_int((JsonNode *) wli->data);
            trg_tree_view_add_column(tv, desc, width);
        }
    }

    g_list_free(columns);
    g_list_free(widths);
}
Example #30
0
/**
 * Returns true if the JsonNode is an object and has a member
 * with the `data` attribute.
 */
gboolean
cometd_msg_has_data(JsonNode* node)
{
    g_return_val_if_fail(JSON_NODE_HOLDS_OBJECT (node), FALSE);

    gboolean ret;
    JsonObject* obj = json_node_get_object(node);
    ret = json_object_has_member(obj, COMETD_MSG_DATA_FIELD);

    return ret;
}