blob: 1c326af06cfbed832582bbd5222f590f4594e50a (
plain) (
tree)
|
|
/*
* 4144's whoisonline code.
*
*/
#include "onlinelist.h"
#include <iostream>
#include <fstream>
#include <SDL.h>
#include <SDL_thread.h>
#include <vector>
#include <algorithm>
#include "automation.h"
#include "game.h"
#include "main.h"
#include "utils/stringutils.h"
OnlineList::OnlineList():
mThread(NULL),
mDownloadStatus(UPDATE_LIST),
mDownloadComplete(true),
mAllowUpdate(true),
mOnlinePlayers()
{
download();
}
OnlineList::~OnlineList()
{
if (mThread && SDL_GetThreadID(mThread))
SDL_WaitThread(mThread, NULL);
}
int OnlineList::downloadThread(void *ptr)
{
OnlineList *wio = reinterpret_cast<OnlineList *>(ptr);
std::string namelist = "online.txt";
std::ifstream listFile (namelist.c_str(), std::ifstream::in);
if (!wio->mAllowUpdate)
{
return 0;
}
if (listFile.is_open())
{
wio->mOnlinePlayers.clear();
const std::string gmText = "(GM)";
bool listStarted(false);
while (!listFile.eof())
{
std::string line;
getline(listFile, line);
if (!line.empty())
{
std::string lineStr = line;
utils_trim(lineStr);
std::string::size_type pos = lineStr.find(gmText, 0);
if (pos != std::string::npos && pos == lineStr.length() - gmText.length())
{
lineStr = lineStr.substr(0, pos-1);
utils_trim(lineStr);
}
if (listStarted == true)
{
size_t found = lineStr.find(" users are online."); //Dodgy hack!
if (found == std::string::npos)
wio->mOnlinePlayers.insert(lineStr);
}
else if (lineStr == "------------------------------")
listStarted = true;
}
}
listFile.close();
}
else
{
wio->mDownloadStatus = UPDATE_ERROR;
return 0;
}
wio->mDownloadComplete = true;
return 0;
}
void OnlineList::download()
{
mDownloadComplete = true;
if (mThread && SDL_GetThreadID(mThread))
SDL_WaitThread(mThread, NULL);
mDownloadComplete = false;
mThread = SDL_CreateThread(OnlineList::downloadThread, this);
if (mThread == NULL)
mDownloadStatus = UPDATE_ERROR;
}
void OnlineList::logic()
{
if (!mAllowUpdate)
return;
if (mUpdateTimer == 0)
mUpdateTimer = cur_time;
double timeDiff = difftime(cur_time, mUpdateTimer);
int timeLimit = 2; // Downloads the online list every 20 seconds.
if (timeDiff >= timeLimit && mDownloadStatus != UPDATE_LIST)
{
mUpdateTimer = 0;
mDownloadStatus = UPDATE_LIST;
download();
}
switch (mDownloadStatus)
{
case UPDATE_ERROR:
mDownloadStatus = UPDATE_COMPLETE;
break;
case UPDATE_LIST:
if (mDownloadComplete == true)
{
mDownloadStatus = UPDATE_COMPLETE;
mUpdateTimer = 0;
if (mOnlinePlayers.size() > 0)
Automation::getAutomationHandler()->updateOnline(mOnlinePlayers);
}
break;
default:
break;
}
}
|