Example #1
0
static void
kms_webrtc_session_parse_turn_url (KmsWebrtcSession * self)
{
  GRegex *regex;
  GMatchInfo *match_info = NULL;

  g_free (self->turn_user);
  self->turn_user = NULL;
  g_free (self->turn_password);
  self->turn_password = NULL;
  g_free (self->turn_address);
  self->turn_address = NULL;

  if ((self->turn_url == NULL)
      || (g_strcmp0 ("", self->turn_url) == 0)) {
    GST_INFO_OBJECT (self, "TURN server info cleared");
    return;
  }

  regex =
      g_regex_new
      ("^(?<user>.+):(?<password>.+)@(?<address>[0-9.]+):(?<port>[0-9]+)(\\?transport=(?<transport>(udp|tcp|tls)))?$",
      0, 0, NULL);
  g_regex_match (regex, self->turn_url, 0, &match_info);
  g_regex_unref (regex);

  if (g_match_info_matches (match_info)) {
    gchar *port_str;
    gchar *turn_transport;

    self->turn_user = g_match_info_fetch_named (match_info, "user");
    self->turn_password = g_match_info_fetch_named (match_info, "password");
    self->turn_address = g_match_info_fetch_named (match_info, "address");

    port_str = g_match_info_fetch_named (match_info, "port");
    self->turn_port = g_ascii_strtoll (port_str, NULL, 10);
    g_free (port_str);

    self->turn_transport = TURN_PROTOCOL_UDP;   /* default */
    turn_transport = g_match_info_fetch_named (match_info, "transport");
    if (turn_transport != NULL) {
      if (g_strcmp0 ("tcp", turn_transport) == 0) {
        self->turn_transport = TURN_PROTOCOL_TCP;
      } else if (g_strcmp0 ("tls", turn_transport) == 0) {
        self->turn_transport = TURN_PROTOCOL_TLS;
      }
      g_free (turn_transport);
    }

    GST_INFO_OBJECT (self, "TURN server info set (%s)", self->turn_url);
  } else {
    GST_ELEMENT_ERROR (self, RESOURCE, SETTINGS,
        ("URL '%s' not allowed. It must have this format: 'user:password@address:port(?transport=[udp|tcp|tls])'",
            self->turn_url),
        ("URL '%s' not allowed. It must have this format: 'user:password@address:port(?transport=[udp|tcp|tls])'",
            self->turn_url));
  }

  g_match_info_free (match_info);
}
Example #2
0
/**
 * gstreamill_get_job:
 * @uri: (in): access uri, e.g. /live/test/encoder/0
 *
 * Get the Job by access uri.
 *
 * Returns: job
 */
Job *gstreamill_get_job (Gstreamill *gstreamill, gchar *uri)
{
        Job *job = NULL;
        GRegex *regex;
        GMatchInfo *match_info;
        gchar *name = NULL;

        regex = g_regex_new ("^/(live|dvr)/(?<name>[^/]*)/.*", G_REGEX_OPTIMIZE, 0, NULL);
        match_info = NULL;
        g_regex_match (regex, uri, 0, &match_info);
        g_regex_unref (regex);
        if (g_match_info_matches (match_info)) {
                name = g_match_info_fetch_named (match_info, "name");
        }

        if (name != NULL) {
                job = get_job (gstreamill, name);
                g_free (name);
        }
        if (match_info != NULL) {
                g_match_info_free (match_info);
        }

        return job;
}
Example #3
0
void
hook (GMatchInfo *minfo, gpointer user_data)
{
    GString *str = (GString *)user_data;

    g_string_append_printf (str, "FROM THE HOOK<br/><br/>\n");

    while (g_match_info_matches (minfo))
    {
        guint n = g_match_info_get_match_count (minfo);
        g_string_append_printf (str, "Match count: %d<br/><br/>\n", n);
        gchar *word = g_match_info_fetch (minfo, 0);
        g_string_append_printf (str, "Found: %s<br/><br/>\n", word);
        g_free (word);

        guint i;
        for (i = 1; i < n; i++)
        {
            gchar *word = g_match_info_fetch (minfo, i);
            g_string_append_printf (str, "sub %d: %s<br/><br/>\n", i, word);
            g_free (word);
        }

        if (n > 1)
        {
            word = g_match_info_fetch_named (minfo, "controller");
            g_string_append_printf (str, "sub named controller: %s<br/><br/>\n", word);
            g_free (word);
        }

        g_match_info_next (minfo, NULL);
    }
}
static VALUE
rg_fetch(VALUE self, VALUE rb_match_reference)
{
    gchar *match;

    switch (TYPE(rb_match_reference)) {
      case RUBY_T_FIXNUM:
        {
            gint match_num;
            match_num = NUM2INT(rb_match_reference);
            match = g_match_info_fetch(_SELF(self), match_num);
        }
        break;
      case RUBY_T_STRING:
      case RUBY_T_SYMBOL:
        {
            const gchar *match_name;
            match_name = RVAL2CSTR_ACCEPT_SYMBOL(rb_match_reference);
            match = g_match_info_fetch_named(_SELF(self), match_name);
        }
        break;
      default:
        rb_raise(rb_eArgError, "Expected a String, a Symbol or an Integer");
        break;
    }

    return CSTR2RVAL_FREE(match);
}
Example #5
0
static gboolean is_http_progress_play_url (RequestData *request_data)
{
        GRegex *regex = NULL;
        GMatchInfo *match_info = NULL;
        gchar *e;
        gint index;

        if (request_data->parameters[0] != '\0') {
                GST_WARNING ("parameters is needless : %s?%s", request_data->uri, request_data->parameters);
                return FALSE;
        }

        index = -1;
        regex = g_regex_new ("^/live/.*/encoder/(?<encoder>[0-9]+)$", G_REGEX_OPTIMIZE, 0, NULL);
        g_regex_match (regex, request_data->uri, 0, &match_info);
        if (g_match_info_matches (match_info)) {
                e = g_match_info_fetch_named (match_info, "encoder");
                index = g_ascii_strtoll (e, NULL, 10);
                g_free (e);
        }
        if (match_info != NULL) {
                g_match_info_free (match_info);
        }
        if (regex != NULL) {
                g_regex_unref (regex);
        }
        if (index == -1) {
                GST_DEBUG ("not http progress play uri: %s", request_data->uri);
                return FALSE;
        }

        return TRUE;
}
Example #6
0
static gint encoder_extract_streams (Encoder *encoder, gchar **bins)
{
        GRegex *regex;
        GMatchInfo *match_info;
        EncoderStream *stream;
        gchar *bin, **p;

        p = bins;
        while (*p != NULL) {
                bin = *p;
                regex = g_regex_new ("appsrc *name=(?<name>[^ ]*)", G_REGEX_OPTIMIZE, 0, NULL);
                g_regex_match (regex, bin, 0, &match_info);
                g_regex_unref (regex);
                if (g_match_info_matches (match_info)) {
                        stream = (EncoderStream *)g_malloc (sizeof (EncoderStream));
                        stream->name = g_match_info_fetch_named (match_info, "name");
                        g_match_info_free (match_info);
                        g_array_append_val (encoder->streams, stream);
                        GST_INFO ("encoder stream %s found %s", stream->name, bin);

                } else if (g_str_has_prefix (bin, "appsrc")) {
                        GST_ERROR ("appsrc name property must be set");
                        return 1;
                }
                p++;
        }

        return 0;
}
Example #7
0
static gint encoder_extract_streams (Encoder *encoder, gchar **bins)
{
    GRegex *regex;
    GMatchInfo *match_info;
    EncoderStream *stream, *segment_reference_stream = NULL;
    gchar *bin, **p;

    p = bins;
    while (*p != NULL) {
        bin = *p;
        regex = g_regex_new ("appsrc *name=(?<name>[^ ]*)", G_REGEX_OPTIMIZE, 0, NULL);
        g_regex_match (regex, bin, 0, &match_info);
        g_regex_unref (regex);
        if (g_match_info_matches (match_info)) {
            stream = (EncoderStream *)g_malloc (sizeof (EncoderStream));
            stream->name = g_match_info_fetch_named (match_info, "name");
            g_match_info_free (match_info);
            g_array_append_val (encoder->streams, stream);
            stream->is_segment_reference = FALSE;
            if (g_str_has_prefix (stream->name, "video") && strstr (bin, "x264enc") != NULL) {
                /* with video encoder */
                encoder->has_video = TRUE;
                if (!encoder->has_tssegment) {
                    segment_reference_stream = stream;
                    encoder->has_audio_only = FALSE;
                }
            }
            GST_INFO ("encoder stream %s found %s", stream->name, bin);

            if (g_str_has_prefix (stream->name, "audio")) {
                if (!(encoder->has_tssegment || encoder->has_video)) {
                    encoder->has_audio_only = TRUE;
                    segment_reference_stream = stream;
                }
            }

        } else if (g_str_has_prefix (bin, "appsrc")) {
            GST_ERROR ("appsrc name property must be set");
            return 1;
        }

        if (strstr (bin, "tssegment") != NULL) {
            /* has tssegment element */
            encoder->has_tssegment = TRUE;
            encoder->has_video = FALSE;
            encoder->has_audio_only = FALSE;
            segment_reference_stream = NULL;
        }
        p++;
    }

    if (segment_reference_stream != NULL) {
        segment_reference_stream->is_segment_reference = TRUE;
    }

    return 0;
}
Example #8
0
int ckpmon_run(char *arg)
{
	extern lua_State *L;

	gchar *pmon_input = NULL;
	char *pmon_buf = NULL;
	gsize length = 0;
	GRegex *regex;
	GMatchInfo *match_info;
	GError *err = NULL;

	printPrompt("PMON版本输入格式如下例:\"1.3.6\"\n请输入\n");

	// get pmon spec version: pmon_input
	int len = getTableNumElement(L, "con", "PMONVER_LEN");
	pmon_input = getNCharsPrompt("PMON版本条码", len, TRUE);

	if (pmon_input == NULL) {
		printPrompt("未输入\n");
		return 1;
	}

	printPrompt("输入版本号为:");
	printMsg(pmon_input);
	printMsg("\n");

	// get pmon env version: pmon_env
	g_file_get_contents ("/proc/cmdline", &pmon_buf, &length, NULL);

	regex = g_regex_new (PMON_STR,
				G_REGEX_NO_AUTO_CAPTURE | G_REGEX_OPTIMIZE | G_REGEX_DUPNAMES,
				0, &err);

	g_regex_match (regex, pmon_buf, 0, &match_info);
	gchar *pmon_named = g_match_info_fetch_named(match_info, "pmonver");
	g_print ("%s\n", pmon_named);

	// cmp
	gchar *text_pmon_env = g_strdup_printf("本机的版本号[cmdline]为:%s\n", pmon_named);
	printPrompt(g_string_chunk_insert_const(text_chunk, text_pmon_env));
	g_free(text_pmon_env);

	if (strcasecmp(pmon_input, (const char *)pmon_named)) {
		printNG("机器当前PMON版本号与标准不相符!\n");
		return 1;
	} else {
		printOK("PMON版本号相符。\n");
	}

	g_free(pmon_input);	// TODO: here free g_strdup, but have not test
	g_free (pmon_named);
	g_match_info_free (match_info);
	g_regex_unref (regex);

	return 0;
}
Example #9
0
static bool check_file_parse_line(const char * const line,
	enum hash_func_e *id, char **filename, char **digest)
{
	GMatchInfo *info = NULL;

