예제 #1
0
/**
 * load_codecs_cache
 * @media_type: a #FsMediaType
 *
 * Will load the codecs blueprints from the cache.
 *
 * Returns: TRUE if successful, FALSE if error, or cache outdated
 *
 */
GList *
load_codecs_cache (FsMediaType media_type)
{
  GMappedFile *mapped = NULL;
  gchar *contents = NULL;
  gchar *in = NULL;
  gsize size;
  GError *err = NULL;
  GList *blueprints = NULL;

  gchar magic[8] = {0};
  gchar magic_media = '?';
  gint num_blueprints;
  gchar *cache_path;
  int i;


  if (media_type == FS_MEDIA_TYPE_AUDIO) {
    magic_media = 'A';
  } else if (media_type == FS_MEDIA_TYPE_VIDEO) {
    magic_media = 'V';
  } else {
    GST_ERROR ("Invalid media type %d", media_type);
    return NULL;
  }

  cache_path = get_codecs_cache_path (media_type);

  if (!cache_path)
    return NULL;

  if (!codecs_cache_valid (cache_path)) {
    GST_DEBUG ("Codecs cache %s is outdated or does not exist", cache_path);
    g_free (cache_path);
    return NULL;
  }

  GST_DEBUG ("Loading codecs cache %s", cache_path);

  mapped = g_mapped_file_new (cache_path, FALSE, &err);
  if (mapped == NULL) {
    GST_DEBUG ("Unable to mmap file %s : %s", cache_path,
      err ? err->message: "unknown error");
    g_clear_error (&err);

    if (!g_file_get_contents (cache_path, &contents, &size, NULL))
      goto error;
  } else {
    if ((contents = g_mapped_file_get_contents (mapped)) == NULL) {
      GST_WARNING ("Can't load file %s : %s", cache_path, g_strerror (errno));
      goto error;
    }
    /* check length for header */
    size = g_mapped_file_get_length (mapped);
  }

  /* in is a cursor pointer on the file contents */

  in = contents;

  if (size < sizeof (magic)) {
    GST_WARNING ("Cache file corrupt");
    goto error;
  }

  memcpy (magic, in, sizeof (magic));
  in += sizeof (magic);
  size -= sizeof (magic);

  if (magic[0] != 'F' ||
      magic[1] != 'S' ||
      magic[2] != magic_media ||
      magic[3] != 'C' ||
      magic[4] != '1' ||   /* This is the version number */
      magic[5] != '1') {
    GST_WARNING ("Cache file has incorrect magic header. File corrupted");
    goto error;
  }

  if (size < sizeof (gint)) {
    GST_WARNING ("Cache file corrupt (size: %"G_GSIZE_FORMAT" < sizeof (int))",
        size);
    goto error;
  }

  memcpy (&num_blueprints, in, sizeof(gint));
  in += sizeof (gint);
  size -= sizeof (gint);

  if (num_blueprints > 50)
  {
    GST_WARNING ("Impossible number of blueprints in cache %d, ignoring",
        num_blueprints);
    goto error;
  }

  for (i = 0; i < num_blueprints; i++) {
    CodecBlueprint *blueprint = load_codec_blueprint (media_type, &in, &size);
    if (!blueprint) {
      GST_WARNING ("Can not load all of the blueprints, cache corrupted");

      if (blueprints) {
        g_list_foreach (blueprints, (GFunc) codec_blueprint_destroy, NULL);
        g_list_free (blueprints);
        blueprints = NULL;
      }

      goto error;
    }
    blueprints = g_list_append (blueprints, blueprint);
  }

 error:
  if (mapped) {
#if GLIB_CHECK_VERSION(2,22,0)
    g_mapped_file_unref (mapped);
#else
    g_mapped_file_free (mapped);
#endif
  } else {
    g_free (contents);
  }
  g_free (cache_path);
  return blueprints;
}
예제 #2
0
static void
do_get (OtTrivialHttpd    *self,
        SoupServer        *server,
        SoupMessage       *msg,
        const char        *path,
        SoupClientContext *context)
{
  char *slash;
  int ret;
  struct stat stbuf;
  g_autofree char *safepath = NULL;

  httpd_log (self, "serving %s\n", path);
  if (strstr (path, "../") != NULL)
    {
      soup_message_set_status (msg, SOUP_STATUS_FORBIDDEN);
      goto out;
    }

  if (opt_random_500s_percentage > 0 &&
      emitted_random_500s_count < opt_random_500s_max &&
      g_random_int_range (0, 100) < opt_random_500s_percentage)
    {
      emitted_random_500s_count++;
      soup_message_set_status (msg, SOUP_STATUS_INTERNAL_SERVER_ERROR);
      goto out;
    }

  if (path[0] == '/')
    path++;

  safepath = g_build_filename (gs_file_get_path_cached (self->root), path, NULL);

  do
    ret = stat (safepath, &stbuf);
  while (ret == -1 && errno == EINTR);
  if (ret == -1)
    {
      if (errno == EPERM)
        soup_message_set_status (msg, SOUP_STATUS_FORBIDDEN);
      else if (errno == ENOENT)
        soup_message_set_status (msg, SOUP_STATUS_NOT_FOUND);
      else
        soup_message_set_status (msg, SOUP_STATUS_INTERNAL_SERVER_ERROR);
      goto out;
    }

  if (!is_safe_to_access (&stbuf))
    {
      soup_message_set_status (msg, SOUP_STATUS_FORBIDDEN);
      goto out;
    }

  if (S_ISDIR (stbuf.st_mode))
    {
      slash = strrchr (safepath, '/');
      if (!slash || slash[1])
        {
          g_autofree char *redir_uri = NULL;

          redir_uri = g_strdup_printf ("%s/", soup_message_get_uri (msg)->path);
          soup_message_set_redirect (msg, SOUP_STATUS_MOVED_PERMANENTLY,
                                     redir_uri);
        }
      else
        {
          g_autofree char *index_realpath = g_strconcat (safepath, "/index.html", NULL);
          if (stat (index_realpath, &stbuf) != -1)
            {
              g_autofree char *index_path = g_strconcat (path, "/index.html", NULL);
              do_get (self, server, msg, index_path, context);
            }
          else
            {
              GString *listing = get_directory_listing (safepath);
              soup_message_set_response (msg, "text/html",
                                         SOUP_MEMORY_TAKE,
                                         listing->str, listing->len);
              soup_message_set_status (msg, SOUP_STATUS_OK);
              g_string_free (listing, FALSE);
            }
        }
    }
  else 
    {
      if (!S_ISREG (stbuf.st_mode))
        {
          soup_message_set_status (msg, SOUP_STATUS_FORBIDDEN);
          goto out;
        }
      
      if (msg->method == SOUP_METHOD_GET)
        {
          g_autoptr(GMappedFile) mapping = NULL;
          gsize buffer_length, file_size;
          SoupRange *ranges;
          int ranges_length;
          gboolean have_ranges;

          mapping = g_mapped_file_new (safepath, FALSE, NULL);
          if (!mapping)
            {
              soup_message_set_status (msg, SOUP_STATUS_INTERNAL_SERVER_ERROR);
              goto out;
            }

          file_size = g_mapped_file_get_length (mapping);
          have_ranges = soup_message_headers_get_ranges(msg->request_headers, file_size, &ranges, &ranges_length);
          if (opt_force_ranges && !have_ranges && g_strrstr (path, "/objects") != NULL)
            {
              SoupSocket *sock;
              buffer_length = file_size/2;
              soup_message_headers_set_content_length (msg->response_headers, file_size);
              soup_message_headers_append (msg->response_headers,
                                           "Connection", "close");

              /* soup-message-io will wait for us to add
               * another chunk after the first, to fill out
               * the declared Content-Length. Instead, we
               * forcibly close the socket at that point.
               */
              sock = soup_client_context_get_socket (context);
              g_signal_connect (msg, "wrote-chunk", G_CALLBACK (close_socket), sock);
            }
          else
            buffer_length = file_size;

          if (have_ranges)
            {
              if (ranges_length > 0 && ranges[0].start >= file_size)
                {
                  soup_message_set_status (msg, SOUP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE);
                  soup_message_headers_free_ranges (msg->request_headers, ranges);
                  goto out;
                }
              soup_message_headers_free_ranges (msg->request_headers, ranges);
            }
          if (buffer_length > 0)
            {
              SoupBuffer *buffer;

              buffer = soup_buffer_new_with_owner (g_mapped_file_get_contents (mapping),
                                                   buffer_length,
                                                   g_mapped_file_ref (mapping),
                                                   (GDestroyNotify)g_mapped_file_unref);
              soup_message_body_append_buffer (msg->response_body, buffer);
              soup_buffer_free (buffer);
            }
        }
      else /* msg->method == SOUP_METHOD_HEAD */
        {
          g_autofree char *length = NULL;

          /* We could just use the same code for both GET and
           * HEAD (soup-message-server-io.c will fix things up).
           * But we'll optimize and avoid the extra I/O.
           */
          length = g_strdup_printf ("%lu", (gulong)stbuf.st_size);
          soup_message_headers_append (msg->response_headers,
                                       "Content-Length", length);
        }
      soup_message_set_status (msg, SOUP_STATUS_OK);
    }
 out:
  {
    guint status = 0;
    g_autofree gchar *reason = NULL;

    g_object_get (msg,
                  "status-code", &status,
                  "reason-phrase", &reason,
                  NULL);
    httpd_log (self, "  status: %s (%u)\n", reason, status);
  }
  return;
}
예제 #3
0
int
store (dt_imageio_module_data_t *sdata, const int imgid, dt_imageio_module_format_t *format, dt_imageio_module_data_t *fdata,
       const int num, const int total, const gboolean high_quality)
{
  gint tags = 0;
  int result=1;
  dt_storage_picasa_params_t *p=(dt_storage_picasa_params_t *)sdata;

  int fail = 0;
#ifdef _OPENMP // synch parallel store
  #pragma omp critical
#endif
  if( p->picasa_api->current_album == NULL )
    if( _picasa_api_create_album( p->picasa_api ) != 201 )
    {
      dt_control_log("failed to create picasa album");
      fail = 1;
    }

  if(fail) return 1;

  const char *ext = format->extension(fdata);

  // Let's upload image...

  /* construct a temporary file name */
  char fname[4096]= {0};
  dt_loc_get_tmp_dir (fname,4096);
  g_strlcat (fname,"/darktable.XXXXXX.",4096);
  g_strlcat(fname,ext,4096);

  char *caption="a image";
  char *description="";
  char *mime="image/jpeg";

  // Ok, maybe a dt_imageio_export_to_buffer would suit here !?
  gint fd=g_mkstemp(fname);
  fprintf(stderr,"tempfile: %s\n",fname);
  if(fd==-1)
  {
    dt_control_log("failed to create temporary image for picasa export");
    return 1;
  }
  close(fd);
  const dt_image_t *img = dt_image_cache_read_get(darktable.image_cache, imgid);
  caption = g_path_get_basename( img->filename );

  (g_strrstr(caption,"."))[0]='\0'; // Shop extension...

  GList *desc = dt_metadata_get(img->id, "Xmp.dc.description", NULL);
  if(desc != NULL)
  {
    description = desc->data;
  }
  dt_image_cache_read_release(darktable.image_cache, img);

  if(dt_imageio_export(imgid, fname, format, fdata, high_quality) != 0)
  {
    fprintf(stderr, "[imageio_storage_picasa] could not export to file: `%s'!\n", fname);
    dt_control_log(_("could not export to file `%s'!"), fname);
    result = 1;
    goto cleanup;
  }

  // Open the temp file and read image to memory
  GMappedFile *imgfile = g_mapped_file_new(fname,FALSE,NULL);
  int size = g_mapped_file_get_length( imgfile );
  gchar *data =g_mapped_file_get_contents( imgfile );

#ifdef _OPENMP
  #pragma omp critical
#endif
  {
  // Fetch the attached tags of image id if exported..
  if( p->export_tags == TRUE )
    tags = imgid;

  // Upload image to picasa
    if( _picasa_api_upload_photo( p->picasa_api, mime , data, size , caption, description, tags ) == 201 )
      result=0;
  }

  // Unreference the memorymapped file...
  g_mapped_file_unref( imgfile );

  // And remove from filesystem..
  unlink( fname );

cleanup:

  g_free( caption );
  if(desc)
  {
    g_free(desc->data);
    g_list_free(desc);
  }

  if(!result)
    dt_control_log(_("%d/%d exported to picasa webalbum"), num, total );
  return result;
}
예제 #4
0
GtkIconCache *
_gtk_icon_cache_new_for_path (const gchar *path)
{
  GtkIconCache *cache = NULL;
  GMappedFile *map;

  gchar *cache_filename;
  gint fd = -1;
  struct stat st;
  struct stat path_st;
  gchar *buffer = NULL;
  CacheInfo info;

   /* Check if we have a cache file */
  cache_filename = g_build_filename (path, "icon-theme.cache", NULL);

  GTK_NOTE (ICONTHEME, 
	    g_print ("look for cache in %s\n", path));

  if (g_stat (path, &path_st) < 0)
    goto done;

  /* Open the file and map it into memory */
  fd = g_open (cache_filename, O_RDONLY|_O_BINARY, 0);

  if (fd < 0)
    goto done;
  
  if (fstat (fd, &st) < 0 || st.st_size < 4)
    goto done;

  /* Verify cache is uptodate */
  if (st.st_mtime < path_st.st_mtime)
    {
      GTK_NOTE (ICONTHEME, 
		g_print ("cache outdated\n"));
      goto done; 
    }

  map = g_mapped_file_new (cache_filename, FALSE, NULL);

  if (!map)
    goto done;

  info.cache = g_mapped_file_get_contents (map);
  info.cache_size = g_mapped_file_get_length (map);
  info.n_directories = 0;
  info.flags = CHECK_OFFSETS|CHECK_STRINGS;

  if (!_gtk_icon_cache_validate (&info))
    {
      g_mapped_file_free (map);
      g_warning ("Icon cache '%s' is invalid\n", cache_filename);

      goto done;
    }
  
  GTK_NOTE (ICONTHEME, g_print ("found cache for %s\n", path));

  cache = g_new0 (GtkIconCache, 1);
  cache->ref_count = 1;
  cache->map = map;
  cache->buffer = g_mapped_file_get_contents (map);

 done:
  g_free (cache_filename);  
  if (fd >= 0)
    close (fd);

  return cache;
}
예제 #5
0
/**
 * gst_registry_binary_read_cache:
 * @registry: a #GstRegistry
 * @location: a filename
 *
 * Read the contents of the binary cache file at @location into @registry.
 *
 * Returns: %TRUE on success.
 */
