コード例 #1
0
/****************************************************************************
 * Update the Icon.png file
 ***************************************************************************/
bool UpdateTask::DownloadIconPNG(void)
{
	if(!IsNetworkInit())
		return false;

	struct block file = downloadfile(iconUpdateURL);
	if(!file.data)
		return false;

	CreateSubfolder(Settings.UpdatePath);

	//! append slash if it is missing
	std::string destPath = Settings.UpdatePath;
	if(destPath.size() > 0 && destPath[destPath.size()-1] != '/')
		destPath += '/';

	destPath += "icon.png";

	FILE * pFile = fopen(destPath.c_str(), "wb");
	if(!pFile)
		return false;

	fwrite(file.data, 1, file.size, pFile);
	fclose(pFile);
	free(file.data);

	return true;
}
コード例 #2
0
bool Wiinnertag::CreateExample(const string &filepath)
{
	if(filepath.size() == 0)
		return false;

	CreateSubfolder(filepath.c_str());

	string fullpath = filepath;
	if(fullpath[fullpath.size()-1] != '/')
		fullpath += '/';
	fullpath += "Wiinnertag.xml";

	TiXmlDocument xmlDoc;

	TiXmlDeclaration declaration("1.0", "UTF-8", "");
	xmlDoc.InsertEndChild(declaration);

	TiXmlElement Tag("Tag");
	Tag.SetAttribute("URL", "http://www.wiinnertag.com/wiinnertag_scripts/update_sign.php?key={KEY}&game_id={ID6}");
	Tag.SetAttribute("Key", "1234567890");
	xmlDoc.InsertEndChild(Tag);

	xmlDoc.SaveFile(fullpath);

	return true;
}
コード例 #3
0
ファイル: sys.cpp プロジェクト: Jeremy-D-Miller/usbloader-gui
void ScreenShot()
{
	time_t rawtime;
	struct tm * timeinfo;
	char filename[100];	// Filename, with current date/time.
	char fullPath[300];	// Full pathname: ConfigPath + filename.

	time(&rawtime);
	timeinfo = localtime(&rawtime);

	// Create the filename with the current date/time.
	// Format: USBLoader_GX_ScreenShot-Month_Day_Hour_Minute_Second_Year.png
	int ret = strftime(filename, sizeof(filename), "USBLoader_GX_ScreenShot-%b%d%H%M%S%y.png", timeinfo);
	if (ret == 0)
	{
		// Error formatting the time.
		// Use the raw time in seconds as a fallback.
		snprintf(filename, sizeof(filename), "USBLoader_GX_ScreenShot-%ld.png", rawtime);
	}

	// Create the full pathname.
	snprintf(fullPath, sizeof(fullPath), "%s%s", Settings.ConfigPath, filename);

	if(!CreateSubfolder(Settings.ConfigPath))
	{
		gprintf("Can't create screenshot folder\n");
		return;
	}

	TakeScreenshot(fullPath);
}
コード例 #4
0
ファイル: fileop.cpp プロジェクト: Gamer125/wiibrowser
/****************************************************************************
 * CreateSubfolder
 *
 * Create recursive all subfolders to the given path
 ***************************************************************************/
bool CreateSubfolder(const char * fullpath)
{
    if(!fullpath)
        return false;

    if(CheckFile(fullpath))
        return true;

    string dirpath(fullpath);

    int length = dirpath.size()-1;
    while(dirpath[length] == '/')
    {
        dirpath.erase(length);
        --length;
    }

    string subpath(dirpath);
    size_t pos = subpath.rfind('/');
    if(pos == string::npos)
        return false;

    if(subpath.size()-1 > pos)
        subpath.erase(pos+1);

    bool result = CreateSubfolder(subpath.c_str());
    if(!result)
        return false;

    return (mkdir(dirpath.c_str(), 0777) != -1);
}
コード例 #5
0
bool CSettings::FindConfig()
{
	bool found = false;
	char CheckDevice[12];
	char CheckPath[300];

	// Enumerate the devices supported by libogc.
	for (int i = SD; (i < MAXDEVICES) && !found; ++i)
	{
		snprintf(CheckDevice, sizeof(CheckDevice), "%s:", DeviceName[i]);

		if(!found)
		{
			// Check for the config file in the apps directory.
			strlcpy(BootDevice, CheckDevice, sizeof(BootDevice));
			snprintf(ConfigPath, sizeof(ConfigPath), "%s/apps/usbloader_gx/", BootDevice);
			snprintf(CheckPath, sizeof(CheckPath), "%sGXGlobal.cfg", ConfigPath);
			found = CheckFile(CheckPath);
		}
		if(!found)
		{
			// Check for the config file in the config directory.
			strlcpy(BootDevice, CheckDevice, sizeof(BootDevice));
			snprintf(ConfigPath, sizeof(ConfigPath), "%s/config/", BootDevice);
			snprintf(CheckPath, sizeof(CheckPath), "%sGXGlobal.cfg", ConfigPath);
			found = CheckFile(CheckPath);
		}
	}

	FILE * testFp = NULL;
	//! No existing config so try to find a place where we can write it too
	for (int i = SD; (i < MAXDEVICES) && !found; ++i)
	{
		sprintf(CheckDevice, "%s:", DeviceName[i]);

		if (!found)
		{
			// Check if we can write to the apps directory.
			strlcpy(BootDevice, CheckDevice, sizeof(BootDevice));
			snprintf(ConfigPath, sizeof(ConfigPath), "%s/apps/usbloader_gx/", BootDevice);
			snprintf(CheckPath, sizeof(CheckPath), "%sGXGlobal.cfg", ConfigPath);
			testFp = fopen(CheckPath, "wb");
			found = (testFp != NULL);
			if(testFp) fclose(testFp);
		}
		if (!found)
		{
			// Check if we can write to the config directory.
			strlcpy(BootDevice, CheckDevice, sizeof(BootDevice));
			snprintf(ConfigPath, sizeof(ConfigPath), "%s/config/", BootDevice);
			CreateSubfolder(ConfigPath);
			snprintf(CheckPath, sizeof(CheckPath), "%sGXGlobal.cfg", ConfigPath);
			testFp = fopen(CheckPath, "wb");
			found = (testFp != NULL);
			if(testFp) fclose(testFp);
		}
	}

	return found;
}
コード例 #6
0
bool CSettings::Save()
{
    if(!bChanged)
        return true;

    CreateSubfolder(configPath.c_str());

	std::string filepath = configPath;
	filepath += "/loadiine_gx2.cfg";

	CFile file(filepath, CFile::WriteOnly);
	if (!file.isOpen())
        return false;

	file.fwrite("%s%i\n", VERSION_LINE, VALID_VERSION);

	for(u32 i = 0; i < settingsValues.size(); i++)
    {
        switch(settingsValues[i].dataType)
        {
            case TypeBool:
                file.fwrite("%s=%i\n", settingsNames[i], settingsValues[i].bValue);
                break;
            case TypeS8:
                file.fwrite("%s=%i\n", settingsNames[i], settingsValues[i].cValue);
                break;
            case TypeU8:
                file.fwrite("%s=%i\n", settingsNames[i], settingsValues[i].ucValue);
                break;
            case TypeS16:
                file.fwrite("%s=%i\n", settingsNames[i], settingsValues[i].sValue);
                break;
            case TypeU16:
                file.fwrite("%s=%i\n", settingsNames[i], settingsValues[i].usValue);
                break;
            case TypeS32:
                file.fwrite("%s=%i\n", settingsNames[i], settingsValues[i].iValue);
                break;
            case TypeU32:
                file.fwrite("%s=%u\n", settingsNames[i], settingsValues[i].uiValue);
                break;
            case TypeF32:
                file.fwrite("%s=%f\n", settingsNames[i], settingsValues[i].fValue);
                break;
            case TypeString:
                if(settingsValues[i].strValue != NULL)
                    file.fwrite("%s=%s\n", settingsNames[i], settingsValues[i].strValue->c_str());
                break;
            default:
                break;
        }
    }

    file.close();
    bChanged = false;

	return true;
}
コード例 #7
0
/****************************************************************************
 * CreateSubfolder
 *
 * Create recursive all subfolders to the given path
 ***************************************************************************/
extern "C" bool CreateSubfolder(const char * fullpath)
{
	if(!fullpath)
		return false;

	bool result  = false;

	char dirnoslash[strlen(fullpath)+1];
	strcpy(dirnoslash, fullpath);

	int pos = strlen(dirnoslash)-1;
	while(dirnoslash[pos] == '/')
	{
		dirnoslash[pos] = '\0';
		pos--;
	}

	if(CheckFile(dirnoslash))
	{
		return true;
	}
	else
	{
		char parentpath[strlen(dirnoslash)+2];
		strcpy(parentpath, dirnoslash);
		char * ptr = strrchr(parentpath, '/');

		if(!ptr)
		{
			//!Device root directory (must be with '/')
			strcat(parentpath, "/");
			struct stat filestat;
			if (stat(parentpath, &filestat) == 0)
				return true;

			return false;
		}

		ptr++;
		ptr[0] = '\0';

		result = CreateSubfolder(parentpath);
	}

	if(!result)
		return false;

	if (mkdir(dirnoslash, 0777) == -1)
	{
		return false;
	}

	return true;
}
コード例 #8
0
/****************************************************************************
 * UpdateApp from a given url. The dol is downloaded and overwrites the old one.
 ***************************************************************************/