	if (check_regex_match(line, &info) != CHECK_FORMAT_UNKNOWN) {
		char *function = g_match_info_fetch_named(info, "FUNCTION");
		if (function) {
			*id = gtkhash_hash_func_get_id_from_name(function);
			g_free(function);
		}

		*filename = g_match_info_fetch_named(info, "FILENAME");
		*digest = g_match_info_fetch_named(info, "DIGEST");

		g_match_info_free(info);
		return true;
	} else {
		g_match_info_free(info);
		return false;
	}
}
Example #10
0
// Returns true iff first_line valid. If true, populates method with the parsed
// method and path with the parsed path. If no path is found, then path is
// populated with the empty string.
bool matchFirstLine(char *first_line, GString *method, GString *path)
{
	GRegex *regex = g_regex_new(REQUEST_FIRST_LINE_REGEX, 0, 0, NULL);
	GMatchInfo *match_info;

	bool matched = g_regex_match(regex, first_line, 0, &match_info);
	if (matched) {
		char *matched_method = g_match_info_fetch_named(match_info, "METHOD");
		g_string_assign(method, matched_method);
		free(matched_method);

		char *matched_path = g_match_info_fetch_named(match_info, "PATH");
		if (matched_path == NULL) {
			g_string_assign(path, "");
		} else {
			g_string_assign(path, matched_path);
		}
		free(matched_path);
	}

	g_match_info_free(match_info);
	g_regex_unref(regex);
	return matched;
}
Example #11
0
static Encoder *
get_encoder (gchar *uri, GArray *channels)
{
        GRegex *regex = NULL;
        GMatchInfo *match_info = NULL;
        gchar *c, *e;
        Channel *channel;
        Encoder *encoder = NULL;

        regex = g_regex_new ("^/channel/(?<channel>[0-9]+)/encoder/(?<encoder>[0-9]+).*", G_REGEX_OPTIMIZE, 0, NULL);
        g_regex_match (regex, uri, 0, &match_info);
        if (g_match_info_matches (match_info)) {
                c = g_match_info_fetch_named (match_info, "channel");
                if (atoi (c) < channels->len) {
                        channel = g_array_index (channels, gpointer, atoi (c));
                        e = g_match_info_fetch_named (match_info, "encoder");
                        if (atoi (e) < channel->encoder_array->len) {
                                GST_DEBUG ("http get request, channel is %s, encoder is %s", c, e);
                                encoder = g_array_index (channel->encoder_array, gpointer, atoi (e));
                        } else {
                                GST_ERROR ("Out range encoder %s, len is %d.", e, channel->encoder_array->len);
                        }
                        g_free (e);
                } else {
                        GST_ERROR ("Out range channel %s.", c);
                }
                g_free (c);
        }

        if (match_info != NULL)
                g_match_info_free (match_info);
        if (regex != NULL)
                g_regex_unref (regex);

        return encoder;
}
Example #12
0
/**
 * gstreamill_get_encoder_output:
 * @uri: (in): access uri, e.g. /live/test/encoder/0
 *
 * Get the EncoderOutput by access uri.
 *
 * Returns: the encoder output
 */