gboolean
priv_gst_registry_binary_read_cache (GstRegistry * registry,
    const char *location)
{
  GMappedFile *mapped = NULL;
  gchar *contents = NULL;
  gchar *in = NULL;
  gsize size;
  GError *err = NULL;
  gboolean res = FALSE;
  guint32 filter_env_hash = 0;
  gint check_magic_result;
#ifndef GST_DISABLE_GST_DEBUG
  GTimer *timer = NULL;
  gdouble seconds;
#endif

  /* make sure these types exist */
  GST_TYPE_ELEMENT_FACTORY;
  GST_TYPE_TYPE_FIND_FACTORY;

#ifndef GST_DISABLE_GST_DEBUG
  timer = g_timer_new ();
#endif

  mapped = g_mapped_file_new (location, FALSE, &err);
  if (G_UNLIKELY (err != NULL)) {
    GST_INFO ("Unable to mmap file %s : %s", location, err->message);
    g_error_free (err);
    err = NULL;
  }

  if (mapped == NULL) {
    /* Error mmap-ing the cache, try a plain memory read */

    g_file_get_contents (location, &contents, &size, &err);
    if (err != NULL) {
      GST_INFO ("Unable to read file %s : %s", location, err->message);
#ifndef GST_DISABLE_GST_DEBUG
      g_timer_destroy (timer);
#endif
      g_error_free (err);
      return FALSE;
    }
  } else {
    /* This can't fail if g_mapped_file_new() succeeded */
    contents = g_mapped_file_get_contents (mapped);
    size = g_mapped_file_get_length (mapped);
  }

  /* in is a cursor pointer, we initialize it with the begin of registry and is updated on each read */
  in = contents;
  GST_DEBUG ("File data at address %p", in);
  if (G_UNLIKELY (size < sizeof (GstBinaryRegistryMagic))) {
    GST_ERROR ("No or broken registry header for file at %s", location);
    goto Error;
  }

  /* check if header is valid */
  if (G_UNLIKELY ((check_magic_result =
              gst_registry_binary_check_magic (&in, size)) < 0)) {

    if (check_magic_result == -1)
      GST_ERROR
          ("Binary registry type not recognized (invalid magic) for file at %s",
          location);
    goto Error;
  }

  if (!_priv_gst_registry_chunks_load_global_header (registry, &in,
          contents + size, &filter_env_hash)) {
    GST_ERROR ("Couldn't read global header chunk");
    goto Error;
  }

  if (filter_env_hash != priv_gst_plugin_loading_get_whitelist_hash ()) {
    GST_INFO_OBJECT (registry, "Plugin loading filter environment changed, "
        "ignoring plugin cache to force update with new filter environment");
    goto done;
  }

  /* check if there are plugins in the file */
  if (G_UNLIKELY (!(((gsize) in + sizeof (GstRegistryChunkPluginElement)) <
              (gsize) contents + size))) {
    GST_INFO ("No binary plugins structure to read");
    /* empty file, this is not an error */
  } else {
    gchar *end = contents + size;
    /* read as long as we still have space for a GstRegistryChunkPluginElement */
    for (;
        ((gsize) in + sizeof (GstRegistryChunkPluginElement)) <
        (gsize) contents + size;) {
      GST_DEBUG ("reading binary registry %" G_GSIZE_FORMAT "(%x)/%"
          G_GSIZE_FORMAT, (gsize) in - (gsize) contents,
          (guint) ((gsize) in - (gsize) contents), size);
      if (!_priv_gst_registry_chunks_load_plugin (registry, &in, end, NULL)) {
        GST_ERROR ("Problem while reading binary registry %s", location);
        goto Error;
      }
    }
  }

done:

#ifndef GST_DISABLE_GST_DEBUG
  g_timer_stop (timer);
  seconds = g_timer_elapsed (timer, NULL);
#endif

  GST_INFO ("loaded %s in %lf seconds", location, seconds);

  res = TRUE;
  /* TODO: once we re-use the pointers to registry contents, return here */

Error:
#ifndef GST_DISABLE_GST_DEBUG
  g_timer_destroy (timer);
#endif
  if (mapped) {
    g_mapped_file_unref (mapped);
  } else {
    g_free (contents);
  }
  return res;
}
예제 #6
0
파일: lcms.c 프로젝트: WilfR/Gimp-Matting
static gboolean
lcms_image_set_profile (gint32       image,
                        cmsHPROFILE  profile,
                        const gchar *filename,
                        gboolean     undo_group)
{
  g_return_val_if_fail (image != -1, FALSE);

  if (filename)
    {
      GimpParasite *parasite;
      GMappedFile  *file;
      GError       *error = NULL;

      file = g_mapped_file_new (filename, FALSE, &error);

      if (! file)
        {
          g_message ("%s", error->message);
          g_error_free (error);

          return FALSE;
        }

      /* check that this file is actually an ICC profile */
      if (! profile)
        {
          profile = cmsOpenProfileFromMem (g_mapped_file_get_contents (file),
                                           g_mapped_file_get_length (file));

          if (profile)
            {
              cmsCloseProfile (profile);
            }
          else
            {
              g_message (_("'%s' does not appear to be an ICC color profile"),
                         gimp_filename_to_utf8 (filename));
              return FALSE;
            }
        }

      if (undo_group)
        gimp_image_undo_group_start (image);

      parasite = gimp_parasite_new ("icc-profile",
                                    GIMP_PARASITE_PERSISTENT |
                                    GIMP_PARASITE_UNDOABLE,
                                    g_mapped_file_get_length (file),
                                    g_mapped_file_get_contents (file));

      g_mapped_file_unref (file);

      gimp_image_attach_parasite (image, parasite);
      gimp_parasite_free (parasite);
    }
  else
    {
      if (undo_group)
        gimp_image_undo_group_start (image);

      gimp_image_detach_parasite (image, "icc-profile");
    }

  gimp_image_detach_parasite (image, "icc-profile-name");

  if (undo_group)
    gimp_image_undo_group_end (image);

  return TRUE;
}
static bool startHttp(ResourceHandle* handle)
{
    ASSERT(handle);

    SoupSession* session = handle->defaultSession();
    ensureSessionIsInitialized(session);

    ResourceHandleInternal* d = handle->getInternal();

    ResourceRequest request(handle->request());
    KURL url(request.url());
    url.removeFragmentIdentifier();
    request.setURL(url);

    d->m_msg = request.toSoupMessage();
    if (!d->m_msg)
        return false;

    if(!handle->shouldContentSniff())
        soup_message_disable_feature(d->m_msg, SOUP_TYPE_CONTENT_SNIFFER);

    g_signal_connect(d->m_msg, "restarted", G_CALLBACK(restartedCallback), handle);
    g_signal_connect(d->m_msg, "got-headers", G_CALLBACK(gotHeadersCallback), handle);
    g_signal_connect(d->m_msg, "content-sniffed", G_CALLBACK(contentSniffedCallback), handle);
    g_signal_connect(d->m_msg, "got-chunk", G_CALLBACK(gotChunkCallback), handle);

#ifdef HAVE_LIBSOUP_2_29_90
    String firstPartyString = request.firstPartyForCookies().string();
    if (!firstPartyString.isEmpty()) {
        GOwnPtr<SoupURI> firstParty(soup_uri_new(firstPartyString.utf8().data()));
        soup_message_set_first_party(d->m_msg, firstParty.get());
    }
#endif
    g_object_set_data(G_OBJECT(d->m_msg), "resourceHandle", reinterpret_cast<void*>(handle));

    FormData* httpBody = d->m_request.httpBody();
    if (httpBody && !httpBody->isEmpty()) {
        size_t numElements = httpBody->elements().size();

        // handle the most common case (i.e. no file upload)
        if (numElements < 2) {
            Vector<char> body;
            httpBody->flatten(body);
            soup_message_set_request(d->m_msg, d->m_request.httpContentType().utf8().data(),
                                     SOUP_MEMORY_COPY, body.data(), body.size());
        } else {
            /*
             * we have more than one element to upload, and some may
             * be (big) files, which we will want to mmap instead of
             * copying into memory; TODO: support upload of non-local
             * (think sftp://) files by using GIO?
             */
            soup_message_body_set_accumulate(d->m_msg->request_body, FALSE);
            for (size_t i = 0; i < numElements; i++) {
                const FormDataElement& element = httpBody->elements()[i];

                if (element.m_type == FormDataElement::data)
                    soup_message_body_append(d->m_msg->request_body, SOUP_MEMORY_TEMPORARY, element.m_data.data(), element.m_data.size());
                else {
                    /*
                     * mapping for uploaded files code inspired by technique used in
                     * libsoup's simple-httpd test
                     */
                    GError* error = 0;
                    gchar* fileName = filenameFromString(element.m_filename);
                    GMappedFile* fileMapping = g_mapped_file_new(fileName, false, &error);

                    g_free(fileName);

                    if (error) {
                        g_error_free(error);
                        g_signal_handlers_disconnect_matched(d->m_msg, G_SIGNAL_MATCH_DATA,
                                                             0, 0, 0, 0, handle);
                        g_object_unref(d->m_msg);
                        d->m_msg = 0;

                        return false;
                    }

                    SoupBuffer* soupBuffer = soup_buffer_new_with_owner(g_mapped_file_get_contents(fileMapping),
                                                                        g_mapped_file_get_length(fileMapping),
                                                                        fileMapping,
#if GLIB_CHECK_VERSION(2, 21, 3)
                                                                        reinterpret_cast<GDestroyNotify>(g_mapped_file_unref));
#else
                                                                        reinterpret_cast<GDestroyNotify>(g_mapped_file_free));
#endif
                    soup_message_body_append_buffer(d->m_msg->request_body, soupBuffer);
                    soup_buffer_free(soupBuffer);
                }
            }
        }
    }
