Source

NPAPI-chrome-file-api / NPAPIFileIOforChromeAPI.cpp

/**********************************************************\

  Auto-generated NPAPIFileIOforChromeAPI.cpp

\**********************************************************/

#define BOOST_FILESYSTEM_VERSION 3

#include "JSObject.h"
#include "variant_list.h"
#include "DOM/Document.h"
#include "global/config.h"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include "NPAPIFileIOforChromeAPI.h"
#include "BinaryArray.h"
#include "DOM/Window.h"
#include "NPObjectAPI.h"
#include "NpapiBrowserHost.h"
#include "DialogManager.h"

using namespace boost::filesystem;
using namespace FB;
using namespace FB::Npapi;


///////////////////////////////////////////////////////////////////////////////
/// @fn FB::variant NPAPIFileIOforChromeAPI::echo(const FB::variant& msg)
///
/// @brief  Echos whatever is passed from Javascript.
///         Go ahead and change it. See what happens!
///////////////////////////////////////////////////////////////////////////////
FB::variant NPAPIFileIOforChromeAPI::echo(const FB::variant& msg)
{
    static int n(0);
    fire_echo("So far, you clicked this many times: ", n++);

    // return "foobar";
    return msg;
}

///////////////////////////////////////////////////////////////////////////////
/// @fn NPAPIFileIOforChromePtr NPAPIFileIOforChromeAPI::getPlugin()
///
/// @brief  Gets a reference to the plugin that was passed in when the object
///         was created.  If the plugin has already been released then this
///         will throw a FB::script_error that will be translated into a
///         javascript exception in the page.
///////////////////////////////////////////////////////////////////////////////
NPAPIFileIOforChromePtr NPAPIFileIOforChromeAPI::getPlugin()
{
    NPAPIFileIOforChromePtr plugin(m_plugin.lock());
    if (!plugin) {
        throw FB::script_error("The plugin is invalid");
    }
    return plugin;
}

// Read/Write property testString
std::string NPAPIFileIOforChromeAPI::get_testString()
{
    return m_testString;
}

void NPAPIFileIOforChromeAPI::set_testString(const std::string& val)
{
    m_testString = val;
}

// Read-only property version
std::string NPAPIFileIOforChromeAPI::get_version()
{
    return FBSTRING_PLUGIN_VERSION;
}

void NPAPIFileIOforChromeAPI::testEvent()
{
    fire_test();
}