EncoderOutput * gstreamill_get_encoder_output (Gstreamill *gstreamill, gchar *uri)
{
        Job *job;
        guint index;
        GRegex *regex = NULL;
        GMatchInfo *match_info = NULL;
        gchar *e;

        index = -1;
        regex = g_regex_new ("^/(live|dvr)/.*/encoder/(?<encoder>[0-9]+).*", G_REGEX_OPTIMIZE, 0, NULL);
        g_regex_match (regex, uri, 0, &match_info);
        if (g_match_info_matches (match_info)) {
                e = g_match_info_fetch_named (match_info, "encoder");
                index = g_ascii_strtoll (e, NULL, 10);
                g_free (e);
        }
        if (match_info != NULL) {
                g_match_info_free (match_info);
        }
        if (regex != NULL) {
                g_regex_unref (regex);
        }
        if (index == -1) {
                GST_INFO ("Not a encoder uri: %s", uri);
                return NULL;
        }
        job = gstreamill_get_job (gstreamill, uri);
        if (job == NULL) {
                GST_ERROR ("Job %s not found.", uri);
                return NULL;
        }
        if (*(job->output->state) != JOB_STATE_PLAYING) {
                GST_ERROR ("FATAL: Job %s state is not playing", job->name);
                return NULL;
        }
        if (index >= job->output->encoder_count) {
                GST_ERROR ("Encoder %s not found.", uri);
                return NULL;
        }
        g_mutex_lock (&(job->access_mutex));
        job->current_access += 1;
        g_mutex_unlock (&(job->access_mutex));

        return &job->output->encoders[index];
}
Example #13
0
static gboolean
replace_start_regex (const GMatchInfo *match_info,
		     GString          *expanded_regex,
		     gpointer          user_data)
{
	gchar *num_string, *subst, *subst_escaped, *escapes;
	gint num;
	struct RegexResolveData *data = user_data;

	escapes = g_match_info_fetch (match_info, 1);
	num_string = g_match_info_fetch (match_info, 2);
	num = _gtk_source_string_to_int (num_string);

	if (num < 0)
	{
		subst = g_match_info_fetch_named (data->start_regex->u.regex.match,
						  num_string);
	}
	else
	{
		subst = g_match_info_fetch (data->start_regex->u.regex.match,
					    num);
	}

	if (subst != NULL)
	{
		subst_escaped = g_regex_escape_string (subst, -1);
	}
	else
	{
		g_warning ("Invalid group: %s", num_string);
		subst_escaped = g_strdup ("");
	}

	g_string_append (expanded_regex, escapes);
	g_string_append (expanded_regex, subst_escaped);

	g_free (escapes);
	g_free (num_string);
	g_free (subst);
	g_free (subst_escaped);

	return FALSE;
}
static gchar *
get_stream_id_from_padname (const gchar * name)
{
  GMatchInfo *match_info = NULL;
  GRegex *regex;
  gchar *id = NULL;

  if (name == NULL)
    return NULL;

  regex = g_regex_new ("^sink_(?<id>\\d+)", 0, 0, NULL);
  g_regex_match (regex, name, 0, &match_info);

  if (g_match_info_matches (match_info))
    id = g_match_info_fetch_named (match_info, "id");

  g_match_info_free (match_info);
  g_regex_unref (regex);

  return id;
}
Example #15
0
static gchar * stop_job (HTTPMgmt *httpmgmt, RequestData *request_data)
{
        gchar *buf, *p;
        GRegex *regex;
        GMatchInfo *match_info;

        if (request_data->method == HTTP_GET) {
                regex = g_regex_new ("/admin/stop/(?<name>.*)", G_REGEX_OPTIMIZE, 0, NULL);
                g_regex_match (regex, request_data->uri, 0, &match_info);
                g_regex_unref (regex);
                if (g_match_info_matches (match_info)) {
                        p = g_match_info_fetch_named (match_info, "name");
                        g_match_info_free (match_info);
                        buf = gstreamill_job_stop (httpmgmt->gstreamill, p);
                        g_free (p);
                        return buf;
                }
        }
        buf = g_strdup ("{\n    \"result\": \"failure\",\n    \"reason\": \"must be get request\"\n}");

        return buf;
}
Example #16
0
static gboolean
kms_ice_candidate_update_values (KmsIceCandidate * self)
{
  GRegex *regex;
  GMatchInfo *match_info;
  gchar *tmp = NULL;
  gboolean ret = FALSE;

  regex = g_regex_new (CANDIDATE_EXPR, 0, 0, NULL);
  g_regex_match (regex, self->priv->candidate, 0, &match_info);

  if (!g_match_info_matches (match_info)) {
    GST_WARNING_OBJECT (self, "Cannot parse from '%s'", self->priv->candidate);
    goto end;
  }

  g_free (self->priv->foundation);
  g_free (self->priv->ip);
  g_free (self->priv->related_addr);

  self->priv->ip = g_match_info_fetch_named (match_info, "addr");

  tmp = g_match_info_fetch_named (match_info, "port");
  self->priv->port = atoi (tmp);
  g_free (tmp);

  self->priv->foundation = g_match_info_fetch_named (match_info, "foundation");

  tmp = g_match_info_fetch_named (match_info, "priority");
  self->priv->priority = atoi (tmp);
  g_free (tmp);

  tmp = g_match_info_fetch_named (match_info, "transport");
  if (g_strcmp0 (tmp, "TCP") == 0 || g_strcmp0 (tmp, "tcp") == 0) {
    self->priv->protocol = KMS_ICE_PROTOCOL_TCP;
  } else if (g_strcmp0 (tmp, "UDP") == 0 || g_strcmp0 (tmp, "udp") == 0) {
    self->priv->protocol = KMS_ICE_PROTOCOL_UDP;
  } else {
    GST_ERROR_OBJECT (self, "Unsupported protocol %s", tmp);
    goto end;
  }

  g_free (tmp);

  tmp = g_match_info_fetch_named (match_info, "type");
  if (g_strcmp0 (tmp, "host") == 0) {
    self->priv->type = KMS_ICE_CANDIDATE_TYPE_HOST;
  } else if (g_strcmp0 (tmp, "srflx") == 0) {
    self->priv->type = KMS_ICE_CANDIDATE_TYPE_SRFLX;
  } else if (g_strcmp0 (tmp, "prflx") == 0) {
    self->priv->type = KMS_ICE_CANDIDATE_TYPE_PRFLX;
  } else if (g_strcmp0 (tmp, "relay") == 0) {
    self->priv->type = KMS_ICE_CANDIDATE_TYPE_RELAY;
  } else {
    GST_ERROR_OBJECT (self, "Unsupported ice candidate type %s", tmp);
    goto end;
  }

  g_free (tmp);

  tmp = g_match_info_fetch_named (match_info, "tcptype");
  if (g_strcmp0 (tmp, "active") == 0) {
    self->priv->tcp_type = KMS_ICE_TCP_CANDIDATE_TYPE_ACTIVE;
  } else if (g_strcmp0 (tmp, "passive") == 0) {
    self->priv->tcp_type = KMS_ICE_TCP_CANDIDATE_TYPE_PASSIVE;
  } else if (g_strcmp0 (tmp, "so") == 0) {
    self->priv->tcp_type = KMS_ICE_TCP_CANDIDATE_TYPE_SO;
  } else {
    self->priv->tcp_type = KMS_ICE_TCP_CANDIDATE_TYPE_NONE;
  }
  g_free (tmp);

  tmp = g_match_info_fetch_named (match_info, "raddr");
  if (tmp != NULL && g_strcmp0 (tmp, "") != 0) {
    self->priv->related_addr = tmp;
  } else {
    self->priv->related_addr = NULL;
    g_free (tmp);
  }

  tmp = g_match_info_fetch_named (match_info, "rport");
  if (tmp != NULL && g_strcmp0 (tmp, "") != 0) {
    self->priv->related_port = atoi (tmp);
  } else {
    self->priv->related_port = -1;
  }

  ret = TRUE;

end:
  g_free (tmp);

  g_match_info_free (match_info);
  g_regex_unref (regex);

  return ret;
}
static void
video_guess_values_from_display_name (const gchar *display_name,
                                      gchar      **title,
                                      gchar      **showname,
                                      GDateTime  **date,
                                      gint        *season,
                                      gint        *episode)
{
  gchar      *metadata;
  GRegex     *regex;
  GMatchInfo *info;

  metadata = video_display_name_to_metadata (display_name);

  regex = g_regex_new (MOVIE_REGEX, 0, 0, NULL);
  g_regex_match (regex, metadata, 0, &info);

  if (g_match_info_matches (info)) {
    if (title) {
      *title = g_match_info_fetch_named (info, "name");
      /* Replace "." with <space> */
      g_strdelimit (*title, ".", ' ');
      *title = g_strstrip (*title);
    }

    if (date) {
      gchar *year = g_match_info_fetch_named (info, "year");

      *date = g_date_time_new_utc (atoi (year), 1, 1, 0, 0, 0.0);
      g_free (year);
    }

    if (showname) {
      *showname = NULL;
    }

    if (season) {
      *season = 0;
    }

    if (episode) {
      *episode = 0;
    }

    g_regex_unref (regex);
    g_match_info_free (info);
    g_free (metadata);

    return;
  }

  g_regex_unref (regex);
  g_match_info_free (info);

  regex = g_regex_new (TV_REGEX, 0, 0, NULL);
  g_regex_match (regex, metadata, 0, &info);

  if (g_match_info_matches (info)) {
    if (title) {
      *title = g_match_info_fetch_named (info, "name");
      g_strdelimit (*title, ".()", ' ');
      *title = g_strstrip (*title);
      if (*title[0] == '\0') {
        g_free (*title);
        *title = NULL;
      }
    }

    if (showname) {
      *showname = g_match_info_fetch_named (info, "showname");
      g_strdelimit (*showname, ".", ' ');
      *showname = g_strstrip (*showname);
    }

    if (season) {
      gchar *s = g_match_info_fetch_named (info, "season");
      if (s) {
        if (*s == 's' || *s == 'S') {
          *season = atoi (s + 1);
        } else {
          *season = atoi (s);
        }
      } else {
        *season = 0;
      }

      g_free (s);
    }

    if (episode) {
      gchar *e = g_match_info_fetch_named (info, "episode");
      if (e) {
        if (g_ascii_strncasecmp (e, "ep", 2) == 0) {
          *episode = atoi (e + 2);
        } else if (*e == 'e' || *e == 'E' || *e == 'x' || *e == '.') {
          *episode = atoi (e + 1);
        } else {
          *episode = atoi (e);
        }
      } else {
        *episode = 0;
      }

      g_free (e);
    }

    if (date) {
      *date = NULL;
    }

    g_regex_unref (regex);
    g_match_info_free (info);
    g_free (metadata);

    return;
  }

  g_regex_unref (regex);
  g_match_info_free (info);

  /* The filename doesn't look like a movie or a TV show, just use the
     filename without extension as the title */
  if (title) {
    *title = g_strdelimit (metadata, ".", ' ');
  }

  if (showname) {
    *showname = NULL;
  }

  if (date) {
    *date = NULL;
  }

  if (season) {
    *season = 0;
  }

  if (episode) {
    *episode = 0;
  }
}
Example #18
0
int
nsp_feed_update_icon(NspFeed *feed)
{
	NspNetData *data;
	char *icon_url = NULL;
	char *icon_path = NULL;
	GRegex *regex;
	GMatchInfo *match_info;
	CURL *curl;
	CURLcode result;
	GdkPixbufLoader *loader = NULL;
	GError *error = NULL;
	char *feed_id_string = NULL;
	
	/* Download web page */
	data = nsp_net_new();
	if ( nsp_net_load_url(feed->site_url, data) ) {
		g_warning("ERROR: %s\n", data->error);
		nsp_net_free(data);
		return 1;
	}
	
	/* Find <link> tag reffering to the icon */
	regex = g_regex_new ("<link[^>]*?rel=[\"'](icon|shortcut icon)[\"'][^>]*?href=[\"'](?<href>.*?)[\"'][^>]*?>", 0, 0, NULL);
	g_regex_match (regex, data->content, 0, &match_info);
	
	while (g_match_info_matches (match_info)) {
		gchar *word = g_match_info_fetch_named (match_info, "href");
		if ( !g_str_has_prefix(word, "http") ) {
			icon_url = g_strdup_printf("%s/%s", feed->site_url, word);
			g_free(word);
			break;
		}
		g_free (word);
		g_match_info_next (match_info, NULL);
	}
	g_match_info_free (match_info);
	g_regex_unref (regex);
	nsp_net_free(data);
	
	/* If no image is found - use home url + /favicon.ico */
	if ( icon_url == NULL ) {
		regex = g_regex_new ("^(?<hostname>https?://[^/]*)", 0, 0, NULL);
		g_regex_match (regex, feed->site_url, 0, &match_info);
		
		if (g_match_info_matches (match_info)) {
			gchar *word = g_match_info_fetch_named (match_info, "hostname");
			icon_url = g_strdup_printf("%s/favicon.ico", word);
			g_free (word);
		}
		
		g_match_info_free (match_info);
		g_regex_unref (regex);
	}
	
	/* Store the image to a GtkPixbufLoader */
	loader = gdk_pixbuf_loader_new();
	curl = curl_easy_init();
	curl_easy_setopt (curl, CURLOPT_URL, icon_url);
	curl_easy_setopt (curl, CURLOPT_HEADER, 0);
	curl_easy_setopt (curl, CURLOPT_FOLLOWLOCATION, 1);
	curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, nsp_feed_download_icon_cb );
	curl_easy_setopt (curl, CURLOPT_WRITEDATA, loader);
	curl_easy_setopt (curl, CURLOPT_TIMEOUT, 60);
	curl_easy_setopt (curl, CURLOPT_NOSIGNAL, 1);
	
	result = curl_easy_perform (curl);
	curl_easy_cleanup(curl);
	g_free(icon_url);
	
	if ( result != 0) {
		return 1;
	}
	
	gdk_pixbuf_loader_close (loader, NULL);
	feed->icon = gdk_pixbuf_loader_get_pixbuf (loader);
	
	if ( !GDK_IS_PIXBUF(feed->icon) ) {
		feed->icon = NULL;
		return 1;
	}
	
	/* Resize and save the image */
	if (gdk_pixbuf_get_width (feed->icon) != 16 || gdk_pixbuf_get_height (feed->icon) != 16) {
		GdkPixbuf *old = feed->icon;
		feed->icon = gdk_pixbuf_scale_simple (old, 16, 16, GDK_INTERP_BILINEAR);
		g_object_unref (G_OBJECT (old));
	}
	
	feed_id_string = malloc(sizeof(char)*9);
	g_snprintf (feed_id_string, 9, "%i", feed->id);
	
	icon_path = g_build_filename( g_get_user_data_dir(), PACKAGE, "/icons", NULL);
	g_mkdir_with_parents(icon_path, 0700);
	
	icon_path = g_build_filename( icon_path, "/", feed_id_string, NULL);
	gdk_pixbuf_save(feed->icon, icon_path, "png", &error, NULL);
	
	if ( error != NULL ) {
		g_warning("ERROR: %s\n", error->message);
		g_error_free(error);
	}
	g_free(icon_path);
	free(feed_id_string);
	
	return 0;
}
static gboolean
gst_genicamsrc_start (GstBaseSrc * bsrc)
{
  GstGenicamSrc *src = GST_GENICAM_SRC (bsrc);
  GC_ERROR ret;
  uint32_t i, num_ifaces, num_devs;
  guint32 width, height, bpp, stride;
  GstVideoInfo vinfo;

  GST_DEBUG_OBJECT (src, "start");

  /* bind functions from CTI */
  if (!gst_genicamsrc_bind_functions (src)) {
    GST_ELEMENT_ERROR (src, LIBRARY, INIT,
        ("GenTL CTI could not be opened: %s", g_module_error ()), (NULL));
    return FALSE;
  }

  /* initialize library and print info */
  ret = GTL_GCInitLib ();
  HANDLE_GTL_ERROR ("GenTL Producer library could not be initialized");

  gst_genicam_print_gentl_impl_info (src);

  /* open GenTL, print info, and update interface list */
  ret = GTL_TLOpen (&src->hTL);
  HANDLE_GTL_ERROR ("System module failed to open");

  gst_genicam_print_system_info (src);

  ret = GTL_TLUpdateInterfaceList (src->hTL, NULL, src->timeout);
  HANDLE_GTL_ERROR ("Failed to update interface list within timeout");

  /* print info for all interfaces and open specified interface */
  ret = GTL_TLGetNumInterfaces (src->hTL, &num_ifaces);
  HANDLE_GTL_ERROR ("Failed to get number of interfaces");
  if (num_ifaces > 0) {
    GST_DEBUG_OBJECT (src, "Found %dGenTL interfaces", num_ifaces);
    for (i = 0; i < num_ifaces; ++i) {
      gst_genicam_print_interface_info (src, i);
    }
  } else {
    GST_ELEMENT_ERROR (src, LIBRARY, FAILED, ("No interfaces found"), (NULL));
    goto error;
  }

  if (!src->interface_id || src->interface_id[0] == 0) {
    size_t id_size;
    GST_DEBUG_OBJECT (src, "Trying to find interface ID at index %d",
        src->interface_index);

    ret = GTL_TLGetInterfaceID (src->hTL, src->interface_index, NULL, &id_size);
    HANDLE_GTL_ERROR ("Failed to get interface ID at specified index");
    if (src->interface_id) {
      g_free (src->interface_id);
    }
    src->interface_id = (gchar *) g_malloc (id_size);
    ret =
        GTL_TLGetInterfaceID (src->hTL, src->interface_index, src->interface_id,
        &id_size);
    HANDLE_GTL_ERROR ("Failed to get interface ID at specified index");
  }

  GST_DEBUG_OBJECT (src, "Trying to open interface '%s'", src->interface_id);
  ret = GTL_TLOpenInterface (src->hTL, src->interface_id, &src->hIF);
  HANDLE_GTL_ERROR ("Interface module failed to open");

  ret = GTL_IFUpdateDeviceList (src->hIF, NULL, src->timeout);
  HANDLE_GTL_ERROR ("Failed to update device list within timeout");

  /* print info for all devices and open specified device */
  ret = GTL_IFGetNumDevices (src->hIF, &num_devs);
  HANDLE_GTL_ERROR ("Failed to get number of devices");
  if (num_devs > 0) {
    for (i = 0; i < num_devs; ++i) {
      gst_genicam_print_device_info (src, i);
    }
  } else {
    GST_ELEMENT_ERROR (src, LIBRARY, FAILED,
        ("No devices found on interface"), (NULL));
    goto error;
  }

  if (!src->device_id || src->device_id[0] == 0) {
    size_t id_size;
    GST_DEBUG_OBJECT (src, "Trying to find device ID at index %d",
        src->device_index);

    GTL_IFGetDeviceID (src->hIF, src->device_index, NULL, &id_size);
    HANDLE_GTL_ERROR ("Failed to get device ID at specified index");
    if (src->device_id) {
      g_free (src->device_id);
    }
    src->device_id = (gchar *) g_malloc (id_size);
    GTL_IFGetDeviceID (src->hIF, src->device_index, src->device_id, &id_size);
    HANDLE_GTL_ERROR ("Failed to get device ID at specified index");
  }

  GST_DEBUG_OBJECT (src, "Trying to open device '%s'", src->device_id);
  ret =
      GTL_IFOpenDevice (src->hIF, src->device_id, DEVICE_ACCESS_CONTROL,
      &src->hDEV);
  HANDLE_GTL_ERROR ("Failed to open device");

  /* find and open specified data stream id */
  if (!src->stream_id || src->stream_id[0] == 0) {
    size_t id_size;
    GST_DEBUG_OBJECT (src, "Trying to find stream ID at index %d",
        src->stream_index);

    GTL_DevGetDataStreamID (src->hDEV, src->stream_index, NULL, &id_size);
    HANDLE_GTL_ERROR ("Failed to get stream ID at specified index");
    if (src->stream_id) {
      g_free (src->stream_id);
    }
    src->stream_id = (gchar *) g_malloc (id_size);
    GTL_DevGetDataStreamID (src->hDEV, src->stream_index, src->stream_id,
        &id_size);
    HANDLE_GTL_ERROR ("Failed to get stream ID at specified index");
  }

  GST_DEBUG_OBJECT (src, "Trying to open data stream '%s'", src->stream_id);
  ret = GTL_DevOpenDataStream (src->hDEV, src->stream_id, &src->hDS);
  HANDLE_GTL_ERROR ("Failed to open data stream");

  {
    uint32_t num_urls = 0;
    char url[2048];
    size_t url_len = sizeof (url);
    INFO_DATATYPE datatype;
    const uint32_t url_index = 0;

    ret = GTL_DevGetPort (src->hDEV, &src->hDevPort);
    HANDLE_GTL_ERROR ("Failed to get port on device");
    ret = GTL_GCGetNumPortURLs (src->hDevPort, &num_urls);
    HANDLE_GTL_ERROR ("Failed to get number of port URLs");

    GST_DEBUG_OBJECT (src, "Found %d port URLs", num_urls);

    GST_DEBUG_OBJECT (src, "Trying to get URL index %d", url_index);
    GTL_GCGetPortURLInfo (src->hDevPort, url_index, URL_INFO_URL, &datatype,
        url, &url_len);
    HANDLE_GTL_ERROR ("Failed to get URL");
    GST_DEBUG_OBJECT (src, "Found URL '%s'", url);

    g_assert (url_len > 6);
    if (g_str_has_prefix (url, "file")) {
      GST_ELEMENT_ERROR (src, RESOURCE, TOO_LAZY,
          ("file url not supported yet"), (NULL));
      goto error;
    } else if (g_str_has_prefix (url, "local")) {
      GError *err = NULL;
      GMatchInfo *matchInfo;
      GRegex *regex;
      gchar *filename, *addr_str, *len_str;
      uint64_t addr;
      size_t len;
      gchar *buf;

      regex =
          g_regex_new
          ("local:(?:///)?(?<filename>[^;]+);(?<address>[^;]+);(?<length>[^?]+)(?:[?]SchemaVersion=([^&]+))?",
          (GRegexCompileFlags) 0, (GRegexMatchFlags) 0, &err);
      if (!regex) {
        goto error;
      }
      g_regex_match (regex, url, (GRegexMatchFlags) 0, &matchInfo);
      filename = g_match_info_fetch_named (matchInfo, "filename");
      addr_str = g_match_info_fetch_named (matchInfo, "address");
      len_str = g_match_info_fetch_named (matchInfo, "length");
      if (!filename || !addr_str || !len_str) {
        GST_ELEMENT_ERROR (src, RESOURCE, TOO_LAZY,
            ("Failed to parse local URL"), (NULL));
        goto error;
      }

      addr = g_ascii_strtoull (addr_str, NULL, 16);
      len = g_ascii_strtoull (len_str, NULL, 16);
      buf = (gchar *) g_malloc (len);
      GTL_GCReadPort (src->hDevPort, addr, buf, &len);
      HANDLE_GTL_ERROR ("Failed to read XML from port");

      if (g_str_has_suffix (filename, "zip")) {
        gchar *zipfilepath;
        unzFile uf;
        unz_file_info64 fileinfo;
        gchar xmlfilename[2048];
        gchar *xml;

        zipfilepath = g_build_filename (g_get_tmp_dir (), filename, NULL);
        if (!g_file_set_contents (zipfilepath, buf, len, &err)) {
          GST_ELEMENT_ERROR (src, RESOURCE, TOO_LAZY,
              ("Failed to write zipped XML to %s", zipfilepath), (NULL));
          goto error;
        }
        uf = unzOpen64 (zipfilepath);
        if (!uf) {
          GST_ELEMENT_ERROR (src, RESOURCE, TOO_LAZY,
              ("Failed to open zipped XML %s", zipfilepath), (NULL));
          goto error;
        }
        //ret = unzGetGlobalInfo64(uf, &gi);
        ret =
            unzGetCurrentFileInfo64 (uf, &fileinfo, xmlfilename,
            sizeof (xmlfilename), NULL, 0, NULL, 0);
        if (ret != UNZ_OK) {
          GST_ELEMENT_ERROR (src, RESOURCE, TOO_LAZY,
              ("Failed to query zip file %s", zipfilepath), (NULL));
          goto error;
        }

        ret = unzOpenCurrentFile (uf);
        if (ret != UNZ_OK) {
          GST_ELEMENT_ERROR (src, RESOURCE, TOO_LAZY,
              ("Failed to extract file %s", xmlfilename), (NULL));
          goto error;
        }

        xml = (gchar *) g_malloc (fileinfo.uncompressed_size);
        if (!xml) {
          GST_ELEMENT_ERROR (src, RESOURCE, TOO_LAZY,
              ("Failed to allocate memory to extract XML file"), (NULL));
          goto error;
        }

        ret = unzReadCurrentFile (uf, xml, fileinfo.uncompressed_size);
        if (ret != fileinfo.uncompressed_size) {
          GST_ELEMENT_ERROR (src, RESOURCE, TOO_LAZY,
              ("Failed to extract XML file %s", xmlfilename), (NULL));
          goto error;
        }
        unzClose (uf);
        g_free (zipfilepath);

        zipfilepath = g_build_filename (g_get_tmp_dir (), xmlfilename, NULL);
        g_file_set_contents (zipfilepath, xml, fileinfo.uncompressed_size,
            &err);
        g_free (zipfilepath);

        g_free (xml);
        //GZlibDecompressor *decompress;
        //char *unzipped;
        //gsize outbuf_size, bytes_read, bytes_written;
        //GInputStream *zippedstream, *unzippedstream;
        //decompress = g_zlib_decompressor_new (G_ZLIB_COMPRESSOR_FORMAT_ZLIB);

        ////zippedstream = g_memory_input_stream_new_from_data(buf, len, g_free);
        ////unzippedstream = g_converter_input_stream_new (zippedstream, G_CONVERTER(decompress));
        ////g_input_stream_read_all (G_INPUT_STREAM(unzippedstream), 
        ////    g_converter_output_stream
        //outbuf_size = 10000000;
        //unzipped = (gchar*) g_malloc(outbuf_size);
        //g_converter_convert (G_CONVERTER (decompress), buf, len, unzipped, outbuf_size, G_CONVERTER_NO_FLAGS, &bytes_read, &bytes_written, &err);
        //GST_DEBUG_OBJECT (src, unzipped);
      }

      g_free (filename);
      g_free (addr_str);
      g_free (len_str);
      g_free (buf);
    } else if (g_str_has_prefix (url, "http")) {
      GST_ELEMENT_ERROR (src, RESOURCE, TOO_LAZY,
          ("file url not supported yet"), (NULL));
      goto error;
    }
  }

  {
    // TODO: use Genicam node map for this
    guint32 val = 0;
    size_t datasize = 4;
    ret = GTL_GCReadPort (src->hDevPort, 0x30204, &val, &datasize);
    HANDLE_GTL_ERROR ("Failed to get width");
    width = GUINT32_FROM_BE (val);
    ret = GTL_GCReadPort (src->hDevPort, 0x30224, &val, &datasize);
    HANDLE_GTL_ERROR ("Failed to get height");
    height = GUINT32_FROM_BE (val);

    bpp = 8;
  }

  if (!gst_genicamsrc_prepare_buffers (src)) {
    GST_ELEMENT_ERROR (src, RESOURCE, TOO_LAZY, ("Failed to prepare buffers"),
        (NULL));
    goto error;
  }

  {
    ret =
        GTL_GCRegisterEvent (src->hDS, EVENT_NEW_BUFFER, &src->hNewBufferEvent);
    HANDLE_GTL_ERROR ("Failed to register New Buffer event");
  }

  ret =
      GTL_DSStartAcquisition (src->hDS, ACQ_START_FLAGS_DEFAULT,
      GENTL_INFINITE);
  HANDLE_GTL_ERROR ("Failed to start stream acquisition");

  {
    // TODO: use Genicam node map for this
    guint32 val;
    size_t datasize;

    /* set AcquisitionMode to Continuous */
    val = GUINT32_TO_BE (2);
    datasize = sizeof (val);
    ret = GTL_GCWritePort (src->hDevPort, 0x40004, &val, &datasize);
    HANDLE_GTL_ERROR ("Failed to start device acquisition");

    /* send AcquisitionStart command */
    val = GUINT32_TO_BE (1);
    datasize = sizeof (val);
    ret = GTL_GCWritePort (src->hDevPort, 0x40024, &val, &datasize);
    HANDLE_GTL_ERROR ("Failed to start device acquisition");
  }

  /* create caps */
  if (src->caps) {
    gst_caps_unref (src->caps);
    src->caps = NULL;
  }

  gst_video_info_init (&vinfo);

  if (bpp <= 8) {
    gst_video_info_set_format (&vinfo, GST_VIDEO_FORMAT_GRAY8, width, height);
    src->caps = gst_video_info_to_caps (&vinfo);
  } else if (bpp > 8 && bpp <= 16) {
    GValue val = G_VALUE_INIT;
    GstStructure *s;

    if (G_BYTE_ORDER == G_LITTLE_ENDIAN) {
      gst_video_info_set_format (&vinfo, GST_VIDEO_FORMAT_GRAY16_LE, width,
          height);
    } else if (G_BYTE_ORDER == G_BIG_ENDIAN) {
      gst_video_info_set_format (&vinfo, GST_VIDEO_FORMAT_GRAY16_BE, width,
          height);
    }
    src->caps = gst_video_info_to_caps (&vinfo);

    /* set bpp, extra info for GRAY16 so elements can scale properly */
    s = gst_caps_get_structure (src->caps, 0);
    g_value_init (&val, G_TYPE_INT);
    g_value_set_int (&val, bpp);
    gst_structure_set_value (s, "bpp", &val);
    g_value_unset (&val);
  } else {
    GST_ELEMENT_ERROR (src, STREAM, WRONG_TYPE,
        ("Unknown or unsupported bit depth (%d).", bpp), (NULL));
    return FALSE;
  }

  src->height = vinfo.height;
  src->gst_stride = GST_VIDEO_INFO_COMP_STRIDE (&vinfo, 0);

  GST_DEBUG_OBJECT (src, "starting acquisition");
//TODO: start acquisition engine

  /* TODO: check timestamps on buffers vs start time */
  src->acq_start_time =
      gst_clock_get_time (gst_element_get_clock (GST_ELEMENT (src)));

  return TRUE;

error:
  if (src->hDS) {
    GTL_DSClose (src->hDS);
    src->hDS = NULL;
  }

  if (src->hDEV) {
    GTL_DevClose (src->hDEV);
    src->hDEV = NULL;
  }

  if (src->hIF) {
    GTL_IFClose (src->hIF);
    src->hIF = NULL;
  }

  if (src->hTL) {
    GTL_TLClose (src->hTL);
    src->hTL = NULL;
  }

  GTL_GCCloseLib ();

  return FALSE;
}
Example #20
0
GList *
gimp_palette_load_css (GimpContext   *context,
                       GFile         *file,
                       GInputStream  *input,
                       GError       **error)
{
  GimpPalette      *palette;
  GDataInputStream *data_input;
  gchar            *name;
  GRegex           *regex;
  gchar            *buf;

  g_return_val_if_fail (G_IS_FILE (file), NULL);
  g_return_val_if_fail (G_IS_INPUT_STREAM (input), NULL);
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);

  regex = g_regex_new (".*color.*:(?P<param>.*);", G_REGEX_CASELESS, 0, error);
  if (! regex)
    return NULL;

  name = g_path_get_basename (gimp_file_get_utf8_name (file));
  palette = GIMP_PALETTE (gimp_palette_new (context, name));
  g_free (name);

  data_input = g_data_input_stream_new (input);

  do
    {
      gsize  buf_len = 1024;

      buf = g_data_input_stream_read_line (data_input, &buf_len, NULL, NULL);

      if (buf)
        {
          GMatchInfo *matches;

          if (g_regex_match (regex, buf, 0, &matches))
            {
              GimpRGB  color;
              gchar   *word = g_match_info_fetch_named (matches, "param");

              if (gimp_rgb_parse_css (&color, word, -1))
                {
                  if (! gimp_palette_find_entry (palette, &color, NULL))
                    {
                      gimp_palette_add_entry (palette, -1, NULL, &color);
                    }
                }

              g_free (word);
            }
          g_match_info_free (matches);
          g_free (buf);
        }
    }
  while (buf);

  g_regex_unref (regex);
  g_object_unref (data_input);

  return g_list_prepend (NULL, palette);
}
Example #21
0
static pcat_rcode read_line( data_bucket b, gchar *line, GError **err, read_line_result rval )
{
    pcat_rcode rv = PCAT_SUCCESS;
    
    GMatchInfo *result_match = NULL;
    gboolean matched = g_regex_match( b->result_regex, line, 0 /* match flags */, &result_match );
    if( g_match_info_matches( result_match ) )
    {
        if( !matched )
        {
            abort();
            return PCAT_ERROR;
        }
        gchar *res = g_match_info_fetch_named( result_match, "res" );
        if( res != NULL )
        {
            if( 0 == strcmp( res, "SUCCESS" ) )
            {
                rval->value_result = line_result;
                rval->_.r.succeeded = TRUE;
                g_print( "YAY WE HAVE SUCCESS\n" );
            }
            else if( 0 == strcmp( res, "" ) )
            {
                gchar *second = g_match_info_fetch_named( result_match, "fcode" );
                if( second != NULL )
                {
                    rval->value_result = line_result;
                    rval->_.r.succeeded = FALSE;
                    int match = sscanf( second, "%"SCNi32, &rval->_.r.fcode );
                    if( match != 1 )
                    {
                        printf( "my anger subsides\n" );
                        abort();
                    }
                    printf( "Here we went: %"PRIi32"\n", rval->_.r.fcode );
                    g_free( second );
                }
                else
                {
                    printf( "screw you too\n" );
                    abort();
                }
            }
            else
            {
                printf( "BAD BAD BAD\n" );
                abort();
            }
            g_free( res );
        }
        else
        {
            printf( "screw you two\n" );
            abort();
        }
        // gchar *type_val = g_match_info_fetch( match_info, 2 );
        // gchar *value    = g_match_info_fetch( match_info, 3 );
    }
    else
    {
        GMatchInfo *val_match = NULL;
        matched = g_regex_match( b->val_regex, line, 0 /* match flags */, &val_match );
        if( g_match_info_matches( val_match ) )
        {
            if( !matched )
            {
                abort();
                return PCAT_ERROR;
            }
            parse_value( val_match, err, &rval->_.v );
        }
        else
        {
            //g_print( "NO MATCH: %s", line );
            rv = PCAT_NO_MATCH;
        }
        g_match_info_free( val_match );
    }
    g_match_info_free( result_match );
    return rv;
}
Example #22
0
GList *
gimp_palette_load_css (const gchar  *filename,
		       GError      **error)
{
  GimpPalette *palette;
  gchar       *name;
  FILE        *file;
  GRegex      *regex;
  GimpRGB      color;

  g_return_val_if_fail (filename != NULL, NULL);
  g_return_val_if_fail (g_path_is_absolute (filename), NULL);
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);

  regex = g_regex_new (".*color.*:(?P<param>.*);", G_REGEX_CASELESS, 0, error);
  if (! regex)
    return NULL;

  file = g_fopen (filename, "rb");
  if (! file)
    {
      g_set_error (error, GIMP_DATA_ERROR, GIMP_DATA_ERROR_OPEN,
                   _("Could not open '%s' for reading: %s"),
                   gimp_filename_to_utf8 (filename), g_strerror (errno));
      return NULL;
    }

  name = g_filename_display_basename (filename);
  palette = GIMP_PALETTE (gimp_palette_new (name));
  g_free (name);

  do
    {
      GMatchInfo *matches;
      gchar       buf[1024];

      if (fgets (buf, sizeof (buf), file) != NULL)
	{
	  if (g_regex_match (regex, buf, 0, &matches))
	    {
	      gchar *word = g_match_info_fetch_named (matches, "param");

	      if (gimp_rgb_parse_css (&color, word, -1))
		{
		  if (! gimp_palette_find_entry (palette, &color, NULL))
		    {
		      gimp_palette_add_entry (palette, -1, NULL, &color);
		    }
		}

	      g_free (word);
	    }
	}
    } while (! feof (file));

  fclose (file);

  g_regex_unref (regex);

  return g_list_prepend (NULL, palette);
}
Example #23
0
static void rclib_lyric_add_line(RCLibLyricParsedData *parsed_data,
    GRegex *regex, const gchar *encoding, const gchar *line, gsize length)
{
    GMatchInfo *match_info;
    gchar *tmp;
    gchar *lyric_line;
    gsize bytes_read, bytes_written;
    gint minute = 0;
    gfloat second = 0.0;
    gint64 time;
    gchar *str;
    gint value;
    gchar *text = NULL;
    GArray *time_array;
    gint i;
    RCLibLyricData *lyric_data;
    if(parsed_data==NULL || regex==NULL || line==NULL) return;
    if(g_utf8_validate(line, length, NULL))
        lyric_line = g_strdup(line);
    else if(encoding!=NULL)
    {
        tmp = g_convert(line, length, "UTF-8", encoding, &bytes_read,
            &bytes_written, NULL);
        if(tmp==NULL) return;
        lyric_line = tmp;
    }
    else return;
    if(!g_regex_match(regex, lyric_line, 0, &match_info))
    {
        g_free(lyric_line);
        return;
    }
    time_array = g_array_new(FALSE, FALSE, sizeof(gint64));
    while(g_match_info_matches(match_info))
    {
        str = g_match_info_fetch_named(match_info, "time");
        if(str!=NULL && strlen(str)>0)
        {
            if(sscanf(str, "[%d:%f]", &minute, &second)==2)
            {
                time = minute * 6000 + (gint)(second * 100);
                time *= 10 * GST_MSECOND;
                g_array_append_val(time_array, time);
            }
        }
        g_free(str);
        str = g_match_info_fetch_named(match_info, "title");
        if(str!=NULL)
            tmp = g_strstr_len(str, -1, ":");
        else
            tmp = NULL;
        if(tmp!=NULL && strlen(tmp)>2)
        {
            tmp++;
            if(parsed_data->title==NULL)
                parsed_data->title = g_strndup(tmp, strlen(tmp)-1);
        }
        g_free(str);
        str = g_match_info_fetch_named(match_info, "artist");
        if(str!=NULL)
            tmp = g_strstr_len(str, -1, ":");
        else
            tmp = NULL;
        if(tmp!=NULL && strlen(tmp)>2)
        {
            tmp++;
            if(parsed_data->artist==NULL)
                parsed_data->artist = g_strndup(tmp, strlen(tmp)-1);
        }
        g_free(str);
        str = g_match_info_fetch_named(match_info, "album");
        if(str!=NULL)
            tmp = g_strstr_len(str, -1, ":");
        else
            tmp = NULL;
        if(tmp!=NULL && strlen(tmp)>2)
        {
            tmp++;
            if(parsed_data->album==NULL)
                parsed_data->album = g_strndup(tmp, strlen(tmp)-1);
        }
        g_free(str);
        str = g_match_info_fetch_named(match_info, "author");
        if(str!=NULL)
            tmp = g_strstr_len(str, -1, ":");
        else
            tmp = NULL;
        if(tmp!=NULL && strlen(tmp)>2)
        {
            tmp++;
            if(parsed_data->author==NULL)
                parsed_data->author = g_strndup(tmp, strlen(tmp)-1);
        }
        g_free(str);
        str = g_match_info_fetch_named(match_info, "offset");
        if(str!=NULL)
            tmp = g_strstr_len(str, -1, ":");
        else
            tmp = NULL;
        if(tmp!=NULL && strlen(tmp)>2)
        {
            tmp++;
            if(sscanf(tmp, "%d", &value)==1)
                parsed_data->offset = value;
        }
        g_free(str);
        str = g_match_info_fetch_named(match_info, "text");
        if(str!=NULL && strlen(str)>0)
        {
            text = g_strdup(str);
        }
        g_free(str);
        g_match_info_next(match_info, NULL);
    }
    if(text==NULL) text = g_strdup("");
    for(i=0;i<time_array->len;i++)
    {
        lyric_data = g_new0(RCLibLyricData, 1);
        lyric_data->time = g_array_index(time_array, gint64, i);
        lyric_data->length = -1;
        lyric_data->text = g_strdup(text);
        g_sequence_insert_sorted(parsed_data->seq, lyric_data,
            rclib_lyric_time_compare_func, NULL);
    }
    g_free(text);
    g_array_free(time_array, TRUE);
    g_free(lyric_line);
}
/**
 * rakia_codec_param_parse_generic:
 * @fmtp: a string value with the parameter description
 * @out: the parameter map to populate
 *
 * Parses parameters formatted as a semicolon separated list of
 * <replaceable>parameter</replaceable><literal>=</literal><replaceable>value</replaceable>
 * pairs, as recommended in IETF RFC 4855 Section 3.
 */