예제 #8
0
int
main (int argc, char *argv[])
{
  App *app = &s_app;
  GError *error = NULL;
  GstBus *bus;

  gst_init (&argc, &argv);

  GST_DEBUG_CATEGORY_INIT (appsrc_playbin_debug, "appsrc-playbin", 0,
      "appsrc playbin example");

  if (argc < 2) {
    g_print ("usage: %s <filename>\n", argv[0]);
    return -1;
  }

  /* try to open the file as an mmapped file */
  app->file = g_mapped_file_new (argv[1], FALSE, &error);
  if (error) {
    g_print ("failed to open file: %s\n", error->message);
    g_error_free (error);
    return -2;
  }
  /* get some vitals, this will be used to read data from the mmapped file and
   * feed it to appsrc. */
  app->length = g_mapped_file_get_length (app->file);
  app->data = (guint8 *) g_mapped_file_get_contents (app->file);
  app->offset = 0;

  /* create a mainloop to get messages */
  app->loop = g_main_loop_new (NULL, TRUE);

  app->playbin = gst_element_factory_make ("playbin2", NULL);
  g_assert (app->playbin);

  bus = gst_pipeline_get_bus (GST_PIPELINE (app->playbin));

  /* add watch for messages */
  gst_bus_add_watch (bus, (GstBusFunc) bus_message, app);

  /* set to read from appsrc */
  g_object_set (app->playbin, "uri", "appsrc://", NULL);

  /* get notification when the source is created so that we get a handle to it
   * and can configure it */
  g_signal_connect (app->playbin, "deep-notify::source",
      (GCallback) found_source, app);

  /* go to playing and wait in a mainloop. */
  gst_element_set_state (app->playbin, GST_STATE_PLAYING);

  /* this mainloop is stopped when we receive an error or EOS */
  g_main_loop_run (app->loop);

  GST_DEBUG ("stopping");

  gst_element_set_state (app->playbin, GST_STATE_NULL);

  /* free the file */
  g_mapped_file_free (app->file);

  gst_object_unref (bus);
  g_main_loop_unref (app->loop);

  return 0;
}
예제 #9
0
파일: sfx.c 프로젝트: billy3321/lazybuntu
int main(int argc, char** argv)
{
    GError *err = NULL;
    GMappedFile *map;
    char *buf = NULL, *pbuf = NULL, *data = NULL, *end;
    gsize len = 0;
    char *extract_path;

    gtk_init( &argc, &argv );

    /* load the executable file itself */
    map = g_mapped_file_new( argv[0], FALSE, NULL );
    if( !map )
        return 1;

    buf = g_mapped_file_get_contents(map);
    len = g_mapped_file_get_length( map );

    /* find the data */
    magic[0] = '_';

    for( pbuf = buf, end = buf + len - magic_len; G_LIKELY( pbuf < end ); ++pbuf )
    {
        if( G_UNLIKELY( 0 == memcmp( pbuf, magic, magic_len ) ) )
        {
            data = pbuf + magic_len + 1;
            break;
        }
    }

    if( G_UNLIKELY( ! data ) )
    {
        g_mapped_file_free( map );
        show_error( "檔案損毀,請重新下載。" );
        return 1;   /* error!  no data found */
    }

    len -= (data - buf);    /* skip ourself */

    extract_path = g_strconcat( "/tmp/Lazybuntu-", g_get_user_name(), NULL );
    g_mkdir_with_parents( extract_path, 0755 ); /* FIXME: is 0755 OK? */

    cmdv[3] = extract_path;
    if( g_spawn_async_with_pipes( NULL, cmdv, NULL, G_SPAWN_SEARCH_PATH|G_SPAWN_DO_NOT_REAP_CHILD, NULL, NULL, &pid, &std_in, NULL, NULL, &err ) )
    {
        int status = 0;
        write( std_in, data, len );
        close( std_in );
        waitpid( pid, &status, 0 );
        g_spawn_close_pid( pid );
    }
    else
    {
        show_error( err->message );   
        g_error_free( err );
    }
    g_mapped_file_free( map );

    g_chdir( extract_path );
    g_free( extract_path );
    g_chdir( "Lazybuntu" );
    execl( "Lazybuntu", NULL );

    show_error("錯誤,無法執行 Lazybuntu!");

    return 0;
}
예제 #10
0
gboolean
youtube_proxy_upload_async (YoutubeProxy              *self,
                            const gchar               *filename,
                            GHashTable                *fields,
                            gboolean                   incomplete,
                            YoutubeProxyUploadCallback callback,
                            GObject                   *weak_object,
                            gpointer                   userdata,
                            GError                   **error)
{
  SoupMultipart *mp;
  SoupMessage *message;
  SoupMessageHeaders *part_headers;
  SoupBuffer *sb;
  gchar *content_type;
  gchar *atom_xml;
  GMappedFile *map;
  YoutubeProxyUploadClosure *closure;

  map = g_mapped_file_new (filename, FALSE, error);
  if (*error != NULL) {
    g_warning ("Error opening file %s: %s", filename, (*error)->message);
    return FALSE;
  }

  mp = soup_multipart_new ("multipart/related");

  atom_xml = _construct_upload_atom_xml (fields, incomplete);

  sb = soup_buffer_new_with_owner (atom_xml,
                                   strlen(atom_xml),
                                   atom_xml,
                                   (GDestroyNotify) g_free);

  part_headers = soup_message_headers_new (SOUP_MESSAGE_HEADERS_MULTIPART);

  soup_message_headers_append (part_headers, "Content-Type",
                               "application/atom+xml; charset=UTF-8");


  soup_multipart_append_part (mp, part_headers, sb);

  soup_buffer_free (sb);

  content_type = g_content_type_guess (
      filename,
      (const guchar*) g_mapped_file_get_contents (map),
      g_mapped_file_get_length (map),
      NULL);

  sb = soup_buffer_new_with_owner (g_mapped_file_get_contents (map),
                                   g_mapped_file_get_length (map),
                                   map,
                                   (GDestroyNotify) g_mapped_file_unref);

  soup_message_headers_replace (part_headers, "Content-Type", content_type);

  soup_multipart_append_part (mp, part_headers, sb);

  soup_buffer_free (sb);

  soup_message_headers_free (part_headers);

  message = soup_form_request_new_from_multipart (UPLOAD_URL, mp);

  soup_multipart_free (mp);

  _set_upload_headers (self, message->request_headers, filename);

  closure = _upload_async_closure_new (self, callback, message, weak_object,
                                       userdata);

  g_signal_connect (message,
                    "wrote-body-data",
                    (GCallback) _message_wrote_data_cb,
                    closure);


  _rest_proxy_queue_message (REST_PROXY (self), message, _upload_completed_cb,
                             closure);

  return TRUE;
}
예제 #11
0
int main(int argc, char *argv[]) {
	
	GMappedFile *program_file=0;
	gchar* prog_ptr=0;
	const gchar* ssk_sig=SSK_SIGNATURE;
	GError *error=0;
	bool isFound=0;
	int i,j;
	g_type_init();
	if(argc!=3) {
		USAGE;
		exit(1);
	}
		
	program_file = g_mapped_file_new(argv[1], /* writable */ 1, &error);
	if( !program_file ) {
		g_printf("Can not open file: %s", error->message);
		g_error_free(error);
		USAGE;
		exit(2);
	}
	prog_ptr=g_mapped_file_get_contents(program_file);
	for(i=0; i<g_mapped_file_get_length(program_file) && !isFound; i++)	{
		if(prog_ptr[i]==ssk_sig[0]) {
			for(j=0; j<sizeof(SSK_SIGNATURE); j++)	{
				if(ssk_sig[j]==0) {
					isFound=1;
					break;
				}
				if(prog_ptr[i+j]!=ssk_sig[j]) {
					break;
				}
			}
		}
	}
	i+=sizeof(SSK_SIGNATURE)-2;
	if(!isFound) {
		g_printf("Can not find special signature in program.\n");
		USAGE;
		exit(3);
	}
	
	GPtrArray* serials = get_serial_array(&error);
	if( !serials ) {
		g_printf("%s\n", error->message);
		g_error_free(error);
		exit(4);
	}

	gchar* first_ser = g_ptr_array_index(serials,0);
		
	// select key here;
	for(j=0; first_ser[j]!=0; j++)	{
		prog_ptr[i+j]= first_ser[j];
	}
	prog_ptr[i+j]=0;
	FILE* outprog=fopen(argv[2], "w");
	if(!outprog) {
		g_printf("open file %s failed\n",argv[2]);
		exit(5);
	}
	fwrite(prog_ptr, 1, g_mapped_file_get_length(program_file), outprog);
	fclose(outprog);
	g_mapped_file_free(program_file);
	
	return 0;
}
예제 #12
0
static void
_twitpic_upload_photo (SwPhotoUploadIface    *self,
                       const gchar           *filename,
                       GHashTable            *params,
                       DBusGMethodInvocation *context)
{
  SwServiceTwitter *twitter = SW_SERVICE_TWITTER (self);
  SwServiceTwitterPrivate *priv = twitter->priv;
  GError *error = NULL;
  RestProxyCall *call;
  RestParam *param;
  GMappedFile *map;
  char *title, *content_type;
  int opid;

  map = g_mapped_file_new (filename, FALSE, &error);
  if (error) {
    dbus_g_method_return_error (context, error);
    return;
  }

  /* Use the title as the tweet, and if the title isn't specified use the
     filename */
  title = g_hash_table_lookup (params, "title");
  if (title == NULL) {
    title = g_path_get_basename (filename);
  }

  call = rest_proxy_new_call (priv->twitpic_proxy);
  rest_proxy_call_set_function (call, "upload.xml");

  rest_proxy_call_add_params (call,
                              "key", sw_keystore_get_key ("twitpic"),
                              "message", title,
                              NULL);
  g_free (title);

  content_type = g_content_type_guess (filename,
                                       (const guchar*) g_mapped_file_get_contents (map),
                                       g_mapped_file_get_length (map),
                                       NULL);

  param = rest_param_new_with_owner ("media",
                                     g_mapped_file_get_contents (map),
                                     g_mapped_file_get_length (map),
                                     content_type,
                                     filename,
                                     map,
                                     (GDestroyNotify)g_mapped_file_unref);
  rest_proxy_call_add_param_full (call, param);

  g_free (content_type);

  opid = sw_next_opid ();

  rest_proxy_call_upload (call,
                          on_upload_cb,
                          (GObject *)self,
                          GINT_TO_POINTER (opid),
                          NULL);
  sw_photo_upload_iface_return_from_upload_photo (context, opid);
}
예제 #13
0
파일: vikgoto.c 프로젝트: guyou/viking
/**
 * Automatic attempt to find out where you are using:
 *   1. http://www.geoplugin.com ++
 *   2. if not specific enough fallback to using the default goto tool with a country name
 * ++ Using returned JSON information
 *  c.f. with googlesearch.c - similar implementation is used here
 *
 * returns:
 *   0 if failed to locate anything
 *   1 if exact latitude/longitude found
 *   2 if position only as precise as a city
 *   3 if position only as precise as a country
 * @name: Contains the name of place found. Free this string after use.
 */
