SLProject  4.2.000
A platform independent 3D computer graphics framework for desktop OS, Android, iOS and online in web browsers
SLIOFetch.cpp
Go to the documentation of this file.
1 /**
2  * \file SLIOFetch.cpp
3  * \date October 2022
4  * \authors Marino von Wattenwyl
5  * \copyright http://opensource.org/licenses/GPL-3.0
6  * \remarks Please use clangformat to format the code. See more code style on
7  * https://github.com/cpvrlab/SLProject4/wiki/SLProject-Coding-Style
8 */
9 
10 #include <SLIOFetch.h>
11 
12 #ifdef SL_STORAGE_WEB
13 //-----------------------------------------------------------------------------
14 # include <emscripten/fetch.h>
15 # include <pthread.h>
16 # include <cassert>
17 # include <iostream>
18 //-----------------------------------------------------------------------------
19 bool SLIOReaderFetch::exists(std::string url)
20 {
21  assert(pthread_self() != 0 && "Fetching is not allowed on the main thread");
22 
23  emscripten_fetch_attr_t attr;
24  emscripten_fetch_attr_init(&attr);
25  std::strcpy(attr.requestMethod, "HEAD");
26  attr.attributes = EMSCRIPTEN_FETCH_SYNCHRONOUS;
27  emscripten_fetch_t* fetch = emscripten_fetch(&attr, url.c_str());
28  bool exists = fetch->status == 200;
29  emscripten_fetch_close(fetch);
30 
31  return exists;
32 }
33 //-----------------------------------------------------------------------------
35  : SLIOReaderMemory(url)
36 {
37  assert(pthread_self() != 0 && "Fetching is not allowed on the main thread");
38 
39  std::cout << "FETCH \"" << url << "\"" << std::endl;
40 
41  emscripten_fetch_attr_t attr;
42  emscripten_fetch_attr_init(&attr);
43  std::strcpy(attr.requestMethod, "GET");
44  attr.attributes = EMSCRIPTEN_FETCH_LOAD_TO_MEMORY | EMSCRIPTEN_FETCH_SYNCHRONOUS;
45  emscripten_fetch_t* fetch = emscripten_fetch(&attr, url.c_str());
46 
47  int status = fetch->status;
48  size_t size = (size_t)fetch->totalBytes;
49  std::cout << "STATUS: " << status << ", SIZE: " << size << std::endl;
50 
51  if (status == 200)
52  {
53  SLIOMemory::set(_path, std::vector<char>(fetch->data, fetch->data + size));
54  }
55 
56  emscripten_fetch_close(fetch);
57 }
58 //-----------------------------------------------------------------------------
60 {
62 }
63 //-----------------------------------------------------------------------------
64 #endif
SLIOReaderFetch(std::string url)
Definition: SLIOFetch.cpp:34
static bool exists(std::string url)
Definition: SLIOFetch.cpp:19
SLIOStream implementation for reading from memory.
Definition: SLIOMemory.h:28
std::string _path
Definition: SLIOMemory.h:37
void set(std::string path, const std::vector< char > &data)
Definition: SLIOMemory.cpp:29
void clear(std::string path)
Definition: SLIOMemory.cpp:34