Source

NPAPI-chrome-file-api / NPAPIFileIOforChromeAPI.cpp

ryanackley cf0cb11 


















ryanackley a94bab9 













ryanackley 43e5547 
ryanackley a94bab9 

























































































unknown 33888fa 
ryanackley a94bab9 





















































unknown 33888fa 
ryanackley a94bab9 

































unknown 33888fa 
ryanackley a94bab9 








































unknown 33888fa 
ryanackley a94bab9 



































unknown 33888fa 

ryanackley a94bab9 




ryanackley 43e5547 









ryanackley a94bab9 































unknown 33888fa 

ryanackley a94bab9 
unknown 33888fa 
ryanackley a94bab9 
/*
* Copyright 2012 Ryan Ackley (ryanackley@gmail.com)
*
* This file is part of NPAPI Chrome File API
*
* NPAPI Chrome File API is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* 
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#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 "DOM/Window.h"
#include "NPObjectAPI.h"
#include "NpapiBrowserHost.h"
#include "DialogManager.h"
#include "FileWatcher.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 = new char[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();
	delete [] buffer;
    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 = new char[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");
        }
		delete [] buffer;
        
        //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();
	NPAPIFileIOforChromePtr plugin = m_plugin.lock();
    dlgMgr->OpenFolderDialog(m_host, plugin->GetWindow(), boost::bind(&NPAPIFileIOforChromeAPI::fileSelectCallback, this, _1, callback));
}
void NPAPIFileIOforChromeAPI::fileSelectCallback(const std::string &path, JSObjectPtr callback)
{
    callback->Invoke("",FB::variant_list_of(path));
}
void NPAPIFileIOforChromeAPI::watchDirectory(std::string key, std::string path, JSObjectPtr callback)
{
    FileWatcher* watcher = FileWatcher::get();
    watcher->WatchFile(key, path, callback);
}
void NPAPIFileIOforChromeAPI::stopWatching(std::string key)
{
    FileWatcher* watcher = FileWatcher::get();
    watcher->StopWatching(key);
}
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();
    
#else
	return "";
#endif

}