gint a_vik_goto_where_am_i ( VikViewport *vvp, struct LatLon *ll, gchar **name )
{
  gint result = 0;
  *name = NULL;

  gchar *tmpname = a_download_uri_to_tmp_file ( "http://www.geoplugin.net/json.gp", NULL );
  //gchar *tmpname = g_strdup ("../test/www.geoplugin.net-slash-json.gp.result");
  if (!tmpname) {
    return result;
  }

  ll->lat = 0.0;
  ll->lon = 0.0;

  gchar *pat;
  GMappedFile *mf;
  gchar *ss;
  gint fragment_len;

  gchar lat_buf[32], lon_buf[32];
  lat_buf[0] = lon_buf[0] = '\0';
  gchar *country = NULL;
  gchar *city = NULL;

  if ((mf = g_mapped_file_new(tmpname, FALSE, NULL)) == NULL) {
    g_critical(_("couldn't map temp file"));
    goto tidy;
  }

  gsize len = g_mapped_file_get_length(mf);
  gchar *text = g_mapped_file_get_contents(mf);

  if ((pat = g_strstr_len(text, len, JSON_COUNTRY_PATTERN))) {
    pat += strlen(JSON_COUNTRY_PATTERN);
    fragment_len = 0;
    ss = pat;
    while (*pat != '"') {
      fragment_len++;
      pat++;
    }
    country = g_strndup(ss, fragment_len);
  }

  if ((pat = g_strstr_len(text, len, JSON_CITY_PATTERN))) {
    pat += strlen(JSON_CITY_PATTERN);
    fragment_len = 0;
    ss = pat;
    while (*pat != '"') {
      fragment_len++;
      pat++;
    }
    city = g_strndup(ss, fragment_len);
  }

  if ((pat = g_strstr_len(text, len, JSON_LATITUDE_PATTERN))) {
    pat += strlen(JSON_LATITUDE_PATTERN);
    ss = lat_buf;
    if (*pat == '-')
      *ss++ = *pat++;
    while ((ss < (lat_buf + sizeof(lat_buf))) && (pat < (text + len)) &&
	   (g_ascii_isdigit(*pat) || (*pat == '.')))
      *ss++ = *pat++;
    *ss = '\0';
    ll->lat = g_ascii_strtod(lat_buf, NULL);
  }

  if ((pat = g_strstr_len(text, len, JSON_LONGITUDE_PATTERN))) {
    pat += strlen(JSON_LONGITUDE_PATTERN);
    ss = lon_buf;
    if (*pat == '-')
      *ss++ = *pat++;
    while ((ss < (lon_buf + sizeof(lon_buf))) && (pat < (text + len)) &&
	   (g_ascii_isdigit(*pat) || (*pat == '.')))
      *ss++ = *pat++;
    *ss = '\0';
    ll->lon = g_ascii_strtod(lon_buf, NULL);
  }

  if ( ll->lat != 0.0 && ll->lon != 0.0 ) {
    if ( ll->lat > -90.0 && ll->lat < 90.0 && ll->lon > -180.0 && ll->lon < 180.0 ) {
      // Found a 'sensible' & 'precise' location
      result = 1;
      *name = g_strdup ( _("Locality") ); //Albeit maybe not known by an actual name!
    }
  }
  else {
    // Hopefully city name is unique enough to lookup position on
    // For American places the service may append the State code on the end
    // But if the country code is not appended if could easily get confused
    //  e.g. 'Portsmouth' could be at least
    //   Portsmouth, Hampshire, UK or
    //   Portsmouth, Viginia, USA.

    // Try city name lookup
    if ( city ) {
      g_debug ( "%s: found city %s", __FUNCTION__, city );
      if ( strcmp ( city, "(Unknown city)" ) != 0 ) {
        VikCoord new_center;
        if ( vik_goto_place ( NULL, vvp, city, &new_center ) ) {
          // Got something
          vik_coord_to_latlon ( &new_center, ll );
          result = 2;
          *name = city;
          goto tidy;
        }
      }
    }

    // Try country name lookup
    if ( country ) {
      g_debug ( "%s: found country %s", __FUNCTION__, country );
      if ( strcmp ( country, "(Unknown Country)" ) != 0 ) {
        VikCoord new_center;
        if ( vik_goto_place ( NULL, vvp, country, &new_center ) ) {
          // Finally got something
          vik_coord_to_latlon ( &new_center, ll );
          result = 3;
          *name = country;
          goto tidy;
        }
      }
    }
  }
  
 tidy:
  g_mapped_file_unref ( mf );
  (void)g_remove ( tmpname );
  g_free ( tmpname );
  return result;
}
예제 #14
0
bool ResourceHandle::startHttp(String urlString)
{
    SoupSession* session = defaultSession();
    ensureSessionIsInitialized(session);

    d->m_msg = request().toSoupMessage();
    g_signal_connect(d->m_msg, "restarted", G_CALLBACK(restartedCallback), this);
    g_signal_connect(d->m_msg, "got-headers", G_CALLBACK(gotHeadersCallback), this);
    g_signal_connect(d->m_msg, "content-sniffed", G_CALLBACK(contentSniffedCallback), this);
    g_signal_connect(d->m_msg, "got-chunk", G_CALLBACK(gotChunkCallback), this);

    g_object_set_data(G_OBJECT(d->m_msg), "resourceHandle", reinterpret_cast<void*>(this));

    FormData* httpBody = d->m_request.httpBody();
    if (httpBody && !httpBody->isEmpty()) {
        size_t numElements = httpBody->elements().size();

        // handle the most common case (i.e. no file upload)
        if (numElements < 2) {
            Vector<char> body;
            httpBody->flatten(body);
            soup_message_set_request(d->m_msg, d->m_request.httpContentType().utf8().data(),
                                     SOUP_MEMORY_COPY, body.data(), body.size());
        } else {
            /*
             * we have more than one element to upload, and some may
             * be (big) files, which we will want to mmap instead of
             * copying into memory; TODO: support upload of non-local
             * (think sftp://) files by using GIO?
             */
            soup_message_body_set_accumulate(d->m_msg->request_body, FALSE);
            for (size_t i = 0; i < numElements; i++) {
                const FormDataElement& element = httpBody->elements()[i];

                if (element.m_type == FormDataElement::data)
                    soup_message_body_append(d->m_msg->request_body, SOUP_MEMORY_TEMPORARY, element.m_data.data(), element.m_data.size());
                else {
                    /*
                     * mapping for uploaded files code inspired by technique used in
                     * libsoup's simple-httpd test
                     */
                    GError* error = 0;
                    gchar* fileName = filenameFromString(element.m_filename);
                    GMappedFile* fileMapping = g_mapped_file_new(fileName, false, &error);

                    g_free(fileName);

                    if (error) {
                        ResourceError resourceError(g_quark_to_string(SOUP_HTTP_ERROR),
                                                    d->m_msg->status_code,
                                                    urlString,
                                                    String::fromUTF8(error->message));
                        g_error_free(error);

                        d->client()->didFail(this, resourceError);

                        g_signal_handlers_disconnect_matched(d->m_msg, G_SIGNAL_MATCH_DATA,
                                                             0, 0, 0, 0, this);
                        g_object_unref(d->m_msg);
                        d->m_msg = 0;

                        return false;
                    }

                    SoupBuffer* soupBuffer = soup_buffer_new_with_owner(g_mapped_file_get_contents(fileMapping),
                                                                        g_mapped_file_get_length(fileMapping),
                                                                        fileMapping,
#if GLIB_CHECK_VERSION(2, 21, 3)
                                                                        reinterpret_cast<GDestroyNotify>(g_mapped_file_unref));
#else
                                                                        reinterpret_cast<GDestroyNotify>(g_mapped_file_free));
#endif
                    soup_message_body_append_buffer(d->m_msg->request_body, soupBuffer);
                    soup_buffer_free(soupBuffer);
                }
            }
        }
    }