int UpdateTask::DownloadApp(const char *url)
{
	if(!url)
	{
		ThrowMsg(tr("Error"), tr("URL is empty."));
		return -1;
	}

	//! append slash if it is missing
	std::string destPath = Settings.UpdatePath;
	if(destPath.size() > 0 && destPath[destPath.size()-1] != '/')
		destPath += '/';

	destPath += "boot.zip";

	CreateSubfolder(Settings.UpdatePath);

	int res = DownloadFileToPath(url, destPath.c_str(), false);
	if(res < 102400)
	{
		RemoveFile(destPath.c_str());
		ThrowMsg(tr("Update failed"), tr("Could not download file."));
		return -1;
	}
	else
	{
		StartProgress(tr("Extracting file..."));

		ZipFile zip(destPath.c_str());
		zip.ExtractAll(Settings.UpdatePath);

		RemoveFile(destPath.c_str());

		StopProgress();

		if(Settings.UpdateMetaxml)
			DownloadMetaXml();
		if(Settings.UpdateIconpng)
			DownloadIconPNG();
	}

	return 1;
}
コード例 #9
0
int UpdateLanguageFiles()
{
	if(!CreateSubfolder(Settings.languagefiles_path))
	{
		ShowError(tr("Could not create path: %s"), Settings.languagefiles_path);
		return -1;
	}

	if(!IsNetworkInit())
	{
		ShowError(tr("Network is not initiated."));
		return -2;
	}

	DirList Dir(Settings.languagefiles_path, ".lang");

	//give up now if we didn't find any
	if (Dir.GetFilecount() == 0)
	{
		if(WindowPrompt(tr("Error:"), tr("No language files to update on your devices! Do you want to download new language files?"), tr("Yes"), tr("No")))
			return DownloadAllLanguageFiles();

		return -2;
	}

	char savepath[150];
	char codeurl[200];

	//we assume that the network will already be init by another function
	// ( that has gui eletents in it because this one doesn't)
	int done = 0;

	//build the URL, save path, and download each file and save it
	for(int i = 0; i < Dir.GetFilecount(); ++i)
	{
		snprintf(codeurl, sizeof(codeurl), "%s%s?p=%s", LanguageFilesURL, Dir.GetFilename(i), GetRev());
		snprintf(savepath, sizeof(savepath), "%s/%s", Settings.languagefiles_path, Dir.GetFilename(i));

		struct block file = downloadfile(codeurl);

		ShowProgress(tr("Updating Language Files:"), 0, Dir.GetFilename(i), i, Dir.GetFilecount(), false, true);

		if (file.data != NULL)
		{
			FILE * pfile;
			pfile = fopen(savepath, "wb");
			if (pfile != NULL)
			{
				fwrite(file.data, 1, file.size, pfile);
				fclose(pfile);
				done++;
			}
			free(file.data);
		}
	}

	ProgressStop();

	// reload current language file
	if(Settings.language_path[0] != 0)
		Settings.LoadLanguage(Settings.language_path, CONSOLE_DEFAULT);
	else
		Settings.LoadLanguage(NULL, CONSOLE_DEFAULT);

	// return the number of files we updated
	return done;
}
コード例 #10
0
ファイル: GameLauncher.cpp プロジェクト: Dworcor/loadiine_gx2
int GameLauncher::loadGameToMemory(const discHeader *header)
{
    if(!header)
        return INVALID_INPUT;

    //! initialize the RPL/RPX table first entry to zero + 1 byte for name zero termination
    //! just in case no RPL/RPX are found, though it wont boot then anyway
    memset(RPX_RPL_ARRAY, 0, sizeof(s_rpx_rpl) + 1);

	DirList rpxList(header->gamepath + RPX_RPL_PATH, ".rpx", DirList::Files);

	if(rpxList.GetFilecount() == 0)
    {
        log_printf("RPX file not found!\n");
        return RPX_NOT_FOUND;
    }
	if(rpxList.GetFilecount() != 1)
    {
        log_printf("Warning: Too many RPX files in the folder! Found %i files! Using first one.\n", rpxList.GetFilecount());
        //return TOO_MANY_RPX_NOT_FOUND;
    }

    u32 entryIndex = 0;
    std::string rpxName;
    std::vector<std::string> rplImportList;

    DirList rplList(header->gamepath + RPX_RPL_PATH, ".rpl", DirList::Files);

    int result = LoadRpxRplToMem(rpxList.GetFilepath(0), rpxList.GetFilename(0), true, entryIndex++, rplImportList);
    if(result < 0)
    {
        log_printf("Failed loading RPX file %s, error %i\n", rpxList.GetFilepath(0), result);
        return result;
    }

    rpxName = rpxList.GetFilename(0);

    //! get all imports from the RPX
    GetRpxImports((s_rpx_rpl *)(RPX_RPL_ARRAY), rplImportList);

    for(int i = 0; i < rplList.GetFilecount(); i++)
    {
        result = LoadRpxRplToMem(rplList.GetFilepath(i), rplList.GetFilename(i), false, entryIndex++, rplImportList);
        if(result < 0)
        {
            log_printf("Failed loading RPL file %s, error %i\n", rplList.GetFilepath(0), result);
            return result;
        }
    }

    //! TODO: clean this path creation up
    std::string game_dir = header->gamepath;
    size_t pos = game_dir.rfind('/');

    if(pos != std::string::npos)
        game_dir = game_dir.substr(pos + 1);

    //! set the save game path from the gamenames path
    std::string saveGamePath = CSettings::getValueAsString(CSettings::GameSavePath) + "/" + game_dir;
    std::string saveGamePathCommon;
    std::string saveGamePathUser;

    if(CSettings::getValueAsU8(CSettings::GameSaveMode) == GAME_SAVES_SHARED)
    {
        saveGamePathUser = "******";
        saveGamePathCommon = "c";
    }
    else
    {
        /* get persistent ID - thanks to Maschell */
        unsigned int nn_act_handle;
        unsigned long (*GetPersistentIdEx)(unsigned char);
        int (*GetSlotNo)(void);
        void (*nn_Initialize)(void);
        void (*nn_Finalize)(void);
        OSDynLoad_Acquire("nn_act.rpl", &nn_act_handle);
        OSDynLoad_FindExport(nn_act_handle, 0, "GetPersistentIdEx__Q2_2nn3actFUc", &GetPersistentIdEx);
        OSDynLoad_FindExport(nn_act_handle, 0, "GetSlotNo__Q2_2nn3actFv", &GetSlotNo);
        OSDynLoad_FindExport(nn_act_handle, 0, "Initialize__Q2_2nn3actFv", &nn_Initialize);
        OSDynLoad_FindExport(nn_act_handle, 0, "Finalize__Q2_2nn3actFv", &nn_Finalize);

        nn_Initialize(); // To be sure that it is really Initialized

        unsigned char slotno = GetSlotNo();
        unsigned int persistentID = GetPersistentIdEx(slotno);
        nn_Finalize(); //must be called an equal number of times to nn_Initialize

        char persistentIdString[10];
        snprintf(persistentIdString, sizeof(persistentIdString), "%08X", persistentID);

        saveGamePathUser = persistentIdString;
        saveGamePathCommon = "common";
    }

    CreateSubfolder((saveGamePath + "/" + saveGamePathUser).c_str());
    CreateSubfolder((saveGamePath + "/" + saveGamePathCommon).c_str());

    std::string tempPath = CSettings::getValueAsString(CSettings::GamePath);
    //! remove "sd:" and replace with "/vol/external01"
    pos = tempPath.find('/');
    if(pos != std::string::npos)
        tempPath = std::string(CAFE_OS_SD_PATH) + tempPath.substr(pos);

    game_paths_t *game_paths = (game_paths_t *)GAME_PATH_STRUCT;

    //! set pointer to firth path and copy it
    game_paths->os_game_path_base = (char*)(game_paths + 1);
    strcpy(game_paths->os_game_path_base, tempPath.c_str());

    //! set pointer to next path and copy it
    game_paths->os_save_path_base = game_paths->os_game_path_base + tempPath.size() + 1;

    tempPath = CSettings::getValueAsString(CSettings::GameSavePath);
    //! remove "sd:" and replace with "/vol/external01"
    pos = tempPath.find('/');
    if(pos != std::string::npos)
        tempPath = std::string(CAFE_OS_SD_PATH) + tempPath.substr(pos);

    strcpy(game_paths->os_save_path_base, tempPath.c_str());

    //! set pointer to next path and copy it
    game_paths->game_dir = game_paths->os_save_path_base + tempPath.size() + 1;
    strcpy(game_paths->game_dir, game_dir.c_str());

    //! set pointer to next path and copy it
    game_paths->save_dir_common = game_paths->game_dir + game_dir.size() + 1;
    strcpy(game_paths->save_dir_common, saveGamePathCommon.c_str());

    //! set pointer to next path and copy it
    game_paths->save_dir_user = game_paths->save_dir_common + saveGamePathCommon.size() + 1;
    strcpy(game_paths->save_dir_user, saveGamePathUser.c_str());

    log_printf("game_paths->os_game_path_base: %s\n", game_paths->os_game_path_base);
    log_printf("game_paths->os_save_path_base: %s\n", game_paths->os_save_path_base);
    log_printf("game_paths->game_dir:          %s\n", game_paths->game_dir);
    log_printf("game_paths->save_dir_common:   %s\n", game_paths->save_dir_common);
    log_printf("game_paths->save_dir_user:     %s\n", game_paths->save_dir_user);

    LoadXmlParameters(&cosAppXmlInfoStruct, rpxName.c_str(), (header->gamepath + RPX_RPL_PATH).c_str());

    DCFlushRange((void*)&cosAppXmlInfoStruct, sizeof(ReducedCosAppXmlInfo));

    log_printf("XML Launching Parameters\n");
    log_printf("rpx_name:        %s\n", cosAppXmlInfoStruct.rpx_name);
    log_printf("version_cos_xml: %i\n", cosAppXmlInfoStruct.version_cos_xml);
    log_printf("os_version:      %08X%08X\n", (unsigned int)(cosAppXmlInfoStruct.os_version >> 32), (unsigned int)(cosAppXmlInfoStruct.os_version & 0xFFFFFFFF));
    log_printf("title_id:        %08X%08X\n", (unsigned int)(cosAppXmlInfoStruct.title_id >> 32), (unsigned int)(cosAppXmlInfoStruct.title_id & 0xFFFFFFFF));
    log_printf("app_type:        %08X\n", cosAppXmlInfoStruct.app_type);
    log_printf("cmdFlags:        %08X\n", cosAppXmlInfoStruct.cmdFlags);
    log_printf("max_size:        %08X\n", cosAppXmlInfoStruct.max_size);
    log_printf("avail_size:      %08X\n", cosAppXmlInfoStruct.avail_size);
    log_printf("codegen_size:    %08X\n", cosAppXmlInfoStruct.codegen_size);
    log_printf("codegen_core:    %08X\n", cosAppXmlInfoStruct.codegen_core);
    log_printf("max_codesize:    %08X\n", cosAppXmlInfoStruct.max_codesize);
    log_printf("overlay_arena:   %08X\n", cosAppXmlInfoStruct.overlay_arena);
    log_printf("sdk_version:     %i\n", cosAppXmlInfoStruct.sdk_version);
    log_printf("title_version:   %08X\n", cosAppXmlInfoStruct.title_version);

    return 0;
}
コード例 #11
0
int MiiAllTools::Internal_ExtractAll_Miis_Nand_Dev(std::string devpath, int selected)
{
	if (firstrun)
	{
		MiiList.Get();
		CreateSubfolder(devpath.c_str());
		firstrun = false;
	}
	
	//! Get extract file name
	std::string destPath = devpath;
	if (destPath[destPath.size()-1] != '/')
		destPath += "/";
	destPath += FixMiiName(MiiList.GetFullName(selected));
	destPath += ".miigx";
	
	int miisrc = Nand::OpenRead(MII_FILE);
	if (miisrc >= 0)
	{
		int pos = MiiList.GetFullPosition(selected);
		Nand::Seek(miisrc, MII_HEADER+(pos*MII_SIZE), 0);
		
		u8*memory = (u8*)Tools::AllocateMemory_32(MII_SIZE);
		if(!memory)
		{
			Nand::Close(miisrc);
			return -1;
		}
		
		//! Read Mii
		int ret = Nand::Read(miisrc, memory, MII_SIZE);
		if (ret != MII_SIZE)
		{
			Nand::Close(miisrc);
			free(memory);
			memory = NULL;
			return -1;
		}
		Nand::Close(miisrc);
		
		//! Open destination file
		FILE * miidest = fopen(destPath.c_str(), "wb");
		if(!miidest)
		{
			free(memory);
			memory = NULL;
			return -1;
		}
		
		//! Write file
		fwrite(memory, 1, MII_SIZE, miidest);
		fclose(miidest);
		free(memory);
		memory = NULL;
		
		if (AbortRequested)
			return -10;
		else
			return 1;
		
	}
	
	return -1;
}
コード例 #12
0
int MiiAllTools::Internal_ExtractAll_Miis_Emu_Dev(std::string devpath, int selected)
{
	if (firstrun)
	{
		EmuMiiList.Get();
		CreateSubfolder(devpath.c_str());
		firstrun = false;
	}
	
	//! Get extract file name
	std::string destPath = devpath;
	if (destPath[destPath.size()-1] != '/')
		destPath += "/";
	destPath += FixMiiName(EmuMiiList.GetFullName(selected));
	destPath += ".miigx";
	
	std::string EmuMiiDBPath = Settings.EmuNandPath;
	EmuMiiDBPath += MII_FILE;
	
	//! Read Mii
	u8* memory = (u8*)memalign(32, MII_SIZE);
	if(memory)
	{
		FILE * miisrc = fopen(EmuMiiDBPath.c_str(), "rb");
		if (miisrc)
		{
			int pos = EmuMiiList.GetFullPosition(selected);
			fseek(miisrc, MII_HEADER+(pos*MII_SIZE), SEEK_SET);
			
			if (fread(memory, 1, MII_SIZE, miisrc) != MII_SIZE)
			{
				fclose(miisrc);
				free(memory);
				memory = NULL;
				return -1;
			}
			
			fclose(miisrc);
			
			//! Open destination file
			FILE * miidest = fopen(destPath.c_str(), "wb");
			if(!miidest)
			{
				free(memory);
				memory = NULL;
				return -1;
			}
			
			//! Write file
			fwrite(memory, 1, MII_SIZE, miidest);
			fclose(miidest);
			free(memory);
			memory = NULL;
			
			if (AbortRequested)
				return -10;
			else
				return 1;
			
		}
	}
	
	return -1;
}
コード例 #13
0
bool CSettings::Save()
{
	if (!FindConfig()) return false;

	char filedest[300];
	snprintf(filedest, sizeof(filedest), "%sGXGlobal.cfg", ConfigPath);

	if(!CreateSubfolder(ConfigPath))	return false;

	FILE * file = fopen(filedest, "w");
	if (!file) return false;

	fprintf(file, "# USB Loader GX R%s - Main settings file\n", GetRev());
	fprintf(file, "# Note: This file is automatically generated\n");
	fprintf(file, "godmode = %d\n", godmode);
	fprintf(file, "videomode = %d\n", videomode);
	fprintf(file, "videopatch = %d\n", videopatch);
	fprintf(file, "videoPatchDol = %d\n", videoPatchDol);
	fprintf(file, "language = %d\n", language);
	fprintf(file, "ocarina = %d\n", ocarina);
	fprintf(file, "hddinfo = %d\n", hddinfo);
	fprintf(file, "sinfo = %d\n", sinfo);
	fprintf(file, "rumble = %d\n", rumble);
	fprintf(file, "volume = %d\n", volume);
	fprintf(file, "sfxvolume = %d\n", sfxvolume);
	fprintf(file, "gamesoundvolume = %d\n", gamesoundvolume);
	fprintf(file, "tooltips = %d\n", tooltips);
	fprintf(file, "RememberUnlock = %d\n", RememberUnlock);
	char EncryptedTxt[50];
	EncryptString(unlockCode, EncryptedTxt);
	fprintf(file, "password = %s\n", EncryptedTxt);
	fprintf(file, "GameSort = %d\n", GameSort);
	fprintf(file, "LoaderIOS = %d\n", LoaderIOS);
	fprintf(file, "cios = %d\n", cios);
	fprintf(file, "keyset = %d\n", keyset);
	fprintf(file, "xflip = %d\n", xflip);
	fprintf(file, "gridRows = %d\n", gridRows);
	fprintf(file, "quickboot = %d\n", quickboot);
	fprintf(file, "wsprompt = %d\n", wsprompt);
	fprintf(file, "parentalcontrol = %d\n", parentalcontrol);
	fprintf(file, "covers_path = %s\n", covers_path);
	fprintf(file, "covers2d_path = %s\n", covers2d_path);
	fprintf(file, "coversFull_path = %s\n", coversFull_path);
	fprintf(file, "theme_path = %s\n", theme_path);
	fprintf(file, "theme = %s\n", theme);
	fprintf(file, "disc_path = %s\n", disc_path);
	fprintf(file, "language_path = %s\n", language_path);
	fprintf(file, "languagefiles_path = %s\n", languagefiles_path);
	fprintf(file, "TxtCheatcodespath = %s\n", TxtCheatcodespath);
	fprintf(file, "titlestxt_path = %s\n", titlestxt_path);
	fprintf(file, "gamesound = %d\n", gamesound);
	fprintf(file, "dolpath = %s\n", dolpath);
	fprintf(file, "ogg_path = %s\n", ogg_path);
	fprintf(file, "wiilight = %d\n", wiilight);
	fprintf(file, "gameDisplay = %d\n", gameDisplay);
	fprintf(file, "update_path = %s\n", update_path);
	fprintf(file, "homebrewapps_path = %s\n", homebrewapps_path);
	fprintf(file, "BNRCachePath = %s\n", BNRCachePath);
	fprintf(file, "Cheatcodespath = %s\n", Cheatcodespath);
	fprintf(file, "BcaCodepath = %s\n", BcaCodepath);
	fprintf(file, "WipCodepath = %s\n", WipCodepath);
	fprintf(file, "WDMpath = %s\n", WDMpath);
	fprintf(file, "titlesOverride = %d\n", titlesOverride);
	fprintf(file, "ForceDiscTitles = %d\n", ForceDiscTitles);
	fprintf(file, "patchcountrystrings = %d\n", patchcountrystrings);
	fprintf(file, "screensaver = %d\n", screensaver);
	fprintf(file, "musicloopmode = %d\n", musicloopmode);
	fprintf(file, "autonetwork = %d\n", autonetwork);
	fprintf(file, "discart = %d\n", discart);
	fprintf(file, "coversfull = %d\n", coversfull);
	fprintf(file, "partition = %d\n", partition);
	fprintf(file, "marknewtitles = %d\n", marknewtitles);
	fprintf(file, "ShowFreeSpace = %d\n", ShowFreeSpace);
	fprintf(file, "InstallToDir = %d\n", InstallToDir);
	fprintf(file, "GameSplit = %d\n", GameSplit);
	fprintf(file, "InstallPartitions = %08X\n", InstallPartitions);
	fprintf(file, "PlaylogUpdate = %d\n", PlaylogUpdate);
	fprintf(file, "ParentalBlocks = %08X\n", ParentalBlocks);
	fprintf(file, "returnTo = %s\n", returnTo);
	fprintf(file, "HomeMenu = %d\n", HomeMenu);
	fprintf(file, "MultiplePartitions = %d\n", MultiplePartitions);
	fprintf(file, "USBPort = %d\n", USBPort);
	fprintf(file, "USBAutoMount = %d\n", USBAutoMount);
	fprintf(file, "CacheTitles = %d\n", CacheTitles);
	fprintf(file, "BlockIOSReload = %d\n", BlockIOSReload);
	fprintf(file, "WSFactor = %0.3f\n", WSFactor);
	fprintf(file, "FontScaleFactor = %0.3f\n", FontScaleFactor);
	fprintf(file, "ClockFontScaleFactor = %0.3f\n", ClockFontScaleFactor);
	fprintf(file, "EnabledCategories = ");
	for(u32 i = 0; i < EnabledCategories.size(); ++i)
	{
		fprintf(file, "%i", EnabledCategories[i]);
		if(i+1 < EnabledCategories.size())
			fprintf(file, ",");
	}
	fprintf(file, "\n");
	fprintf(file, "RequiredCategories = ");
	for(u32 i = 0; i < RequiredCategories.size(); ++i)
	{
		fprintf(file, "%i", RequiredCategories[i]);
		if(i+1 < RequiredCategories.size())
			fprintf(file, ",");
	}
	fprintf(file, "\n");
	fprintf(file, "ForbiddenCategories = ");
	for(u32 i = 0; i < ForbiddenCategories.size(); ++i)
	{
		fprintf(file, "%i", ForbiddenCategories[i]);
		if(i+1 < ForbiddenCategories.size())
			fprintf(file, ",");
	}
	fprintf(file, "\n");
	fprintf(file, "Wiinnertag = %d\n", Wiinnertag);
	fprintf(file, "WiinnertagPath = %s\n", WiinnertagPath);
	fprintf(file, "SelectedGame = %d\n", SelectedGame);
	fprintf(file, "GameListOffset = %d\n", GameListOffset);
	fprintf(file, "sneekVideoPatch = %d\n", sneekVideoPatch);
	fprintf(file, "NandEmuMode = %d\n", NandEmuMode);
	fprintf(file, "NandEmuChanMode = %d\n", NandEmuChanMode);
	fprintf(file, "NandEmuPath = %s\n", NandEmuPath);
	fprintf(file, "NandEmuChanPath = %s\n", NandEmuChanPath);
	fprintf(file, "UseSystemFont = %d\n", UseSystemFont);
	fprintf(file, "Hooktype = %d\n", Hooktype);
	fprintf(file, "WiirdDebugger = %d\n", WiirdDebugger);
	fprintf(file, "WiirdDebuggerPause = %d\n", WiirdDebuggerPause);
	fprintf(file, "ShowPlayCount = %d\n", ShowPlayCount);
	fprintf(file, "LoaderMode = %d\n", LoaderMode);
	fprintf(file, "SearchMode = %d\n", SearchMode);
	fprintf(file, "GameAspectRatio = %d\n", GameAspectRatio);
	fprintf(file, "PointerSpeed = %g\n", PointerSpeed);
	fprintf(file, "UseChanLauncher = %d\n", UseChanLauncher);
	fprintf(file, "AdjustOverscanX = %d\n", AdjustOverscanX);
	fprintf(file, "AdjustOverscanY = %d\n", AdjustOverscanY);
	fprintf(file, "TooltipDelay = %d\n", TooltipDelay);
	fprintf(file, "GameWindowMode = %d\n", GameWindowMode);
	fprintf(file, "CacheBNRFiles = %d\n", CacheBNRFiles);
	fprintf(file, "BannerAnimStart = %d\n", BannerAnimStart);
	fprintf(file, "BannerGridSpeed = %g\n", BannerGridSpeed);
	fprintf(file, "BannerZoomDuration = %d\n", BannerZoomDuration);
	fprintf(file, "BannerProjectionOffsetX = %g\n", BannerProjectionOffsetX);
	fprintf(file, "BannerProjectionOffsetY = %g\n", BannerProjectionOffsetY);
	fprintf(file, "BannerProjectionWidth = %g\n", BannerProjectionWidth);
	fprintf(file, "BannerProjectionHeight = %g\n", BannerProjectionHeight);
	fprintf(file, "GCBannerScale = %g\n", GCBannerScale);
	fprintf(file, "GameCubePath = %s\n", GameCubePath);
	fprintf(file, "GameCubeSDPath = %s\n", GameCubeSDPath);
	fprintf(file, "GameCubeMode = %d\n", GameCubeMode);
	fprintf(file, "GameCubeSource = %d\n", GameCubeSource);
	fprintf(file, "MultiDiscPrompt = %d\n", MultiDiscPrompt);
	fprintf(file, "DMLVideo = %d\n", DMLVideo);
	fprintf(file, "DMLProgPatch = %d\n", DMLProgPatch);
	fprintf(file, "DMLNMM = %d\n", DMLNMM);
	fprintf(file, "DMLActivityLED = %d\n", DMLActivityLED);
	fprintf(file, "DMLPADHOOK = %d\n", DMLPADHOOK);
	fprintf(file, "DMLNoDisc2 = %d\n", DMLNoDisc2);
	fprintf(file, "DMLWidescreen = %d\n", DMLWidescreen);
	fprintf(file, "DMLScreenshot = %d\n", DMLScreenshot);
	fprintf(file, "DMLJPNPatch = %d\n", DMLJPNPatch);
	fprintf(file, "DMLDebug = %d\n", DMLDebug);
	fprintf(file, "NINDeflicker = %d\n", NINDeflicker);
	fprintf(file, "NINPal50Patch = %d\n", NINPal50Patch);
	fprintf(file, "NINWiiUWide = %d\n", NINWiiUWide);
	fprintf(file, "NINVideoScale = %d\n", NINVideoScale);
	fprintf(file, "NINVideoOffset = %d\n", NINVideoOffset);
	fprintf(file, "NINRemlimit = %d\n", NINRemlimit);
	fprintf(file, "NINMCEmulation = %d\n", NINMCEmulation);
	fprintf(file, "NINMCSize = %d\n", NINMCSize);
	fprintf(file, "NINAutoboot = %d\n", NINAutoboot);
	fprintf(file, "NINSettings = %d\n", NINSettings);
	fprintf(file, "NINUSBHID = %d\n", NINUSBHID);
	fprintf(file, "NINMaxPads = %d\n", NINMaxPads);
	fprintf(file, "NINNativeSI = %d\n", NINNativeSI);
	fprintf(file, "NINOSReport = %d\n", NINOSReport);
	fprintf(file, "NINLED = %d\n", NINLED);
	fprintf(file, "NINLog = %d\n", NINLog);
	fprintf(file, "DEVOMCEmulation = %d\n", DEVOMCEmulation);
	fprintf(file, "DEVOWidescreen = %d\n", DEVOWidescreen);
	fprintf(file, "DEVOActivityLED = %d\n", DEVOActivityLED);
	fprintf(file, "DEVOFZeroAX = %d\n", DEVOFZeroAX);
	fprintf(file, "DEVOTimerFix = %d\n", DEVOTimerFix);
	fprintf(file, "DEVODButtons = %d\n", DEVODButtons);
	fprintf(file, "DEVOCropOverscan = %d\n", DEVOCropOverscan);
	fprintf(file, "DEVODiscDelay = %d\n", DEVODiscDelay);
	fprintf(file, "DEVOLoaderPath = %s\n", DEVOLoaderPath);
	fprintf(file, "NINLoaderPath = %s\n", NINLoaderPath);
	fprintf(file, "GCInstallCompressed = %d\n", GCInstallCompressed);
	fprintf(file, "GCInstallAligned = %d\n", GCInstallAligned);
	fprintf(file, "PrivateServer = %d\n", PrivateServer);
	fprintf(file, "CustomBannersURL = %s\n", CustomBannersURL);
	fclose(file);

	return true;
}
コード例 #14
0
ファイル: GameLauncher.cpp プロジェクト: Axel-F/loadiine_gx2
int GameLauncher::loadGameToMemory(const discHeader *header)
{
    if(!header)
        return INVALID_INPUT;

    //! initialize our tables required for the games
    memoryInitAreaTable();
    rpxRplTableInit();

    DirList rpxList(header->gamepath + RPX_RPL_PATH, ".rpx", DirList::Files);

    if(rpxList.GetFilecount() == 0)
    {
        log_printf("RPX file not found!\n");
        return RPX_NOT_FOUND;
    }
    if(rpxList.GetFilecount() != 1)
    {
        log_printf("Warning: Too many RPX files in the folder! Found %i files! Using first one.\n", rpxList.GetFilecount());
        //return TOO_MANY_RPX_NOT_FOUND;
    }

    u32 entryIndex = 0;
    std::string rpxName;
    std::vector<std::string> rplImportList;
    std::set<int> rplImportFileIdx;

    DirList rplList(header->gamepath + RPX_RPL_PATH, ".rpl", DirList::Files);

    int result = LoadRpxRplToMem(rpxList.GetFilepath(0), rpxList.GetFilename(0), true, entryIndex++, rplImportList);
    if(result < 0)
    {
        log_printf("Failed loading RPX file %s, error %i\n", rpxList.GetFilepath(0), result);
        return result;
    }

    rpxName = rpxList.GetFilename(0);

    //! get all imports from the RPX
    GetRpxImports(rpxRplTableGet(), rplImportList);

    for(int i = 0; i < rplList.GetFilecount(); i++)
    {
        rplImportFileIdx.insert(i);
    }
    
    //! check for static rpls and load them
    bool importsAdded;
    do
    {
        importsAdded = false;
        for(std::set<int>::iterator it = rplImportFileIdx.begin(); it != rplImportFileIdx.end();)
        {
            int num = *it;
            if(std::find(rplImportList.begin(), rplImportList.end(), rplList.GetFilename(num)) != rplImportList.end())
            {
                result = LoadRpxRplToMem(rplList.GetFilepath(num), rplList.GetFilename(num), false, entryIndex++, rplImportList);
                if(result < 0)
                {
                    log_printf("Failed loading RPL file %s, error %i\n", rplList.GetFilepath(num), result);
                    return result;
                }
                importsAdded = true;
                it = rplImportFileIdx.erase(it);
            }
            else
            {
                it++;
            }
        }
    } while (importsAdded);

    //! load dynamic rpls
    for(std::set<int>::iterator it = rplImportFileIdx.begin(); it != rplImportFileIdx.end(); it++)
    {
        int num = *it;
        result = LoadRpxRplToMem(rplList.GetFilepath(num), rplList.GetFilename(num), false, entryIndex++, rplImportList);
        if(result < 0)
        {
            log_printf("Failed loading RPL file %s, error %i\n", rplList.GetFilepath(num), result);
            return result;
        }
    }

    //! TODO: clean this path creation up
    std::string game_dir = header->gamepath;
    size_t pos = game_dir.rfind('/');

    if(pos != std::string::npos)
        game_dir = game_dir.substr(pos + 1);

    //! set the save game path from the gamenames path
    std::string saveGamePath = CSettings::getValueAsString(CSettings::GameSavePath) + "/" + game_dir;
    std::string saveGamePathCommon;
    std::string saveGamePathUser;

    if(CSettings::getValueAsU8(CSettings::GameSaveMode) == GAME_SAVES_SHARED)
    {
        saveGamePathUser = "******";
        saveGamePathCommon = "c";
    }
    else
    {
        /* get persistent ID - thanks to Maschell */
        unsigned int nn_act_handle;
        unsigned long (*GetPersistentIdEx)(unsigned char);
        int (*GetSlotNo)(void);
        void (*nn_Initialize)(void);
        void (*nn_Finalize)(void);
        OSDynLoad_Acquire("nn_act.rpl", &nn_act_handle);
        OSDynLoad_FindExport(nn_act_handle, 0, "GetPersistentIdEx__Q2_2nn3actFUc", &GetPersistentIdEx);
        OSDynLoad_FindExport(nn_act_handle, 0, "GetSlotNo__Q2_2nn3actFv", &GetSlotNo);
        OSDynLoad_FindExport(nn_act_handle, 0, "Initialize__Q2_2nn3actFv", &nn_Initialize);
        OSDynLoad_FindExport(nn_act_handle, 0, "Finalize__Q2_2nn3actFv", &nn_Finalize);

        nn_Initialize(); // To be sure that it is really Initialized

        unsigned char slotno = GetSlotNo();
        unsigned int persistentID = GetPersistentIdEx(slotno);
        nn_Finalize(); //must be called an equal number of times to nn_Initialize

        char persistentIdString[10];
        snprintf(persistentIdString, sizeof(persistentIdString), "%08X", persistentID);

        saveGamePathUser = persistentIdString;
        saveGamePathCommon = "common";
    }

    CreateSubfolder((saveGamePath + "/" + saveGamePathUser).c_str());
    CreateSubfolder((saveGamePath + "/" + saveGamePathCommon).c_str());

    std::string tempPath = CSettings::getValueAsString(CSettings::GamePath);
    //! remove "sd:" and replace with "/vol/external01"
    pos = tempPath.find('/');
    if(pos != std::string::npos)
        tempPath = std::string(CAFE_OS_SD_PATH) + tempPath.substr(pos);

    strlcpy(gamePathStruct.os_game_path_base, tempPath.c_str(), sizeof(gamePathStruct.os_game_path_base));

    tempPath = CSettings::getValueAsString(CSettings::GameSavePath);
    //! remove "sd:" and replace with "/vol/external01"
    pos = tempPath.find('/');
    if(pos != std::string::npos)
        tempPath = std::string(CAFE_OS_SD_PATH) + tempPath.substr(pos);

    strlcpy(gamePathStruct.os_save_path_base, tempPath.c_str(), sizeof(gamePathStruct.os_save_path_base));
    strlcpy(gamePathStruct.game_dir, game_dir.c_str(), sizeof(gamePathStruct.game_dir));
    strlcpy(gamePathStruct.save_dir_common, saveGamePathCommon.c_str(), sizeof(gamePathStruct.save_dir_common));
    strlcpy(gamePathStruct.save_dir_user, saveGamePathUser.c_str(), sizeof(gamePathStruct.save_dir_user));

    log_printf("gamePathStruct.os_game_path_base: %s\n", gamePathStruct.os_game_path_base);
    log_printf("gamePathStruct.os_save_path_base: %s\n", gamePathStruct.os_save_path_base);
    log_printf("gamePathStruct.game_dir:          %s\n", gamePathStruct.game_dir);
    log_printf("gamePathStruct.save_dir_common:   %s\n", gamePathStruct.save_dir_common);
    log_printf("gamePathStruct.save_dir_user:     %s\n", gamePathStruct.save_dir_user);

    LoadXmlParameters(&cosAppXmlInfoStruct, rpxName.c_str(), (header->gamepath + RPX_RPL_PATH).c_str());

    DCFlushRange((void*)&cosAppXmlInfoStruct, sizeof(ReducedCosAppXmlInfo));

    log_printf("XML Launching Parameters\n");
    log_printf("rpx_name:        %s\n", cosAppXmlInfoStruct.rpx_name);
    log_printf("version_cos_xml: %i\n", cosAppXmlInfoStruct.version_cos_xml);
    log_printf("os_version:      %08X%08X\n", (unsigned int)(cosAppXmlInfoStruct.os_version >> 32), (unsigned int)(cosAppXmlInfoStruct.os_version & 0xFFFFFFFF));
    log_printf("title_id:        %08X%08X\n", (unsigned int)(cosAppXmlInfoStruct.title_id >> 32), (unsigned int)(cosAppXmlInfoStruct.title_id & 0xFFFFFFFF));
    log_printf("app_type:        %08X\n", cosAppXmlInfoStruct.app_type);
    log_printf("cmdFlags:        %08X\n", cosAppXmlInfoStruct.cmdFlags);
    log_printf("max_size:        %08X\n", cosAppXmlInfoStruct.max_size);
    log_printf("avail_size:      %08X\n", cosAppXmlInfoStruct.avail_size);
    log_printf("codegen_size:    %08X\n", cosAppXmlInfoStruct.codegen_size);
    log_printf("codegen_core:    %08X\n", cosAppXmlInfoStruct.codegen_core);
    log_printf("max_codesize:    %08X\n", cosAppXmlInfoStruct.max_codesize);
    log_printf("overlay_arena:   %08X\n", cosAppXmlInfoStruct.overlay_arena);
    log_printf("sdk_version:     %i\n", cosAppXmlInfoStruct.sdk_version);
    log_printf("title_version:   %08X\n", cosAppXmlInfoStruct.title_version);

    return 0;
}
コード例 #15
0
ファイル: ZipFile.cpp プロジェクト: Gamer125/wiibrowser
int ZipFile::ExtractAll(const char *dest)
{
    if(!SwitchMode(OPEN))
        return -1;

    bool Stop = false;

    u32 blocksize = 1024*70;
    void *buffer = malloc(blocksize);

    if(!buffer)
        return -5;

    char writepath[1024];
    char filename[1024];
    memset(writepath, 0, sizeof(writepath));
    memset(filename, 0, sizeof(filename));

    unz_file_info cur_file_info;

    int ret = unzGoToFirstFile(uzFile);
    if(ret != UNZ_OK)
    {
        free(buffer);
        return -6;
    }

    while(!Stop)
    {
        if(unzGetCurrentFileInfo(uzFile, &cur_file_info, filename, sizeof(filename), NULL, 0, NULL, 0) != UNZ_OK)
        {
            Stop = true;
        }

        if(!Stop && filename[strlen(filename)-1] != '/')
        {
            u64 uncompressed_size = cur_file_info.uncompressed_size;

            u64 done = 0;
            char *pointer = NULL;

            ret = unzOpenCurrentFile(uzFile);

            snprintf(writepath, sizeof(writepath), "%s/%s", dest, filename);

            pointer = strrchr(writepath, '/');
            int position = pointer-writepath+2;

            char temppath[strlen(writepath)];
            snprintf(temppath, position, "%s", writepath);

            CreateSubfolder(temppath);

            if(ret == UNZ_OK)
            {
                FILE *pfile = fopen(writepath, "wb");
                if(!pfile)
                {
                    free(buffer);
                    fclose(pfile);
                    unzCloseCurrentFile(uzFile);
                    return -8;
                }

                do
                {
                    if(uncompressed_size - done < blocksize)
                        blocksize = uncompressed_size - done;

                    ret = unzReadCurrentFile(uzFile, buffer, blocksize);

                    if(ret == 0)
                        break;

                    fwrite(buffer, 1, blocksize, pfile);

                    done += ret;

                } while(done < uncompressed_size);

                fclose(pfile);
                unzCloseCurrentFile(uzFile);
            }
        }
        if(unzGoToNextFile(uzFile) != UNZ_OK)
        {
            Stop = true;
        }
    }

    free(buffer);
    buffer = NULL;

    return 1;
}
コード例 #16
0
/****************************************************************************
 * Update the language files
 ***************************************************************************/