static void
rakia_codec_param_parse_generic (const gchar *fmtp, TpMediaStreamType media_type,
    RakiaSipCodec *codec)
{
  GMatchInfo *match = NULL;
  gint pos;
  gint value_start;
  gint value_end;

  if (fmtp == NULL)
    return;

  pos = 0;

  /* Fast path for trivial cases, not involving the regex engine */
  while (g_ascii_isspace (fmtp[pos]))
    ++pos;
  if (!fmtp[pos])
    return;

  g_assert (fmtp_attr_regex != NULL);

  g_regex_match_full (fmtp_attr_regex,
      fmtp, -1, pos, G_REGEX_MATCH_ANCHORED, &match, NULL);

  while (g_match_info_matches (match))
    {
      gchar *name;
      gchar *value;

      name = g_match_info_fetch_named (match, FMTP_MATCH_NAME_PARAM);

      g_match_info_fetch_named_pos (match, FMTP_MATCH_NAME_VALUE,
          &value_start, &value_end);

      if (value_end - 1 > value_start
          && fmtp[value_start] == '\"' && fmtp[value_end - 1] == '\"')
        {
          value = rakia_unquote_string (fmtp + value_start,
                                        value_end - value_start);
        }
      else
        {
          value = g_strndup (fmtp + value_start,
                             value_end - value_start);
        }

      rakia_sip_codec_add_param (codec, name, value);

      g_match_info_fetch_pos (match, 0, NULL, &pos);
      if (!fmtp[pos])
        break;

      g_match_info_next (match, NULL);
    }

  g_match_info_free (match);

  if (fmtp[pos])
    MESSAGE ("failed to parse part of format parameters"
               " as an attribute-value list: %s", &fmtp[pos]);
}
Example #25
0
/**
 * gnome_parse_locale:
 * @locale: a locale string
 * @language_codep: (out) (allow-none) (transfer full): location to
 * store the language code, or %NULL
 * @country_codep: (out) (allow-none) (transfer full): location to
 * store the country code, or %NULL
 * @codesetp: (out) (allow-none) (transfer full): location to
 * store the codeset, or %NULL
 * @modifierp: (out) (allow-none) (transfer full): location to
 * store the modifier, or %NULL
 *
 * Extracts the various components of a locale string of the form
 * [language[_country][.codeset][@modifier]]. See
 * http://en.wikipedia.org/wiki/Locale.
 *
 * Return value: %TRUE if parsing was successful.
 *
 * Since: 3.8
 */