예제 #15
0
/**
 * dh_assistant_view_set_link:
 * @view: an devhelp assistant view
 * @link: the #DhLink
 *
 * Open @link in the assistant view, if %NULL the view will be blanked.
 *
 * Return value: %TRUE if the requested link is open, %FALSE otherwise.
 **/
gboolean
dh_assistant_view_set_link (DhAssistantView *view,
                            DhLink          *link)
{
        DhAssistantViewPriv *priv;
        gchar               *uri;
        const gchar         *anchor;
        gchar               *filename;
        GMappedFile         *file;
        const gchar         *contents;
        gsize                length;
        gchar               *key;
        gsize                key_length;
        gsize                offset = 0;
        const gchar         *start;
        const gchar         *end;

        g_return_val_if_fail (DH_IS_ASSISTANT_VIEW (view), FALSE);

        priv = GET_PRIVATE (view);

        if (priv->link == link) {
                return TRUE;
        }

        if (priv->link) {
                dh_link_unref (priv->link);
                priv->link = NULL;
        }

        if (link) {
                link = dh_link_ref (link);
        } else {
                webkit_web_view_load_uri (WEBKIT_WEB_VIEW (view), "about:blank");
                return TRUE;
        }

        uri = dh_link_get_uri (link);
        anchor = strrchr (uri, '#');
        if (anchor) {
                filename = g_strndup (uri, anchor - uri);
                anchor++;
                g_free (uri);
        } else {
                g_free (uri);
                return FALSE;
        }

        if (g_str_has_prefix (filename, "file://"))
            offset = 7;

        file = g_mapped_file_new (filename + offset, FALSE, NULL);
        if (!file) {
                g_free (filename);
                return FALSE;
        }

        contents = g_mapped_file_get_contents (file);
        length = g_mapped_file_get_length (file);

        key = g_strdup_printf ("<a name=\"%s\"", anchor);
        key_length = strlen (key);

        start = find_in_buffer (contents, key, length, key_length);
        g_free (key);

        end = NULL;

        if (start) {
                const gchar *start_key;
                const gchar *end_key;

                length -= start - contents;

                start_key = "<pre class=\"programlisting\">";

                start = find_in_buffer (start,
                                        start_key,
                                        length,
                                        strlen (start_key));

                end_key = "<div class=\"refsect";

                if (start) {
                        end = find_in_buffer (start, end_key,
                                              length - strlen (start_key),
                                              strlen (end_key));
                        if (!end) {
                                end_key = "<div class=\"footer";
                                end = find_in_buffer (start, end_key,
                                                      length - strlen (start_key),
                                                      strlen (end_key));
                        }
                }
        }

        if (start && end) {
                gchar       *buf;
                gboolean     break_line;
                const gchar *function;
                gchar       *stylesheet;
                gchar       *javascript;
                gchar       *html;

                buf = g_strndup (start, end-start);

                /* Try to reformat function signatures so they take less
                 * space and look nicer. Don't reformat things that don't
                 * look like functions.
                 */
                switch (dh_link_get_link_type (link)) {
                case DH_LINK_TYPE_FUNCTION:
                        break_line = TRUE;
                        function = "onload=\"reformatSignature()\"";
                        break;
                case DH_LINK_TYPE_MACRO:
                        break_line = TRUE;
                        function = "onload=\"cleanupSignature()\"";
                        break;
                default:
                        break_line = FALSE;
                        function = "";
                        break;
                }

                if (break_line) {
                        gchar *name;

                        name = strstr (buf, dh_link_get_name (link));
                        if (name && name > buf) {
                                name[-1] = '\n';
                        }
                }

                stylesheet = dh_util_build_data_filename ("devhelp",
                                                          "assistant",
                                                          "assistant.css",
                                                          NULL);
                javascript = dh_util_build_data_filename ("devhelp",
                                                          "assistant",
                                                          "assistant.js",
                                                          NULL);

                html = g_strdup_printf (
                        "<html>"
                        "<head>"
                        "<link rel=\"stylesheet\" type=\"text/css\" href=\"file://%s\"/>"
                        "<script src=\"file://%s\"></script>"
                        "</head>"
                        "<body %s>"
                        "<div class=\"title\">%s: <a href=\"%s\">%s</a></div>"
                        "<div class=\"subtitle\">%s %s</div>"
                        "<div class=\"content\">%s</div>"
                        "</body>"
                        "</html>",
                        stylesheet,
                        javascript,
                        function,
                        dh_link_get_type_as_string (link),
                        dh_link_get_uri (link),
                        dh_link_get_name (link),
                        _("Book:"),
                        dh_link_get_book_name (link),
                        buf);
                g_free (buf);

                g_free (stylesheet);
                g_free (javascript);

                priv->snippet_loaded = FALSE;
                webkit_web_view_load_string (
                        WEBKIT_WEB_VIEW (view),
                        html,
                        "text/html",
                        NULL,
                        filename);

                g_free (html);
        } else {
                webkit_web_view_load_uri (WEBKIT_WEB_VIEW (view), "about:blank");
        }

#if GLIB_CHECK_VERSION(2,21,3)
        g_mapped_file_unref (file);
#else
        g_mapped_file_free (file);
#endif

        g_free (filename);

        return TRUE;
}
예제 #16
0
/**
 *  step.1: https://developers.google.com/photos/library/guides/upload-media#uploading-bytes
 *  step.2: https://developers.google.com/photos/library/guides/upload-media#creating-media-item
 */