bool UpdateTask::UpdateLanguageFiles(void)
{
	if(!IsNetworkInit())
		return false;

	char langpath[150];
	snprintf(langpath, sizeof(langpath), "%s", Settings.LanguagePath);
	if(langpath[strlen(langpath)-1] != '/')
	{
		char * ptr = strrchr(langpath, '/');
		if(ptr)
			ptr[1] = '\0';
	}

	if(!CreateSubfolder(langpath))
	{
		ThrowMsg(tr("Error:"), "%s", tr("Cannot create directory: "), langpath);
		return -1;
	}

	URL_List LinkList(languageUpdateURL);

	if(LinkList.GetURLCount() <= 0)
	{
		ThrowMsg(tr("Error:"), tr("No files found."));
		return -1;
	}

	ProgressWindow::Instance()->StartProgress(tr("Downloading files..."));
	ProgressWindow::Instance()->SetUnit(tr("files"));

	u32 FilesDownloaded = 0;

	for (int i = 0; i < LinkList.GetURLCount(); i++)
	{
		if(ProgressWindow::Instance()->IsCanceled())
			continue;

		ShowProgress(i, LinkList.GetURLCount(), LinkList.GetURL(i));

		char * fileext = strrchr(LinkList.GetURL(i), '.');
		if(!fileext)
			continue;

		if (strcasecmp(fileext, ".lang") != 0)
			continue;

		char fullURL[MAXPATHLEN];
		if(LinkList.IsFullURL(i))
			snprintf(fullURL, sizeof(fullURL), "%s", LinkList.GetURL(i));
		else
			snprintf(fullURL, sizeof(fullURL), "%s%s", languageUpdateURL, LinkList.GetURL(i));

		struct block file = downloadfile(fullURL);

		if (file.data && file.size > 0)
		{
			snprintf(fullURL, sizeof(fullURL), "%s%s", langpath, LinkList.GetURL(i));
			FILE * filePtr = fopen(fullURL, "wb");
			if(filePtr)
			{
				fwrite(file.data, 1, file.size, filePtr);
				fclose(filePtr);
				FilesDownloaded++;
			}
		}

		if(file.data)
			free(file.data);
	}

	// finish up the progress for this file
	ProgressWindow::Instance()->FinishProgress((LinkList.GetURLCount()-1)*20*1024);
	ProgressWindow::Instance()->StopProgress();
	ProgressWindow::Instance()->SetUnit(NULL);

	return FilesDownloaded;
}
コード例 #17
0
int DownloadAllLanguageFiles(int revision)
{
	if(!CreateSubfolder(Settings.languagefiles_path))
	{
		ShowError(tr("Could not create path: %s"), Settings.languagefiles_path);
		return -1;
	}

	if(!IsNetworkInit())
	{
		ShowError(tr("Network is not initiated."));
		return -2;
	}
	char fullURL[300];

	URL_List LinkList(LanguageFilesURL);
	int listsize = LinkList.GetURLCount();
	int files_downloaded = 0;
	char target[6];
	if(revision > 0)
		snprintf(target, sizeof(target), "%d", revision);
	else
		snprintf(target, sizeof(target), "%s", GetRev());

	ShowProgress(tr("Updating Language Files:"), 0, 0, 0, listsize, false, true);

	for (int i = 0; i < listsize; i++)
	{
		const char * filename = strrchr(LinkList.GetURL(i), '/');
		if(filename) filename++;
		else filename = LinkList.GetURL(i);

		if(!filename)
			continue;

		const char * FileExt = strrchr(filename, '.');
		if (!FileExt || strcasecmp(FileExt, ".lang") != 0)
			continue;

		debughelper_printf("%s\n", filename);

		ShowProgress(tr("Updating Language Files:"), 0, filename, i, listsize, false, true);

		snprintf(fullURL, sizeof(fullURL), "%s%s?p=%s", LanguageFilesURL, filename, target);

		struct block file = downloadfile(fullURL);
		if (file.data)
		{
			char filepath[300];
			snprintf(filepath, sizeof(filepath), "%s/%s", Settings.languagefiles_path, filename);
			FILE * pfile = fopen(filepath, "wb");
			if(pfile)
			{
				fwrite(file.data, 1, file.size, pfile);
				fclose(pfile);
				files_downloaded++;
			}
			free(file.data);
		}
	}

	ProgressStop();

	// reload current language file
	if(Settings.language_path[0] != 0)
		Settings.LoadLanguage(Settings.language_path, CONSOLE_DEFAULT);
	else
		Settings.LoadLanguage(NULL, CONSOLE_DEFAULT);

	return files_downloaded;
}
コード例 #18
0
void Explorer::ProcessChoice(int choice)
{
	FileBrowser * browser = (FileBrowser *) curBrowser;
	if(!browser)
		return;

	else if(browser->GetCurrentFilename() && strcmp(browser->GetCurrentFilename(),"..") != 0)
	{
		if(choice == CUT)
		{
			choice = WindowPrompt(browser->GetCurrentFilename(), tr("Cut current marked item(s)?"), tr("Yes"), tr("Cancel"));
			if(choice == 1)
			{
				Clipboard::Instance()->Reset();
				//append selected Item
				browser->MarkCurrentItem();
				//Get ItemMarker
				ItemMarker * IMarker = browser->GetItemMarker();

				for(int i = 0; i < IMarker->GetItemcount(); i++)
					Clipboard::Instance()->AddItem(IMarker->GetItem(i));

				IMarker->Reset();
				Clipboard::Instance()->Operation = OP_MOVE;
			}
		}

		else if(choice == COPY)
		{
			choice = WindowPrompt(browser->GetCurrentFilename(), tr("Copy current marked item(s)?"), tr("Yes"), tr("Cancel"));
			if(choice == 1)
			{
				Clipboard::Instance()->Reset();
				//append selected Item
				browser->MarkCurrentItem();
				//Get ItemMarker
				ItemMarker * IMarker = browser->GetItemMarker();

				for(int i = 0; i < IMarker->GetItemcount(); i++)
					Clipboard::Instance()->AddItem(IMarker->GetItem(i));

				IMarker->Reset();
				Clipboard::Instance()->Operation = OP_COPY;
			}
		}

		else if(choice == RENAME)
		{
			char srcpath[MAXPATHLEN];
			char destdir[MAXPATHLEN];
			snprintf(srcpath, sizeof(srcpath), "%s", browser->GetCurrentSelectedFilepath());
			char entered[151];
			snprintf(entered, sizeof(entered), "%s", browser->GetCurrentFilename());
			int result = OnScreenKeyboard(entered, 150);
			if(result == 1)
			{
				snprintf(destdir, sizeof(destdir), "%s/%s", browser->GetCurrentPath(), entered);
				if(!RenameFile(srcpath, destdir))
					WindowPrompt(tr("Failed renaming item"), tr("Name might already exists."), tr("OK"));
				//! Update browser
				guiBrowser->Refresh();
			}
		}

		else if(choice == DELETE)
		{
			char currentpath[MAXPATHLEN];
			snprintf(currentpath, sizeof(currentpath), "%s/", browser->GetCurrentSelectedFilepath());
			choice = WindowPrompt(browser->GetCurrentFilename(), tr("Delete the selected item(s) and its content?"), tr("Yes"), tr("Cancel"));
			if(choice == 1)
			{
				if(ProgressWindow::Instance()->IsRunning())
					choice = WindowPrompt(tr("Currently a process is running."), tr("Do you want to append this delete to the queue?"), tr("Yes"), tr("Cancel"));

				if(choice == 1)
				{
					//append selected Item
					browser->MarkCurrentItem();
					//Get ItemMarker
					ItemMarker * IMarker = browser->GetItemMarker();
					DeleteTask *task = new DeleteTask(IMarker);
					task->TaskEnd.connect(this, &Explorer::OnFinishedTask);
					this->explorerTasks++;
					Taskbar::Instance()->AddTask(task);
					ThreadedTaskHandler::Instance()->AddTask(task);
					IMarker->Reset();
				}
			}
		}
	}
	else if(choice >= 0 && choice != PASTE && choice != NEWFOLDER && choice != PROPERTIES)
		WindowPrompt(tr("You cant use this operation on:"), tr("Directory .."), tr("OK"));

	if(choice == PASTE)
	{
		choice = WindowPrompt(Clipboard::Instance()->GetItemName(Clipboard::Instance()->GetItemcount()-1), tr("Paste item(s) into current directory?"), tr("Yes"), tr("Cancel"));
		if(choice == 1)
		{
			if(ProgressWindow::Instance()->IsRunning())
				choice = WindowPrompt(tr("Currently a process is running."), tr("Do you want to append this paste to the queue?"), tr("Yes"), tr("Cancel"));

			if(choice == 1)
			{
				if(Clipboard::Instance()->Operation == OP_COPY)
				{
					CopyTask *task = new CopyTask(Clipboard::Instance(), browser->GetCurrentPath());
					task->TaskEnd.connect(this, &Explorer::OnFinishedTask);
					this->explorerTasks++;
					Taskbar::Instance()->AddTask(task);
					ThreadedTaskHandler::Instance()->AddTask(task);
				}
				else if(Clipboard::Instance()->Operation == OP_MOVE)
				{
					MoveTask *task = new MoveTask(Clipboard::Instance(), browser->GetCurrentPath());
					task->TaskEnd.connect(this, &Explorer::OnFinishedTask);
					this->explorerTasks++;
					Taskbar::Instance()->AddTask(task);
					ThreadedTaskHandler::Instance()->AddTask(task);
				}
			}
		}
	}

	else if(choice == ADDTOZIP)
	{
		int ret = WindowPrompt(browser->GetCurrentFilename(), tr("Would you like to add/append the selected item(s) to a zip?"), tr("Yes"), tr("No"));
		if(ret <= 0)
			return;

		char DestZipPath[MAXPATHLEN];
		snprintf(DestZipPath, sizeof(DestZipPath), "%s", browser->GetCurrentPath());
		if(DestZipPath[strlen(DestZipPath)-1] != '/')
			strncat(DestZipPath, "/", sizeof(DestZipPath));
		strncat(DestZipPath, tr("NewZip.zip"), sizeof(DestZipPath));

		if(!OnScreenKeyboard(DestZipPath, sizeof(DestZipPath)))
			return;

		std::string DestPath = DestZipPath;
		size_t pos = DestPath.rfind('/');
		if(pos != std::string::npos)
			DestPath.erase(pos);

		CreateSubfolder(DestPath.c_str());

		//append selected Item
		browser->MarkCurrentItem();
		//Get ItemMarker
		ItemMarker * IMarker = browser->GetItemMarker();

		ZipFile *Zip = new ZipFile(DestZipPath, CheckFile(DestZipPath) ? ZipFile::APPEND : ZipFile::CREATE);
		ArchiveHandle * archive = new ArchiveHandle(Zip);

		PackTask *task = new PackTask(IMarker, "", archive, Settings.CompressionLevel);
		task->TaskEnd.connect(this, &Explorer::OnFinishedTask);
		this->explorerTasks++;
		Taskbar::Instance()->AddTask(task);
		ThreadedTaskHandler::Instance()->AddTask(task);

		//! Update browser
		IMarker->Reset();
	}

	else if(choice == CHECK_MD5)
	{
		int md5Choice = 1;

		if(ProgressWindow::Instance()->IsRunning())
			md5Choice = WindowPrompt(tr("Currently a process is running."), tr("Do you want to append this process to the queue?"), tr("Yes"), tr("Cancel"));

		if(md5Choice == 1)
		{
			char LogPath[1024];
			snprintf(LogPath, sizeof(LogPath), "%s/MD5.log", browser->GetCurrentPath());

			browser->MarkCurrentItem();
			MD5Task *task = new MD5Task(browser->GetItemMarker(), LogPath);
			task->TaskEnd.connect(this, &Explorer::OnFinishedTask);
			this->explorerTasks++;
			Taskbar::Instance()->AddTask(task);
			ThreadedTaskHandler::Instance()->AddTask(task);
			browser->GetItemMarker()->Reset();
		}
	}

	else if(choice == NEWFOLDER)
	{
		char entered[151];
		snprintf(entered, sizeof(entered), tr("New Folder"));
		int result = OnScreenKeyboard(entered, 150);
		if(result == 1)
		{
			char currentpath[MAXPATHLEN];
			snprintf(currentpath, sizeof(currentpath), "%s/%s/", browser->GetCurrentPath(), entered);
			bool ret = CreateSubfolder(currentpath);
			if(ret == false)
				ShowError(tr("Unable to create folder."));

			//! Update browser
			guiBrowser->Refresh();
		}
	}
	else if(choice == PROPERTIES)
	{
		browser->MarkCurrentItem();
		ItemMarker * Marker = browser->GetItemMarker();
		Properties * Prompt = new Properties(Marker);
		Prompt->SetAlignment(ALIGN_CENTER | ALIGN_MIDDLE);
		Prompt->DimBackground(true);
		Application::Instance()->SetUpdateOnly(Prompt);
		Application::Instance()->Append(Prompt);
		Marker->Reset();
	}
}
コード例 #19
0
const u8 * NetReceiver::UncompressData()
{
	if(!filebuffer)
		return NULL;

	//Zip File
	if (filebuffer[0] == 'P' && filebuffer[1] == 'K' && filebuffer[2] == 0x03 && filebuffer[3] == 0x04)
	{
		char temppath[200];
		char tempfilepath[200];
		snprintf(temppath, sizeof(temppath), "%s/WiiXplorerTmp/", Settings.BootDevice);
		snprintf(tempfilepath, sizeof(tempfilepath), "%s/WiiXplorerTmp/tmp.zip", Settings.BootDevice);

		if(!CreateSubfolder(temppath))
		{
			FreeData();
			return NULL;
		}

		FILE * file = fopen(tempfilepath, "wb");
		if(!file)
		{
			FreeData();
			RemoveDirectory(temppath);
			return NULL;
		}

		fwrite(filebuffer, 1, filesize, file);
		fclose(file);

		FreeData();

		ArchiveHandle * Zip = new ArchiveHandle(tempfilepath);
		if(!Zip->ExtractAll(temppath))
		{
			delete Zip;
			RemoveDirectory(temppath);
			return NULL;
		}

		delete Zip;

		DirList Dir(temppath, ".dol,.elf");
		if(Dir.GetFilecount() <= 0)
		{
			RemoveDirectory(temppath);
			ShowError(tr("No homebrew in the zip."));
			return NULL;
		}

		char newfilepath[300];
		snprintf(newfilepath, sizeof(newfilepath), "%s", Dir.GetFilepath(0));
		snprintf(FileName, sizeof(FileName), "%s", Dir.GetFilename(0));

		u8 * buffer = NULL;
		u32 newfilesize = 0;

		if(LoadFileToMem(newfilepath, &buffer, &newfilesize) < 0)
		{
			RemoveDirectory(temppath);
			return NULL;
		}

		RemoveDirectory(temppath);
		filesize = newfilesize;
		filebuffer = buffer;
	}

	//WiiLoad zlib compression
	else if((wiiloadVersion[0] > 0 || wiiloadVersion[1] > 4) && uncfilesize != 0)
	{
		u8 * unc = (u8 *) malloc(uncfilesize);
		if(!unc)
		{
			FreeData();
			return NULL;
		}

		uLongf f = uncfilesize;
		if(uncompress(unc, &f, filebuffer, filesize) != Z_OK)
		{
			free(unc);
			FreeData();
			return NULL;
		}

		free(filebuffer);

		filebuffer = unc;
		filesize = f;
	}

	return filebuffer;
}
コード例 #20
0
ファイル: ZipFile.cpp プロジェクト: Gamer125/wiibrowser
int ZipFile::ExtractFile(int ind, const char *dest, bool withpath)
{
    if(!SwitchMode(OPEN))
        return -1;

    if(!SeekFile(ind) && ind < RealArchiveItemCount)
        return -1;

    ArchiveFileStruct * CurArcFile = GetFileStruct(ind);

    u32 done = 0;

	char * RealFilename = strrchr(CurArcFile->filename, '/');
	if(RealFilename)
        RealFilename += 1;
    else
        RealFilename = CurArcFile->filename;

	char writepath[1024];
	if(withpath)
        snprintf(writepath, sizeof(writepath), "%s/%s", dest, CurArcFile->filename);
    else
        snprintf(writepath, sizeof(writepath), "%s/%s", dest, RealFilename);

	u32 filesize = CurArcFile->length;

    if(CurArcFile->isdir)
    {
        strncat(writepath, "/", sizeof(writepath));
        CreateSubfolder(writepath);
        return 1;
    }

    int ret = unzOpenCurrentFile(uzFile);

    if(ret != UNZ_OK)
        return -2;

    char * temppath = strdup(writepath);
    char * pointer = strrchr(temppath, '/');
    if(pointer)
    {
        pointer += 1;
        pointer[0] = '\0';
    }

    CreateSubfolder(temppath);

    free(temppath);
    temppath = NULL;

    u32 blocksize = 1024*50;
    void *buffer = malloc(blocksize);

    FILE *pfile = fopen(writepath, "wb");
    if(!pfile)
    {
        unzCloseCurrentFile(uzFile);
        free(buffer);
        fclose(pfile);
        WindowPrompt(("Could not extract file:"), CurArcFile->filename, "OK", NULL);
        return -3;
    }

    do
    {
        if(filesize - done < blocksize)
            blocksize = filesize - done;

        ret = unzReadCurrentFile(uzFile, buffer, blocksize);
        if(ret < 0)
        {
            free(buffer);
            fclose(pfile);
            unzCloseCurrentFile(uzFile);
            return -4;
        }

        fwrite(buffer, 1, blocksize, pfile);

        done += ret;

    } while(done < filesize);

    fclose(pfile);
    unzCloseCurrentFile(uzFile);

    free(buffer);

    return 1;
}
コード例 #21
0
bool CSettingsGame::Save()
{
    if(!bChanged)
        return true;

    CreateSubfolder(configPath.c_str());

	std::string filepath = configPath;
	filepath += "/" + this->filename;

	CFile file(filepath, CFile::WriteOnly);
	if (!file.isOpen())
        return false;
	std::string strBuffer;
	strBuffer += strfmt("%s%i\n", VERSION_LINE, VALID_VERSION);

	std::map<std::string,GameSettings>::iterator itr;
	for(itr = settingsGames.begin(); itr != settingsGames.end(); itr++) {

		GameSettings game_settings = itr->second;
		std::vector<CSettingsGame::CSettingsGame::SettingValue> setvalues = getSettingValuesFromGameSettings(game_settings);
		CSettingsGame::SettingValue value;
		strBuffer += strfmt("%s;", itr->first.c_str());
		for(u32 j = 0; j < MAX_VALUE; j++){
			value = setvalues.at(j);
			switch(value.dataType){
				case TypeBool:
					strBuffer += strfmt("%s=%i", settingsNames[j], value.bValue);
					break;
				case TypeS8:
					strBuffer += strfmt("%s=%i", settingsNames[j], value.cValue);
					break;
				case TypeU8:
					strBuffer += strfmt("%s=%i", settingsNames[j], value.ucValue);
					break;
				case TypeS16:
					strBuffer += strfmt("%s=%i", settingsNames[j], value.sValue);
					break;
				case TypeU16:
					strBuffer += strfmt("%s=%i", settingsNames[j], value.usValue);
					break;
				case TypeS32:
					strBuffer += strfmt("%s=%i", settingsNames[j], value.iValue);
					break;
				case TypeU32:
					strBuffer += strfmt("%s=%u", settingsNames[j], value.uiValue);
					break;
				case TypeF32:
					strBuffer += strfmt("%s=%f", settingsNames[j], value.fValue);
					break;
				case TypeString:
					if(value.strValue != NULL)
						strBuffer += strfmt("%s=%s", settingsNames[j], value.strValue->c_str());
					break;
				default:
					break;
			}
			strBuffer += strfmt(";");
		}
		strBuffer += strfmt("\n");
		//Clean pointer
		for(u32 j = 0; j < setvalues.size(); j++){
			if(setvalues.at(j).dataType == TypeString)
				delete setvalues.at(j).strValue;
		}
    }
	file.write((u8*)strBuffer.c_str(), strBuffer.size());
    file.close();
    bChanged = false;

	return true;
}
コード例 #22
0
void MoveTask::Execute(void)
{
	TaskBegin(this);

	// No items to process
	if(Process.GetItemcount() == 0)
	{
		TaskEnd(this);
		return;
	}

	if(ProgressWindow::Instance()->IsRunning())
		ProgressWindow::Instance()->SetTitle(tr("Calculating transfer size..."));
	else
		StartProgress(tr("Calculating transfer size..."));

	ProgressWindow::Instance()->SetTitle(this->getTitle().c_str());

	string destPathSlash = (destPath.size() > 0 && destPath[destPath.size()-1] != '/') ? destPath + '/' : destPath;

	int result = 0;

	//! On same device we move files instead of copy them
	for(int i = 0; i < Process.GetItemcount(); ++i)
	{
		if(CompareDevices(Process.GetItemPath(i), destPathSlash.c_str()))
		{
			string srcpath = Process.GetItemPath(i);
			while(srcpath[srcpath.size()-1] == '/')
				srcpath.erase(srcpath.size()-1);

			const char *pathname = strrchr(srcpath.c_str(), '/');
			if(!pathname)
				continue;

			string dstpath = destPathSlash + (pathname+1);

			if(strcasecmp(srcpath.c_str(), dstpath.c_str()) == 0)
			{
				//! nothing to be done here
				Process.RemoveItem(Process.GetItem(i));
				i--;
				continue;
			}

			//! moving directory to a path where the same directory name exists
			//! we will move all files and remove src directory in the later process
			if(Process.IsItemDir(i) && CheckFile(dstpath.c_str()))
				continue;

			int ret = MoveFile(srcpath.c_str(), dstpath.c_str());
			if(ret < 0)
				result = ret;

			Process.RemoveItem(Process.GetItem(i));
			i--;
		}
	}

	list<ItemList> itemList;

	if(GetItemList(itemList, true) < 0) {
		result = -1;
	}

	//! free memory of process which is no longer required
	Process.Reset();

	//! On same device we move files instead of copy them
	ProgressWindow::Instance()->SetCompleteValues(0, CopySize);

	for(list<ItemList>::iterator listItr = itemList.begin(); listItr != itemList.end(); listItr++)
	{
		//! first move/remove all files in all sub directories
		for(list<string>::iterator itr = listItr->files.begin(); itr != listItr->files.end(); itr++)
		{
			if(ProgressWindow::Instance()->IsCanceled())
				break;

			string srcpath = listItr->basepath + *itr;
			string dstpath = destPathSlash + *itr;

			string folderpath = dstpath;
			size_t pos = folderpath.rfind('/');
			if(pos != string::npos)
				folderpath.erase(pos);

			CreateSubfolder(folderpath.c_str());

			int ret = MoveFile(srcpath.c_str(), dstpath.c_str());
			if(ret < 0)
				result = ret;
		}

		//! Remove all dirs reversed as they were appended to the list
		for(list<string>::iterator itr = listItr->dirs.begin(); itr != listItr->dirs.end(); itr++)
		{
			if(ProgressWindow::Instance()->IsCanceled())
				break;

			RemoveFile((listItr->basepath + *itr).c_str());
		}

		if(ProgressWindow::Instance()->IsCanceled())
		{
			result = PROGRESS_CANCELED;
			break;
		}
	}

	if(result < 0 && result != PROGRESS_CANCELED && !Application::isClosing())
	{
		ThrowMsg(tr("Error:"), tr("Failed moving some item(s)."));
	}

	TaskEnd(this);
}
コード例 #23
0
int WiiSave::Download(std::string ID)
{
	if(ID.empty())
		return -1;
	
	//! Check Network
	if (!IsNetworkInit())
	{
		ManageProgressStop();
		
		ManageButtons * connect = new ManageButtons(tr("No network connection"),
													tr("Do you want to connect?"),
													tr("Yes"),
													tr("Cancel"));
		
		connect->SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE);
		connect->SetPosition(-6, 75);
		connect->SetEffect(EFFECT_FADE, 20);
		mainWindow->Append(connect);
		ResumeGui();
		
		while (connect->GetEffect()) usleep(50);
		
		while(!connect->GetChoice()) usleep(50);
		
		connect->SetEffect(EFFECT_FADE, -20);
		
		while (connect->GetEffect()) usleep(50);
		
		HaltGui();
		
		mainWindow->Remove(connect);
		
		ResumeGui();
		
		if(connect->GetChoice() == 1)
		{
			StartManageProgress(tr("Initializing Network"));
			
			Initialize_Network();
			
			ManageProgressStop();
		}
		
		delete connect;
		
		if (!IsNetworkInit())
			return -2;
		
		StartManageProgress(tr("Downloading saveslist:"), "www.wiisave.com");
	}

	//! Generate gameUrl
	std:: string WiiSaveListURL("http://wiisave.com/savegamecode_xml.php?gamecode=");
	WiiSaveListURL += ID.substr(0, 3);
	
	//! Check Connection
	if(!CheckConnection(WiiSaveListURL.c_str()))
	{
		ManageProgressStop();
		return -3;
	}
	
	//! Check Region
	std::string Region;
	switch (ID[3])
	{
		case 'E':
			Region = "E - USA / Canada";
			break;
		case 'J':
			Region = "J - Japanese";
			break;
		case 'W':
			Region = "J - Japanese";//Region = "NTSC T";
			break;
		case 'K':
			Region = "J - Japanese";//Region = "NTSC K";
			break;
		default:
		case 'P':
		case 'D':
		case 'F':
		case 'I':
		case 'S':
		case 'H':
		case 'U':
		case 'X':
		case 'Y':
		case 'Z':
			Region = "P - European / Other / PAL";
			break;
	}
	
	//! Get list
	WiiSave_List * SaveList = new WiiSave_List(WiiSaveListURL.c_str());

	ManageProgressStop();
	
	if (!SaveList->GetCount())
	{
		delete SaveList;
		return -4;
	}
	
	if (!SaveList->FilterList(Region))
	{
		delete SaveList;
		return -5;
	}
	
	//! open browser & select save
	WiiSaveBrowser * SaveBrowser = new WiiSaveBrowser(SaveList);
	mainWindow->Append(SaveBrowser);
	
	SaveBrowser->Show();
	
	int selected = SaveBrowser->GetSelectedSave();
	delete SaveBrowser;
	
	if (selected < 0)
	{
		delete SaveList;
		return -10;
	}
	
	//! select download destination
	ManageButtons * path = new ManageButtons(tr("Select a target path."),
											 tr("Be carrefull, present files can be overwritten"),
											 tr("OK"));
	
	path->SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE);
	path->SetPosition(-6, 75);
	path->SetEffect(EFFECT_FADE, 20);
	mainWindow->Append(path);
	ResumeGui();
	while (path->GetEffect()) usleep(50);
	
	while(!path->GetChoice()) usleep(50);
	
	path->SetEffect(EFFECT_FADE, -20);
	
	while (path->GetEffect()) usleep(50);
	
	HaltGui();
	
	mainWindow->Remove(path);
	delete path;
	
	ResumeGui();
	
	if( selectBrowser(Settings.BrowserPath.c_str(), PATH) != 2 )
	{
		delete SaveList;
		return -10;
	}
	
	//! download file
	std::string filepath = Settings.TmpPath;
	filepath += "/";
	filepath += SaveList->GetFilteredFilename(selected);
	
	if( WiiSave::InternalDownload(SaveList->GetFilteredDownloadLink(selected), filepath) < 0)
	{
		delete SaveList;
		return -6;
	}
	
	delete SaveList;
	
	//! check file type
	char destID[5];
	std::string srcfilepath;
	bool isSgmgxSave = false;
	bool isDataBin = false;
	
	std::string tmpDest = filepath.substr(0, filepath.rfind("/")+1);
	tmpDest += "tmpExtract";
	
	std::string fileext = filepath.substr(filepath.rfind("."));
	if( !Settings.FileExtensions.CompareArchive(fileext.c_str()) ) //! Archive
	{
		StartManageProgress(tr("Extracting files..."));
		
		//! extract files
		ArchiveHandle * Archive = new ArchiveHandle(filepath.c_str());
		
		Archive->ExtractAll(tmpDest.c_str());
		
		delete Archive;
		RemoveFile(filepath.c_str());
		
		//! check save type
		DirList * dirList = new DirList(tmpDest.c_str(), ".bin" , DirList::Files | DirList::Dirs | DirList::CheckSubfolders);
		
		for(int i = 0; i < dirList->GetFilecount(); i++)
		{
			if(!strcmp(dirList->GetFilename(i), "banner.bin"))
			{
				isSgmgxSave = true;
				srcfilepath = dirList->GetFilepath(i);
				break;
			}
			
			std::string name(dirList->GetFilename(i));
			fileext = name.substr(name.rfind("."));
			if( !Settings.FileExtensions.CompareBinaryFiles(fileext.c_str()) )
			{
				SaveInfos * infos = GetSaveInfos(dirList->GetFilepath(i));
				if(infos)
				{
					isDataBin = true;
					srcfilepath = dirList->GetFilepath(i);
					memcpy(destID, infos->ID, 5);
					delete infos;
					break;
				}
			}
		}
		
		delete dirList;
		
		ManageProgressStop();
	}
	else //! check for data.bin file
	{
		StartManageProgress(tr("Verifying file..."));
		
		SaveInfos * infos = GetSaveInfos(filepath);
		if(infos)
		{
			isDataBin = true;
			srcfilepath = filepath;
			memcpy(destID, infos->ID, 5);
			delete infos;
		}
		
		ManageProgressStop();
	}
	
	if(!isDataBin && !isSgmgxSave) //! supported files not found
	{
		RemoveFile(filepath.c_str());
		RemoveDirectory(tmpDest.c_str());
		return -7;
	}
	
	//! write files
	StartManageProgress(tr("Writing files..."));
	if(isSgmgxSave)
	{
		std::string srcfolder = srcfilepath.substr(0, srcfilepath.rfind("/"));
		
		DirList * dirList = new DirList(srcfolder.c_str(), NULL , DirList::Files | DirList::Dirs);
		
		srcfolder = srcfolder.substr(srcfolder.rfind("/"));
		std::string finaldest = Settings.TmpPath;
		finaldest += srcfolder;
		
		CreateSubfolder(finaldest.c_str());
		
		for(int i = 0; i < dirList->GetFilecount(); i++)
		{
			if(IsDir(i))
				CopyDirectory(dirList->GetFilepath(i), finaldest.c_str());
			else
				CopyFile(dirList->GetFilepath(i),  fmt("%s/%s", finaldest.c_str(), dirList->GetFilename(i)));
		}
		
		delete dirList;
	}
	else if(isDataBin)
	{
		std::string finaldest = Settings.TmpPath;
		finaldest += "/";
		finaldest += destID;
		
		CreateSubfolder(finaldest.c_str());
		
		finaldest += "/data.bin";
		CopyFile(srcfilepath.c_str(), finaldest.c_str());
	}
	
	RemoveFile(filepath.c_str());
	RemoveDirectory(tmpDest.c_str());
	ManageProgressStop();
	
	return 1;
}
コード例 #24
0
/****************************************************************************
 * Download a file from a given url to a given path with a Progressbar
 ****************************************************************************/