gboolean
gnome_parse_locale (const char *locale,
                    char      **language_codep,
                    char      **country_codep,
                    char      **codesetp,
                    char      **modifierp)
{
        static GRegex *re = NULL;
        GMatchInfo *match_info;
        gboolean    res;
        gboolean    retval;

        match_info = NULL;
        retval = FALSE;

        if (re == NULL) {
                GError *error = NULL;
                re = g_regex_new ("^(?P<language>[^_.@[:space:]]+)"
                                  "(_(?P<territory>[[:upper:]]+))?"
                                  "(\\.(?P<codeset>[-_0-9a-zA-Z]+))?"
                                  "(@(?P<modifier>[[:ascii:]]+))?$",
                                  0, 0, &error);
                if (re == NULL) {
                        g_warning ("%s", error->message);
                        g_error_free (error);
                        goto out;
                }
        }

        if (!g_regex_match (re, locale, 0, &match_info) ||
            g_match_info_is_partial_match (match_info)) {
                g_warning ("locale '%s' isn't valid\n", locale);
                goto out;
        }

        res = g_match_info_matches (match_info);
        if (! res) {
                g_warning ("Unable to parse locale: %s", locale);
                goto out;
        }

        retval = TRUE;

        if (language_codep != NULL) {
                *language_codep = g_match_info_fetch_named (match_info, "language");
        }

        if (country_codep != NULL) {
                *country_codep = g_match_info_fetch_named (match_info, "territory");

                if (*country_codep != NULL &&
                    *country_codep[0] == '\0') {
                        g_free (*country_codep);
                        *country_codep = NULL;
                }
        }

        if (codesetp != NULL) {
                *codesetp = g_match_info_fetch_named (match_info, "codeset");

                if (*codesetp != NULL &&
                    *codesetp[0] == '\0') {
                        g_free (*codesetp);
                        *codesetp = NULL;
                }
        }

        if (modifierp != NULL) {
                *modifierp = g_match_info_fetch_named (match_info, "modifier");

                if (*modifierp != NULL &&
                    *modifierp[0] == '\0') {
                        g_free (*modifierp);
                        *modifierp = NULL;
                }
        }

        if (codesetp != NULL && *codesetp != NULL) {
                g_autofree gchar *normalized_codeset = NULL;
                g_autofree gchar *normalized_name = NULL;

                normalized_codeset = normalize_codeset (*codesetp);
                normalized_name = construct_language_name (language_codep ? *language_codep : NULL,
                                                           country_codep ? *country_codep : NULL,
                                                           normalized_codeset,
                                                           modifierp ? *modifierp : NULL);

                if (language_name_is_valid (normalized_name)) {
                        g_free (*codesetp);
                        *codesetp = g_steal_pointer (&normalized_codeset);
                }
        }

 out:
        g_match_info_free (match_info);

        return retval;
}
Example #26
0
GPtrArray* getBugzillaUrls(const string &changelog)
{
    GPtrArray *bugzilla_urls = g_ptr_array_new();

    // Matches Ubuntu bugs
    GRegex *regex;
    GMatchInfo *match_info;
    regex = g_regex_new("LP:\\s+(?:[,\\s*]?#(?'bug'\\d+))*",
                        G_REGEX_CASELESS,
                        G_REGEX_MATCH_NEWLINE_ANY,
                        0);
    g_regex_match (regex, changelog.c_str(), G_REGEX_MATCH_NEWLINE_ANY, &match_info);
    while (g_match_info_matches(match_info)) {
        gchar *bug = g_match_info_fetch_named(match_info, "bug");
        gchar *bugLink;

        bugLink = g_strdup_printf("https://bugs.launchpad.net/bugs/%s", bug);
        g_ptr_array_add(bugzilla_urls, (gpointer) bugLink);

        g_free(bug);
        g_match_info_next(match_info, NULL);
    }
    g_match_info_free(match_info);
    g_regex_unref(regex);

    // Debian bugs
    // Regular expressions to detect bug numbers in changelogs according to the
    // Debian Policy Chapter 4.4. For details see the footnote 15:
    // http://www.debian.org/doc/debian-policy/footnotes.html#f15
    // /closes:\s*(?:bug)?\#?\s?\d+(?:,\s*(?:bug)?\#?\s?\d+)*/i
    regex = g_regex_new("closes:\\s*(?:bug)?\\#?\\s?(?'bug1'\\d+)(?:,\\s*(?:bug)?\\#?\\s?(?'bug2'\\d+))*",
                        G_REGEX_CASELESS,
                        G_REGEX_MATCH_NEWLINE_ANY,
                        0);
    g_regex_match (regex, changelog.c_str(), G_REGEX_MATCH_NEWLINE_ANY, &match_info);
    while (g_match_info_matches(match_info)) {
        gchar *bug1 = g_match_info_fetch_named(match_info, "bug1");
        gchar *bugLink1;

        bugLink1 = g_strdup_printf("http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=%s", bug1);
        g_ptr_array_add(bugzilla_urls, (gpointer) bugLink1);

        g_free(bug1);

        gchar *bug2 = g_match_info_fetch_named(match_info, "bug2");
        if (bug2 != NULL) {
            gchar *bugLink2;

            bugLink2 = g_strdup_printf("http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=%s", bug2);
            g_ptr_array_add(bugzilla_urls, (gpointer) bugLink2);

            g_free(bug2);
        }

        g_match_info_next(match_info, NULL);
    }
    g_match_info_free(match_info);
    g_regex_unref(regex);

    // NULL terminate
    g_ptr_array_add(bugzilla_urls, NULL);

    return bugzilla_urls;
}
Example #27
0
string fetchChangelogData(AptCacheFile &CacheFile,
                          pkgAcquire &Fetcher,
                          pkgCache::VerIterator Ver,
                          pkgCache::VerIterator currver,
                          string *update_text,
                          string *updated,
                          string *issued)
{
    string changelog;

    pkgAcqChangelog *c = new pkgAcqChangelog(&Fetcher, Ver);

    // try downloading it, if that fails, try third-party-changelogs location
    // FIXME: Fetcher.Run() is "Continue" even if I get a 404?!?
    Fetcher.Run();

    // error
    pkgRecords Recs(CacheFile);
    pkgCache::PkgIterator Pkg = Ver.ParentPkg();
    pkgRecords::Parser &rec=Recs.Lookup(Ver.FileList());
    string srcpkg = rec.SourcePkg().empty() ? Pkg.Name() : rec.SourcePkg();
    changelog = "Changelog for this version is not yet available";

    // return empty string if we don't have a file to read
    if (!FileExists(c->DestFile)) {
        return changelog;
    }

    if (_error->PendingError()) {
        return changelog;
    }

    ifstream in(c->DestFile.c_str());
    string line;
    g_autoptr(GRegex) regexVer = NULL;
    regexVer = g_regex_new("(?'source'.+) \\((?'version'.*)\\) "
                           "(?'dist'.+); urgency=(?'urgency'.+)",
                           G_REGEX_CASELESS,
                           G_REGEX_MATCH_ANCHORED,
                           0);
    g_autoptr(GRegex) regexDate = NULL;
    regexDate = g_regex_new("^ -- (?'maintainer'.+) (?'mail'<.+>)  (?'date'.+)$",
                            G_REGEX_CASELESS,
                            G_REGEX_MATCH_ANCHORED,
                            0);

    changelog = "";
    while (getline(in, line)) {
        // we don't want the additional whitespace, because it can confuse
        // some markdown parsers used by client tools
        if (starts_with(line, "  "))
            line.erase(0,1);
        // no need to free str later, it is allocated in a static buffer
        const char *str = utf8(line.c_str());
        if (strcmp(str, "") == 0) {
            changelog.append("\n");
            continue;
        } else {
            changelog.append(str);
            changelog.append("\n");
        }

        if (starts_with(str, srcpkg.c_str())) {
            // Check to see if the the text isn't about the current package,
            // otherwise add a == version ==
            GMatchInfo *match_info;
            if (g_regex_match(regexVer, str, G_REGEX_MATCH_ANCHORED, &match_info)) {
                gchar *version;
                version = g_match_info_fetch_named(match_info, "version");

                // Compare if the current version is shown in the changelog, to not
                // display old changelog information
                if (_system != 0  &&
                        _system->VS->DoCmpVersion(version, version + strlen(version),
                                                  currver.VerStr(), currver.VerStr() + strlen(currver.VerStr())) <= 0) {
                    g_free (version);
                    break;
                } else {
                    if (!update_text->empty()) {
                        update_text->append("\n\n");
                    }
                    update_text->append(" == ");
                    update_text->append(version);
                    update_text->append(" ==");
                    g_free (version);
                }
            }
            g_match_info_free (match_info);
        } else if (starts_with(str, " ")) {
            // update descritption
            update_text->append("\n");
            update_text->append(str);
        } else if (starts_with(str, " --")) {
            // Parse the text to know when the update was issued,
            // and when it got updated
            GMatchInfo *match_info;
            if (g_regex_match(regexDate, str, G_REGEX_MATCH_ANCHORED, &match_info)) {
                GTimeVal dateTime = {0, 0};
                gchar *date;
                date = g_match_info_fetch_named(match_info, "date");
                time_t time;
                g_warn_if_fail(RFC1123StrToTime(date, time));
                dateTime.tv_sec = time;
                g_free(date);

                *issued = g_time_val_to_iso8601(&dateTime);
                if (updated->empty()) {
                    *updated = g_time_val_to_iso8601(&dateTime);
                }
            }
            g_match_info_free(match_info);
        }
    }

    return changelog;
}