static const gchar *gphoto_upload_photo_to_album(dt_gphoto_context_t *ctx, gchar *albumid, gchar *fname,
                                                 gchar *title, gchar *summary, const int imgid)
{
  // step.1 : upload raw data

  gchar *basename = g_path_get_basename(fname);

  JsonObject *response = NULL;
  gchar *photo_id = NULL;
  gchar *upload_token = NULL;

  gchar *filename = dt_util_dstrcat(NULL, "X-Goog-Upload-File-Name: %s", basename);
  g_free(basename);

  struct curl_slist *headers = curl_slist_append(NULL, "Content-type: application/octet-stream");
  headers = curl_slist_append(headers, filename);
  headers = curl_slist_append(headers, "X-Goog-Upload-Protocol: raw");

  // Open the temp file and read image to memory
  GMappedFile *imgfile = g_mapped_file_new(fname, FALSE, NULL);
  const int size = g_mapped_file_get_length(imgfile);
  gchar *data = g_mapped_file_get_contents(imgfile);

  response = gphoto_query_post(ctx, GOOGLE_GPHOTO "v1/uploads", headers, NULL, data, size);

  if(!response)
  {
    // all good, the body is the upload-token
    upload_token = g_strdup(ctx->response->str);
  }
  else
    return NULL;

  // step.2 : add raw data into an album

  headers = NULL;

  headers = curl_slist_append(headers, "Content-type: application/json");

  gchar *jbody = dt_util_dstrcat(NULL, "{ \"albumId\": \"%s\", "
                                         "\"newMediaItems\": [ "
                                           "{ \"description\": \"%s\", "
                                           "  \"simpleMediaItem\": { \"uploadToken\": \"%s\"} "
                                           "} ] }", albumid, summary, upload_token);

  response = gphoto_query_post(ctx, GOOGLE_GPHOTO "v1/mediaItems:batchCreate", headers, NULL, jbody, strlen(jbody));

  g_free(jbody);

  // check that the upload was correct and return the photo_id

  if(response)
  {
    if(json_object_has_member(response, "newMediaItemResults"))
    {
      JsonArray *results = json_object_get_array_member(response, "newMediaItemResults");
      // get first element, we have uploaded a single pciture
      JsonObject *root = json_array_get_object_element(results, 0);
      JsonObject *o = root;
      if(json_object_has_member(o, "status"))
      {
        o = json_node_get_object(json_object_get_member(o, "status"));
        if(json_object_has_member(o, "message"))
        {
          if(g_strcmp0(json_object_get_string_member(o, "message"), "OK"))
            return NULL;
        }
        else
          return NULL;
      }
      else
        return NULL;

      if(json_object_has_member(root, "mediaItem"))
      {
        o = json_node_get_object(json_object_get_member(root, "mediaItem"));
        if(json_object_has_member(o, "id"))
          photo_id = g_strdup(json_object_get_string_member(o, "id"));
      }
    }
  }

  return photo_id;
}
static gboolean
gda_data_model_dir_set_values (GdaDataModel *model, gint row, GList *values, GError **error)
{
	GdaDataModelDir *imodel;
	GList *list;
	gint col;
	FileRow *frow;
	gboolean has_changed = FALSE;

	g_return_val_if_fail (GDA_IS_DATA_MODEL_DIR (model), FALSE);
	g_return_val_if_fail (row >= 0, FALSE);
	imodel = (GdaDataModelDir *) model;
	g_return_val_if_fail (imodel->priv, FALSE);
	if (!values)
		return TRUE;

	if ((guint)row >= imodel->priv->rows->len) {
		gchar *str;
		if (imodel->priv->rows->len > 0)
			str = g_strdup_printf (_("Row %d out of range (0-%d)"), row,
					       imodel->priv->rows->len - 1);
		else
			str = g_strdup_printf (_("Row %d not found (empty data model)"), row);
		add_error (imodel, str);
		g_set_error (error, GDA_DATA_MODEL_ERROR, GDA_DATA_MODEL_ROW_OUT_OF_RANGE_ERROR,
			     "%s", str);
		g_free (str);
                return FALSE;
        }

	frow =  g_ptr_array_index (imodel->priv->rows, row);

	for (col = 0, list = values; list; list = list->next, col++) {
		GValue *value = (GValue *) list->data;
		const GValue *cvalue = gda_data_model_get_value_at (model, col, row, error);
		if (!cvalue)
			return FALSE;
		if (!value || !gda_value_compare (value, cvalue))
			continue;

		switch (col) {
		case COL_SIZE:
		case COL_MIME:
		case COL_MD5SUM:
		default:
			add_error (imodel, _("Column cannot be modified"));
			g_set_error (error, GDA_DATA_MODEL_ERROR, GDA_DATA_MODEL_ACCESS_ERROR,
				     "%s", _("Column cannot be modified"));
			return FALSE;
		case COL_DIRNAME: {
			/* check that the new dir still starts with the basedir */
			const gchar *new_path;
			gchar *old_path;
			gint len, base_len;

			new_path = value ? g_value_get_string (value) : "";
			len = strlen (new_path);
			base_len = strlen (imodel->priv->basedir);
			if ((len < base_len) ||
			    (strncmp (new_path, imodel->priv->basedir, base_len))) {
				add_error (imodel,
					   _("New path must be a subpath of the base directory"));
				g_set_error (error, GDA_DATA_MODEL_ERROR, GDA_DATA_MODEL_ACCESS_ERROR,
					     "%s",
					     _("New path must be a subpath of the base directory"));
				return FALSE;
			}

			old_path = compute_dirname (imodel, frow);
			if (dir_equal (new_path, old_path)) {
				g_free (old_path);
				g_print ("Paths are equal...\n");
				break;
			}

			if (!g_mkdir_with_parents (new_path, 0755)) {
				gchar *new_filename;
				GMappedFile *old_file;
				gboolean allok = FALSE;
				gchar *filename;

				new_filename = g_build_filename (new_path,
								 frow->raw_filename_value ? frow->raw_filename_value :
								 g_value_get_string (frow->filename_value), NULL);
				filename = compute_filename (imodel, frow);
				old_file = g_mapped_file_new (filename, FALSE, NULL);
				if (old_file) {
					if (g_file_set_contents (new_filename, g_mapped_file_get_contents (old_file),
								 g_mapped_file_get_length (old_file), NULL)) {
						g_unlink (filename);
						allok = TRUE;

						if (frow->data_value) {
							GdaBlob *blob;
							blob = (GdaBlob *) gda_value_get_blob (frow->data_value);
							if (blob && blob->op)
								_gda_dir_blob_set_filename (GDA_DIR_BLOB_OP (blob->op),
											   new_filename);
						}
					}
					g_mapped_file_unref (old_file);
				}
				if (!allok) {
					gchar *str;
					str = g_strdup_printf (_("Could not rename file '%s' to '%s'"),
							       filename, new_filename);
					add_error (imodel, str);
					g_set_error (error,
						     GDA_DATA_MODEL_ERROR, GDA_DATA_MODEL_ACCESS_ERROR,
						     "%s", str);
					g_free (str);
					g_free (new_filename);
					g_free (filename);
					g_free (old_path);
					return FALSE;
				}
				else {
					/* renaming succeeded => update FileRow */
#ifndef G_OS_WIN32
					g_rmdir (old_path);
#endif
					g_free (frow->reldir);
					frow->reldir = g_strdup (new_path + base_len);
				}
				g_free (filename);
				g_free (new_filename);
				has_changed = TRUE;
			}
			else {
				gchar *str;
				str = g_strdup_printf (_("Could not create directory '%s'"), new_path);
				add_error (imodel, str);
				g_set_error (error, GDA_DATA_MODEL_ERROR, GDA_DATA_MODEL_ACCESS_ERROR,
					     "%s", str);
				g_free (str);
				g_free (old_path);
				return FALSE;
			}
			g_free (old_path);
			break;
		}
		case COL_FILENAME: {
			gchar *new_filename;
			gchar *filename;

			new_filename = g_build_filename (imodel->priv->basedir,
							 frow->reldir,
							 g_value_get_string (value), NULL);
			filename = compute_filename (imodel, frow);
			if (g_rename (filename, new_filename)) {
				gchar *str;
				str = g_strdup_printf (_("Could not rename file '%s' to '%s'"), filename, new_filename);
				add_error (imodel, str);
				g_set_error (error, GDA_DATA_MODEL_ERROR, GDA_DATA_MODEL_ACCESS_ERROR,
					     "%s", str);
				g_free (str);
				g_free (new_filename);
				g_free (filename);
				return FALSE;
			}
			else {
				/* renaming succeeded => update FileRow */
				gda_value_free (frow->filename_value);
				frow->filename_value = gda_value_copy (value);
				if (frow->raw_filename_value) {
					g_free (frow->raw_filename_value);
					frow->raw_filename_value = g_strdup (g_value_get_string (value));
				}
				if (frow->data_value) {
					GdaBlob *blob;
					blob = (GdaBlob *) gda_value_get_blob (frow->data_value);
					if (blob && blob->op)
						_gda_dir_blob_set_filename (GDA_DIR_BLOB_OP (blob->op),
									   new_filename);
				}
			}
			g_free (new_filename);
			g_free (filename);
			has_changed = TRUE;
			break;
		}
		case COL_DATA: {
			GdaBlob *blob = NULL;
			if (gda_value_isa (value, GDA_TYPE_BLOB)) {
				blob = (GdaBlob *) gda_value_get_blob (value);
			}
			else if (gda_value_isa (value, GDA_TYPE_BINARY)) {
				blob = (GdaBlob *) gda_value_get_binary (value);
			}
			else if (gda_value_is_null (value)) {
				/* create a new empty blob */
				blob = g_new0 (GdaBlob, 1);
			}

			if (blob) {
				GdaBlobOp *op;
				gchar *filename;
				filename = compute_filename (imodel, frow);
				op = _gda_dir_blob_op_new (filename);
				if (gda_blob_op_write_all (op, blob) < 0) {
					gchar *str;
					str = g_strdup_printf (_("Could not overwrite contents of file '%s'"), filename);
					add_error (imodel, str);
					g_set_error (error, GDA_DATA_MODEL_ERROR,
						     GDA_DATA_MODEL_ACCESS_ERROR,
						     "%s", str);
					g_free (str);
					g_object_unref (op);
					g_free (filename);
					return FALSE;
				}
				g_object_unref (op);
				if (gda_value_is_null (value))
					g_free (blob);
				has_changed = FALSE;
				has_changed = update_file_size (frow, filename);
				has_changed = update_file_md5sum (frow, filename) || has_changed;
				has_changed = update_file_mime (frow, filename) || has_changed;
				g_free (filename);
			}
			else {
				add_error (imodel, _("Wrong type of data"));
				g_set_error (error, GDA_DATA_MODEL_ERROR, GDA_DATA_MODEL_ACCESS_ERROR,
					     "%s", _("Wrong type of data"));
				return FALSE;
			}
			break;
		}
		}
	}

	if (has_changed)
		/* signal changes to data model */
		gda_data_model_row_updated ((GdaDataModel *) model, row);

	return TRUE;
}
예제 #18
0
static void prv_soup_server_cb(SoupServer *server, SoupMessage *msg,
			       const char *path, GHashTable *query,
			       SoupClientContext *client, gpointer user_data)
{
	dlr_host_file_t *hf;
	dlr_host_server_t *hs = user_data;
	const gchar *file_name;
	const char *hdr;

	if ((msg->method != SOUP_METHOD_GET) &&
	    (msg->method != SOUP_METHOD_HEAD)) {
		soup_message_set_status(msg, SOUP_STATUS_NOT_IMPLEMENTED);
		goto on_error;
	}

	hf = prv_host_server_find_file(hs, path, &file_name);

	if (!hf) {
		soup_message_set_status(msg, SOUP_STATUS_NOT_FOUND);
		goto on_error;
	}

	hdr = soup_message_headers_get_one(msg->request_headers,
					   "getContentFeatures.dlna.org");

	if (hdr) {
		if (strcmp(hdr, "1") != 0) {
			soup_message_set_status(msg, SOUP_STATUS_BAD_REQUEST);
			goto on_error;
		}

		if ((hf->dlna_header) && strlen(hf->dlna_header) > 0)
			soup_message_headers_append(msg->response_headers,
						    "contentFeatures.dlna.org",
						    hf->dlna_header);
	}

	if (hf->mapped_file) {
		g_mapped_file_ref(hf->mapped_file);
		++hf->mapped_count;
	} else {
		hf->mapped_file = g_mapped_file_new(file_name,
						    FALSE,
						    NULL);

		if (!hf->mapped_file) {
			soup_message_set_status(msg,
						SOUP_STATUS_NOT_FOUND);
			goto on_error;
		}

		hf->mapped_count = 1;
	}

	if (msg->method == SOUP_METHOD_GET) {
		g_signal_connect(msg, "finished",
				 G_CALLBACK(prv_soup_message_finished_cb), hf);

		soup_message_set_response(
				msg, hf->mime_type,
				SOUP_MEMORY_STATIC,
				g_mapped_file_get_contents(hf->mapped_file),
				g_mapped_file_get_length(hf->mapped_file));
	} else {
		soup_message_headers_set_content_type(msg->response_headers,
						      hf->mime_type, NULL);

		soup_message_headers_set_content_length(
			msg->response_headers,
			g_mapped_file_get_length(hf->mapped_file));
	}

	soup_message_set_status(msg, SOUP_STATUS_OK);

on_error:

	return;
}
예제 #19
0
GList *get_entries_from_file(gchar *file_name)
{
  gchar *text, *pat;
  GMappedFile *mf;
  gsize len;
  gboolean more = TRUE;
  gchar lat_buf[32], lon_buf[32];
  gchar *s;
  gint fragment_len;
  GList *found_places = NULL;
  found_geoname *geoname = NULL;
  gchar **found_entries;
  gchar *entry;
  int entry_runner;
  gchar *wikipedia_url = NULL;
  gchar *thumbnail_url = NULL;

  lat_buf[0] = lon_buf[0] = '\0';

  if ((mf = g_mapped_file_new(file_name, FALSE, NULL)) == NULL) {
    g_critical(_("couldn't map temp file"));
    exit(1);
  }
  len = g_mapped_file_get_length(mf);
  text = g_mapped_file_get_contents(mf);

  if (g_strstr_len(text, len, GEONAMES_SEARCH_NOT_FOUND) != NULL) {
    more = FALSE;
  }
  found_entries = g_strsplit(text, "},", 0);
  entry_runner = 0;
  entry = found_entries[entry_runner];
  while (entry)
  {
    more = TRUE;
    geoname = new_found_geoname();
    if ((pat = g_strstr_len(entry, strlen(entry), GEONAMES_COUNTRY_PATTERN))) {
      pat += strlen(GEONAMES_COUNTRY_PATTERN);
      fragment_len = 0;
      s = pat;
      while (*pat != '"') {
        fragment_len++;
        pat++;
      }
      geoname -> country = g_strndup(s, fragment_len);
    }
    if ((pat = g_strstr_len(entry, strlen(entry), GEONAMES_LONGITUDE_PATTERN)) == NULL) {
      more = FALSE;
    }
    else {
      pat += strlen(GEONAMES_LONGITUDE_PATTERN);
      s = lon_buf;
      if (*pat == '-')
        *s++ = *pat++;
      while ((s < (lon_buf + sizeof(lon_buf))) && (pat < (text + len)) &&
              (g_ascii_isdigit(*pat) || (*pat == '.')))
        *s++ = *pat++;
      *s = '\0';
      if ((pat >= (text + len)) || (lon_buf[0] == '\0')) {
        more = FALSE;
      }
      geoname->ll.lon = g_ascii_strtod(lon_buf, NULL);
    }
    if ((pat = g_strstr_len(entry, strlen(entry), GEONAMES_NAME_PATTERN))) {
      pat += strlen(GEONAMES_NAME_PATTERN);
      fragment_len = 0;
      s = pat;
      while (*pat != '"') {
        fragment_len++;
        pat++;
      }
      geoname -> name = g_strndup(s, fragment_len);
    }
    if ((pat = g_strstr_len(entry, strlen(entry), GEONAMES_TITLE_PATTERN))) {
      pat += strlen(GEONAMES_TITLE_PATTERN);
      fragment_len = 0;
      s = pat;
      while (*pat != '"') {
        fragment_len++;
        pat++;
      }
      geoname -> name = g_strndup(s, fragment_len);
    }
    if ((pat = g_strstr_len(entry, strlen(entry), GEONAMES_WIKIPEDIAURL_PATTERN))) {
      pat += strlen(GEONAMES_WIKIPEDIAURL_PATTERN);
      fragment_len = 0;
      s = pat;
      while (*pat != '"') {
        fragment_len++;
        pat++;
      }
      wikipedia_url = g_strndup(s, fragment_len);
    }
    if ((pat = g_strstr_len(entry, strlen(entry), GEONAMES_THUMBNAILIMG_PATTERN))) {
      pat += strlen(GEONAMES_THUMBNAILIMG_PATTERN);
      fragment_len = 0;
      s = pat;
      while (*pat != '"') {
        fragment_len++;
        pat++;
      }
      thumbnail_url = g_strndup(s, fragment_len);
    }
    if ((pat = g_strstr_len(entry, strlen(entry), GEONAMES_LATITUDE_PATTERN)) == NULL) {
      more = FALSE;
    }
    else {
      pat += strlen(GEONAMES_LATITUDE_PATTERN);
      s = lat_buf;
      if (*pat == '-')
        *s++ = *pat++;
      while ((s < (lat_buf + sizeof(lat_buf))) && (pat < (text + len)) &&
              (g_ascii_isdigit(*pat) || (*pat == '.')))
        *s++ = *pat++;
      *s = '\0';
      if ((pat >= (text + len)) || (lat_buf[0] == '\0')) {
        more = FALSE;
      }
      geoname->ll.lat = g_ascii_strtod(lat_buf, NULL);
    }
    if (!more) {
      if (geoname) {
        g_free(geoname);
      }
    }
    else {
      if (wikipedia_url) {
        if (thumbnail_url) {
          geoname -> desc = g_strdup_printf("<a href=\"http://%s\" target=\"_blank\"><img src=\"%s\" border=\"0\"/></a>", wikipedia_url, thumbnail_url);
        }
        else {
          geoname -> desc = g_strdup_printf("<a href=\"http://%s\" target=\"_blank\">%s</a>", wikipedia_url, geoname->name);
        }
      }
      if (wikipedia_url) {
        g_free(wikipedia_url);
        wikipedia_url = NULL;
      }
      if (thumbnail_url) {
        g_free(thumbnail_url);
        thumbnail_url = NULL;
      }
      found_places = g_list_prepend(found_places, geoname);
    }
    entry_runner++;
    entry = found_entries[entry_runner];
  }
  g_strfreev(found_entries);
  found_places = g_list_reverse(found_places);
  g_mapped_file_free(mf);
  return(found_places);
}