int DownloadFileToPath(const char *orig_url, const char *dest, bool UseFilename)
{
	if(!orig_url || !dest)
	{
		ShowError(tr("No URL or Path specified."));
		return -2;
	}

	bool addhttp = false;

	if(strncasecmp(orig_url, "http://", strlen("http://")) != 0)
	{
		addhttp = true;
	}

	char url[strlen(orig_url) + (addhttp ? strlen("http://") : 0) + 1];

	if(addhttp)
		snprintf(url, sizeof(url), "http://%s", orig_url);
	else
		strcpy(url, orig_url);

	char *path = strchr(url + strlen("http://"), '/');

	if(!path)
	{
		ShowError(tr("Not a valid URL path"));
		return -2;
	}

	int domainlength = path - url - strlen("http://");

	if(domainlength == 0)
	{
		ShowError(tr("Not a valid domain"));
		return -3;
	}

	char domain[domainlength + 1];
	strncpy(domain, url + strlen("http://"), domainlength);
	domain[domainlength] = '\0';

	int connection = GetConnection(domain);

	if(connection < 0)
	{
		ShowError(tr("Could not connect to the server."));
		return -4;
	}

	char header[1024];
	char * ptr = header;
	ptr += sprintf(ptr, "GET %s HTTP/1.1\r\n", path);
	ptr += sprintf(ptr, "Host: %s\r\n", domain);
	ptr += sprintf(ptr, "Referer: %s\r\n", domain);
	ptr += sprintf(ptr, "User-Agent: WiiXplorer\r\n");
	ptr += sprintf(ptr, "Pragma: no-cache\r\n");
	ptr += sprintf(ptr, "Cache-Control: no-cache\r\n");
	ptr += sprintf(ptr, "Connection: close\r\n\r\n");

	char filename[255];
	memset(filename, 0, sizeof(filename));

	int filesize = network_request(connection, header, filename);

	if(filesize <= 0)
	{
		net_close(connection);
		ShowError(tr("Filesize is %i Byte."), filesize);
		return -5;
	}

	int blocksize = 4*1024;

	u8 *buffer = (u8 *) malloc(blocksize);
	if(!buffer)
	{
		net_close(connection);
		ShowError(tr("Not enough memory."));
		return -6;
	}

	if(UseFilename)
	{
		if(dest[strlen(dest)-1] != '/')
			strcat((char *) dest, "/");

		CreateSubfolder(dest);

		strcat((char *) dest, filename);
	}

	if(!UseFilename && strcmp(filename, "") == 0)
	{
		const char * ptr = strrchr(dest, '/');
		if(ptr) ptr++;
		else ptr = dest;

		snprintf(filename, sizeof(filename), "%s", ptr);
	}

	FILE *file = fopen(dest, "wb");
	if(!file)
	{
		net_close(connection);
		free(buffer);
		ShowError(tr("Cannot write to destination."));
		return -7;
	}

	ProgressCancelEnable(true);
	StartProgress(tr("Downloading file..."), 0, filename, true, true);

	int done = 0;

	while(done < filesize)
	{
		if(ProgressCanceled())
		{
			done = PROGRESS_CANCELED;
			break;
		}

		ShowProgress(done, filesize);

		if(blocksize > filesize - done)
			blocksize = filesize - done;

		s32 read = network_read(connection, buffer, blocksize);

		if(read < 0)
		{
			done = -8;
			ShowError(tr("Transfer failed"));
			break;
		}
		else if(!read)
			break;

		fwrite(buffer, 1, read, file);

		done += read;
	}

	free(buffer);
	ProgressStop();
	net_close(connection);
	fclose(file);
	ProgressStop();
	ProgressCancelEnable(false);

	return done;
}
コード例 #25
0
int NandTitle::ExtractFile(const char *nandPath, const char *filepath)
{
	if(!nandPath || !filepath)
		return -1;

	char *strDup = strdup(filepath);
	if(!strDup)
		return -666;

	char *ptr = strrchr(strDup, '/');
	if(!ptr)
	{
		free(strDup);
		return -333;
	}
	else
	{
		*ptr = 0;
		CreateSubfolder(strDup);
		free(strDup);
	}

	int done = 0;
	int fd = -1;
	int blocksize = 32*1024;
	u8 *buffer = (u8 *) memalign(32, ALIGN32(blocksize));
	if(!buffer)
		return -666;

	fstats *stats = (fstats *) memalign(32, ALIGN32(sizeof(fstats)));
	if(!stats)
	{
		free(buffer);
		return -666;
	}

	do
	{
		fd = ISFS_Open(nandPath, ISFS_OPEN_READ);
		if(fd < 0)
			break;

		int ret = ISFS_GetFileStats(fd, stats);
		if (ret < 0)
			break;

		int filesize = stats->file_length;

		FILE *pFile = fopen(filepath, "wb");
		if(!pFile)
			break;

		while(done < filesize)
		{
			if(filesize-done < blocksize)
				blocksize = filesize-done;

			ret = ISFS_Read(fd, buffer, blocksize);
			if(ret < 0)
			{
				done = ret;
				break;
			}

			fwrite(buffer, 1, ret, pFile);

			done += ret;
		}

		fclose(pFile);

	} while(0);

	free(buffer);
	free(stats);

	if(fd >= 0)
		ISFS_Close(fd);

	return done;

}