/*void NPAPIFileIOforChromeAPI::saveToFileUrl(std::string url, std::string content)
{
    
}*/
bool NPAPIFileIOforChromeAPI::createDirectory(std::string strPath)
{
    if (!strPath.length())
    {
        return true;
    }
    path p(strPath);
    
    create_directory(p);
    return is_directory(p);
}
bool NPAPIFileIOforChromeAPI::saveBlobToFile(std::string strPath, JSObjectPtr dataArray)
{
    variant lenProp = dataArray->GetProperty("length");
    int arrayLength = (int)lenProp.cast<double>();
    
    DOM::WindowPtr window = m_host->getDOMWindow();
    JSObjectPtr obj = window->getProperty<FB::JSObjectPtr>("JSON");
    variant v = obj->Invoke("stringify", FB::variant_list_of(dataArray));
    
    std::string jsonArray = v.cast<std::string>();
    
    std::ostringstream currentNum("");
    //std::vector<char> buffer;
    //buffer.reserve(arrayLength);
    char buffer[arrayLength];
    int idx = 0;
    
    int size = jsonArray.length();
    for (int x = 0; x < size; x++)
    {
        char next = jsonArray[x];
        switch(next)
        {
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                currentNum << next;
                break;
            default:
                if (currentNum.str().length())
                {
                    int ch;
                    std::istringstream in(currentNum.str());
                    in >> ch;
                    if (idx < arrayLength)
                    {
                        buffer[idx++] = (char)ch;
                    }
                    currentNum.str("");
                }
                break;
        }
    }
    
    
    //int fileLen = buffer.size();
       
    path p(strPath);
   
    /*int fileLen = (int)lenProp.cast<double>();
    char buffer[fileLen];
    
    path p(strPath);
    
    for (int x = 0; x < fileLen; x++)
    {
        buffer[x] = (char)dataArray->GetProperty(x).cast<double>();
    }*/
    
    boost::filesystem::ofstream out(p, std::ios::out | std::ios::binary);
    out.write(buffer, arrayLength);
    out.close();
    return true;
   
}
FB::VariantList NPAPIFileIOforChromeAPI::getDirEntries(std::string strPath)
{
    path p(strPath);
    
    VariantList entries;
    if (is_directory(p))
    {
        directory_iterator di(p);
        directory_iterator eos;
        
        while(di != eos)
        {
            directory_entry de = *di;
           // variant entry;
            //entry.assign<std::string>();
            entries.push_back(de.path().filename().generic_string());
            di++;
        }
    }
    return entries;
    
}
FB::JSAPIPtr NPAPIFileIOforChromeAPI::contentsAtPath(std::string strPath)
{
    path p(strPath);
    
    
    //VariantList jsBytes;
    if (is_regular_file(p))
    {
        int size = file_size(p);
        char buffer[size];
        
        boost::filesystem::ifstream in(p, std::ios::in | std::ios::binary);
    
        in.read(buffer, size);
        in.close();
        
        std::ostringstream json;
        
        json << "[";
        for (int x = 0; x < size; x++)
        {
            json << (int)buffer[x] << ",";
        }
        json << "]";
        
        DOM::WindowPtr win = m_host->getDOMWindow();
        JSObjectPtr jsObj = win->getJSObject();
        
        NPObjectAPIPtr bridgeObj = boost::static_pointer_cast<NPObjectAPI>(jsObj);
        NpapiBrowserHostPtr npapiHost = boost::static_pointer_cast<NpapiBrowserHost>(m_host); 
        
        NPVariant retVal;
        NPVariant tmp;
        
        npapiHost->getNPVariant(&tmp, FB::variant(json.str()));
        
        if (npapiHost->Evaluate(bridgeObj->getNPObject(),
                           &tmp.value.stringValue, &retVal)) {
            if (retVal.type != NPVariantType_Object)
            {
                npapiHost->ReleaseVariantValue(&retVal);
            }
            else
            {
                JSAPIPtr array(new NPObjectAPI(retVal.value.objectValue, npapiHost));
                return array;
            }
            
        } else {
            throw script_error("Error executing JavaScript code");
        }

        
        //return boost::make_shared<BinaryArray>(buffer, size);
        /*jsBytes.reserve(size);
        for (int x = 0; x < size; x++)
        {
            variant ch = buffer[x];
            jsBytes.push_back(ch);
        }*/
    }
    return JSObjectPtr();
    //return ;
    
}
int NPAPIFileIOforChromeAPI::getFileSize(std::string strPath)
{
    path p(strPath);
    return file_size(p);
}
bool NPAPIFileIOforChromeAPI::isDirectory(std::string strPath)
{
    path p(strPath);
    return is_directory(p);
}
bool NPAPIFileIOforChromeAPI::fileExists(std::string strPath)
{
    path p(strPath);
    return exists(p);
}
bool NPAPIFileIOforChromeAPI::removeRecursively(std::string strPath)
{
    path p(strPath);
    return remove_all(p) != 0;
}
void NPAPIFileIOforChromeAPI::launchFileSelect(JSObjectPtr callback)
{
    DialogManager* dlgMgr = DialogManager::get();
    dlgMgr->OpenFolderDialog(m_host, NULL, boost::bind(&NPAPIFileIOforChromeAPI::fileSelectCallback, this, _1, callback));
}
void NPAPIFileIOforChromeAPI::fileSelectCallback(const std::string &path, JSObjectPtr callback)
{
    callback->Invoke("",FB::variant_list_of(path));
}
std::string NPAPIFileIOforChromeAPI::getChromeDataDir(std::string version)
{
#if defined __MACH__ && defined __APPLE__
    path apps("/Applications");
    
    directory_iterator di(apps);
    directory_iterator eos;
    
    std::string userHome = getenv("HOME");
    while(di != eos)
    {
        directory_entry de = *di;
        std::string appPath = de.path().filename().generic_string();
        size_t index = appPath.find("Google Chrom");
        if (index != appPath.npos)
        {
            path vpath = de.path();
            vpath /= ("Contents/Versions/" + version);
            if (exists(vpath))
            {
                std::string dirName = appPath.substr(7, appPath.length() - 11);
                path retVal(userHome);
                retVal /= ("Library/Application Support/Google/" + dirName);
                return retVal.generic_string();
            }
        }
        di++;
    }
    return "";
    
   // pid_t pid = getppid();
    
    
#endif
}