JD2022-TU1/main/extern/Camcam/Inc/account.h

518 lines
17 KiB
C++

#ifndef ACCOUNT_H
#define ACCOUNT_H
#include "http_client_curl.h"
#include "browser.h"
#include "upload_task.h"
#include "download_task.h"
#include "buffered_request.h"
#include <map>
#include <string>
#include "card.h"
typedef unsigned int TDBIndex;
const int ERROR_MISSING_ARG = 1;
const int ERROR_INVALID_TOKEN = 5;
const int ERROR_DUAL_LOGIN = 6;
const int ERROR_VERSION_MISMATCH = 7;
const int ERROR_ENDOF_DEMO = 26;
const int ERROR_PAGE_DELETED_ACCOUNT = 24;
const int ERROR_PAGE_BANNED_ACCOUNT = 25;
const int ERROR_OBSOLETE_MACADDRESS = 27;
const int ERROR_MANDATORY_PATCH = 20000;
class CLogInTask;
class FacebookSession;
/**
* Storage for hardware and system configuration string
*/
class HardwareSnapshot
{
public:
HardwareSnapshot() { _Md5[0] = '\0'; }
void fetchData();
bool isDifferent(const char *otherMd5);
const std::string& str() { return _Str; }
std::string md5() { return std::string(_Md5); }
#ifndef USER_MODE
unsigned int getMemoryUsage() const;
#endif
//void clear();
private:
std::string _Str;
char _Md5[64];
};
/**
* Online account management
*/
class CCamCamAccount : public CamCamHttpClient , public BrowserObserver
{
public:
enum WebPage { Profile, Collection, BugReport, Forum, Help, MoreCredits, Register, NbWebPages };
CCamCamAccount() : _TeaserBrowser(NULL), _YouUpAdBrowser(NULL), _LoginBrowser(NULL), _WebBrowser(NULL),
_ShopBrowser(NULL), _UploadingWindowHasForm(false), _ArticleIsDeleted(true),
_VideoPublishingState(Off), _PublishThumbnailFilenames(false), _LogInTask(NULL), _CardsToPublishJo(NULL),
_Credits(~0), _CreditsUnspent(false), _IsLogged(false), _HardwareSnapshot(NULL), _HasBeenLogged(false), _FacebookSession(NULL) {}
~CCamCamAccount() { if (_WebBrowser) delete _WebBrowser; if (_ShopBrowser ) delete _ShopBrowser; }
/// Initialize
bool init();
/// Set settings
void configure(const char *languageCode, bool publishThumbnailFilenames=false);
/// Deinitialize
void release();
///// Return true if the demo and beta versions are currently the same
//bool sameCurrentDemoAndBeta();
//
///// Return the gameid of the current beta version, or empty if the beta and demo don't match
//std::string getBetaGameId();
enum ConnectionMode {
CNT_NORMAL = 0,
CNT_ANONYMOUS,
CNT_LIMITED_CARDS_MORE,
CNT_LIMITED_CARDS,
CNT_ENDOF_DEMO = 10
};
enum RegisterMode {
RGT_NORMAL = 0,
RGT_DAY,
RGT_TIME,
RGT_BOTH
};
/// Get connection mode
ConnectionMode getConnectionMode() { return _ConnectionMode; }
/// Log-in
bool startAnonymousLogin(RegisterMode registerM, ConnectionMode connection);
bool startLogoutPage();
bool startLoginPage(bool autoLogIn = false, ConnectionMode connection = CNT_NORMAL, RegisterMode registerM = RGT_NORMAL); // start log page
bool logInClassic(const char *login, const char *password);
bool logInSSO(const char *token, const char *source);
friend CLogInTask;
enum LogInProgressState { InProgress=0, Success=1, Failed=2, Finished=3, NbProgressStates };
/// Start Log-in in background thread. Use along with getAsyncLogInProgressState().
bool startAsyncLogInClassic(const char *login, const char *password);
/// Start Log-in in background thread. Use along with getAsyncLogInProgressState(). [If token is NULL, the MAC address can be used for the anonymous mode (disabled)].
bool startAsyncLogInSSO(const char *token, const char *source);
/// Check if async Log-in has completed, and return status (Success/Failed) on first call after completion
LogInProgressState getAsyncLogInProgressState();
/// Log-out
bool logOut(bool forceLogOut = false);
int getProtocolNum() const;
int getIdAccount() const { return atoi(_IdAccount.c_str()); }
// Return true if the account is ready for requests (other than the log-in request)
bool isLoggedIn() const { return _IsLogged; }
// Get Login
const SimpleString<256>& getLogin() const { return _Login; } // getLogin().clear() is atomic regarding getLogin().empty()
/** Return a json object (NULL if not logged-in, in case of error, or if it has already been called before).
* Important: the caller must free it after usage using json_object_put().
*/
json_object * getCardJson();
/// Check if the server has new cards, and refresh the cards if so
bool checkRefreshCards();
/// Get an update of cards. If buffer is NULL, a request will be made to the server.
bool updateCards(HttpPage *assetsBuffer=NULL);
//bool addCredits(int amount);
int getCredits() const { return _Credits; }
int areCreditsUnspent() const { return _CreditsUnspent; }
/// Get initialization code for a type of media specified by inifile
//const char *getAssetListStr(const char *iniFilename, size_t *assetListSize);
double getDownloadProgress();
double getDownloadCurrent();
double getDownloadTotal();
bool cardIsCurrentlyDownloaded(CardElement::Type cardType, u32 id);
bool isDownloading();
bool ensureThumbnailPresent(CardElement::Type cardType, u32 id, u32 idMedia, lua_State * L);
/// If an asset (disguise etc.) zcc is not locally present, download it from the server. Anyway, unpack it.
bool ensureAssetPresent(u32 idZcc, bool immediateUnpacking);
/// Set the actual filename for a zcc name (max 2047 chars)
void getZCCFilename(u32 idZcc, char *filename);
/// Ask to server info about one specific card
bool getAssetInfo(u32 idAsset);
/// Delete all files unpacked from our ZCC list (but keep the ZCC files). Needs the background download task to have been stopped, needs the cards to be available.
void compactAssetCache();
/// If an asset zcc is in download queue, move it to start of queue
bool expediteDownload(CardElement::Type cardType, u32 idZcc);
/// Call onDownloaded() on completed downloads, and clean their data. Call this evenly from the main thread.
void checkCompletedDownloads();
HDC getBrowserHandle(int browser);
// ***************************************************************************
enum VideoPublishingState {
VPS0_LOW, Off=VPS0_LOW, VPS0_HIGH=Off,
VPS1_LOW, Selection=VPS1_LOW, VPS1_HIGH=Selection,
VPSC_LOW, CancelledSelection=VPSC_LOW, CancelledMetadata, CancelledUploadError, VPSC_HIGH=CancelledUploadError,
VPSU_LOW, UploadingEditMetadata=VPSU_LOW, UploadingSubmitted, CancellingMetadata, UploadedEditMetadata, VPSU_HIGH=UploadedEditMetadata,
VPSD_LOW, ExternalSiteOpened=VPSD_LOW, UploadedSubmitted, VPSD_HIGH=UploadedSubmitted };
enum VideoPublishingEvent { OpenSelection, Cancel, CancelEnd, OpenExternalSite, OpenEditMetadata,
SubmitMetadata, CompleteUploading, UploadingError };
/// Cancel last article sent in DB
bool cancelArticle();
// Open upload page for YouUp, or change Login page if needed
bool selectVideoSite(const char *filename, const char *tbFilename, u32 durationInSec, const char *tempVideo);
// Open a page to select the video site to upload the video (not youup one)
bool selectVideoSiteAfterUpload();
/// Get hash of a video
SimpleString<41> getVideoHash(const char *filename);
/// Return if the video exists on server, if hash is NULL, we will get it
bool isAlreadyUploaded(const char *filename, const char* hash = NULL);
// Start sending the files asynchronously to Ubitube
bool uploadFileToUbitube(const char *filename, const char *tbFilename, u32 durationInSec, const char *tempVideo);
// Get progress value from 0 to 100 (100=completed, -1=failed)
s32 getUploadProgressPct();
// ***************************************************************************
/// Create activeX youup pub
bool createYouUpAdPage();
/// Return true if the Ad is init
bool isYouUpAdInit() const { return (_YouUpAdBrowser!=NULL) && _YouUpAdBrowser->GetOwnWindow() != NULL; }
/// Close activeX
void closeYouUpAdPage();
/// Hide/Show the browser for youup
void setYouUpAdPageVisible(bool visible);
/// Set pos and size of the youup pub
void youUpSetPosAndSize(int x, int y, int w, int h);
/// IS the youup ad visible ?
bool isYouUpAdVisible() const { return (_YouUpAdBrowser!=NULL) && _YouUpAdBrowser->isVisible(); }
/// Relead pub with a specific param
void reloadYouUpAdPage(int page, bool displayJustOneTime = true);
/// Open the login page
bool openLoginPage(char *url);
/// Open the login page, guest version
bool openGuestPage(char *arg = NULL);
/// Return the correct page to call
const char* getPage(WebPage page);
/// Call a lua callback to display the ActiveX
bool callGuestPage(const char* page);
/// Close the login/guest page
void closeLoginPage();
/// Set pos and size of the shop browser
void loginSetPosAndSize(int x, int y, int w, int h);
/// Return true if the log-in page has the focus
bool logInPageHasFocus() const { if (_LoginBrowser) return _LoginBrowser->hasFocus(); else return false; }
/// Return true if the youup pub has the focus
bool youupPugPageHasFocus();
/// Open the video upload page
bool openVideoWebPage(char *url);
/// Close the video upload page
void closeVideoWebPage();
/// Cancel the current upload
void cancelVideoUploading();
/// Webbrowser visibility (video)
bool isVideoWebPageVisible() const { return _WebBrowser && _WebBrowser->isVisible(); }
/// Return the URL for the auto-logged-in website, or a blank string in case of error
std::string getLoggedProfileURL(WebPage page);
/// Return the URL with token
std::string getLoggedURL(const char * url);
bool openTeaserPage(int idArticle);
void closeTeaserPage();
void setTeaserPage(int x, int y, int w, int h);
bool isTeaserVisible() const { return (_TeaserBrowser!=NULL) && _TeaserBrowser->isVisible(); }
void setTeaserVisible(bool visible);
/// Open/close
void setShopVisible(bool visible, const char *pageAndParams="");
/// Is the internal browser visible?
bool isShopVisible() const { return (_ShopBrowser!=NULL) && _ShopBrowser->isVisible(); }
/// Open a shop page (shop must be already open)
bool shopNavigate(const char *pageAndParams);
/// Set pos and size of the shop browser
void shopSetPosAndSize(int x, int y, int w, int h);
/// Return true if the shop has the focus
bool shopHasFocus() const;
/// Return true if the shop has the focus
bool uploadBrowserHasFocus() const { if (_WebBrowser) return _WebBrowser->hasFocus(); else return false; }
/// Get auth token, then navigate to page
bool navigateWithAuth(const char *pageAndParams, CWebBrowser *browser);
/// Report an event from the internal browser
void onBrowserEvent(const char *event, CWebBrowser *srcBrowser);
/// Return the browser id corresponding to the specified pointer
int getBrowserId(const CWebBrowser *browser) { if (browser == _LoginBrowser) return 0; else if (browser == _WebBrowser) return 1; else if (browser == _ShopBrowser) return 2; else if (browser == _YouUpAdBrowser) return 3; else return -1; }
/// Check if the url is authorized in the internal log-in browser, otherwise open if in external browser
bool passInternalWebpageFilter(const char *url, CWebBrowser *srcBrowser);
/// Open the default external browser (Firefox, IE...)
bool openExternalWebBrowser(const char *url);
/// Put this in the default case of the WndProc of your parent window
void processWindowsMessage(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
if (!_WebBrowser)
return;
_WebBrowser->processWindowsMessage(hWnd, message, wParam, lParam);
}
/// Get browser event
void updateEvent(CWebBrowser* webbrowser, UINT message, WPARAM wParam, void* userEvent);
/// Return the web browser (NULL if not currently open)
CWebBrowser *videoPublishingBrowser() { return _WebBrowser; }
/// Prepare a request to send in the background with controlled streaming frequency
bool addBufferedRequest(const char *destServerScript, unsigned int objectId, const char *propertyValue, bool expediteSending=false);
/// Get hardware & system information (works only for main loop)
void storeHardwareSnapshot();
void onFlashMsgReceived(const char *msg);
void sendMessageReceived();
void checkFacebookThread();
/// Get buffer memory usage
#ifndef USER_MODE
unsigned int getMemoryUsage() const;
#endif
// Get the hardware snapshot to send, or NULL if there is nothing to send
//const HardwareSnapshot* getHardwareSnapshot() const { return _HardwareSnapshot; }
CUbitubeUploadTask UploadTask;
CDownloadQueueTask DownloadQueueTask;
protected:
bool processLogIn(const char *startupArgs);
bool performPreLogInTasks(); // called in the main thread, while _LogInTask is allocated
bool performPostLogInTasks(); // called in the main thread
bool downloadAsset(TDBIndex index, const char *assetPartCode);
bool ensureValidZccPresent(unsigned int dbIndex, const char *zccFilename, const char *serverHashCode);
void makeURL(SimpleString<2048> *url, const char *action, const char *args, const char *baseURL=NULL) const; // default baseURL is WSBaseURL
void makeURL2(SimpleString<2048> *url, const char *actionAndParams, const char *baseURL) const;
bool unpackCardsFromBuffer(const char *bufPos);
void clearCards(); // calls compactAssetCache() that needs the download task to have been stopped
void callOnBrowserLoadingCallback(int browserId, bool status);
void openExternalWebBrowserUrlDecode(const char *uerl);
void closeBrowserWindow(CWebBrowser *browser);
void setNextVideoPublishingState(VideoPublishingEvent event);
void clearHardwareSnapshot();
bool uploadPhotoToFacebook();
bool autoConnectToFacebook();
bool closeSessionFromFacebook();
//void ensureBetaIdDownloaded();
private:
CardElemContainer _Cards;
json_object *_CardsToPublishJo;
CLogInTask *_LogInTask;
SimpleString<16> _IdAccount;
SimpleString<256> _Login; // check _IsLogged first
SimpleString<256> _Token; // check _IsLogged first
int _Credits;
bool _CreditsUnspent;
ConnectionMode _ConnectionMode;
RegisterMode _RegisterMode;
BckgndBufferedRequester _BufferedRequester;
HardwareSnapshot *_HardwareSnapshot;
//std::string _BetaGameId;
std::string _Filename_tmp, _tbFilename_tmp, _TempVideo_tmp;
u32 _DurationTime_tmp;
CWebBrowser *_LoginBrowser; // allocated on-demand
CWebBrowser *_WebBrowser; // allocated on-demand
CWebBrowser *_ShopBrowser; // allocated on-demand
CWebBrowser *_YouUpAdBrowser; // allocated on-demand
CWebBrowser *_TeaserBrowser;
VideoPublishingState _VideoPublishingState;
bool _UploadingWindowHasForm;
bool _ArticleIsDeleted;
bool _PublishThumbnailFilenames;
volatile bool _IsLogged; // no mutex needed: only log-in is in a background thread, then if getting _IsLogged false (i.e. from end of logOut() to end of performLogIn()), another request is forbidden. logOut() is synchronous.
volatile bool _HasBeenLogged; // this bool is set at TRUE when logout is called to force application to call Logout MSN page in case of another login
HANDLE _FlashMessageMutex;
SimpleString<2048> _FlashMessageToSend;
FacebookSession *_FacebookSession;
friend FacebookSession;
};
/**
* Background log-in task (NOT intended to be used in parallel with other HTTP requests)
*/
class CLogInTask : public CBackgroundTask
{};
/**
* Background log-in task (NOT intended to be used in parallel with other HTTP requests)
*/
class CLogInClassicTask : public CLogInTask
{
public:
void init(const char *login, const char *password)
{
Login = login;
Password = password;
}
std::string Login;
std::string Password;
private:
/// The code of the background task.
void run();
};
/**
* Background log-in task (NOT intended to be used in parallel with other HTTP requests)
*/
class CLogInSSOTask : public CLogInTask
{
public:
void init(const char *token, const char *source) { Token = (token ? token : std::string()); Source = source; }
std::string Token;
std::string Source;
private:
/// The code of the background task.
void run();
};
void samplePrintJson(json_object *jo);
/**
* Facebook session information
*/
class FacebookSession
{
public:
FacebookSession() : _NoExpire(false), isSuccess(false), isRunning (false), isChecked(false) {}
bool setFromJSONSession(char *joStr);
enum TaskList {
FB_NONE = 0,
FB_UPLOAD_PHOTOS,
FB_AUTO_CONNECTION,
FB_CLOSE_SESSION,
FB_LUA_AUTO_CONNECTION,
};
void run(TaskList task);
const char *sessionKey() const { return _SessionKey.c_str(); }
const char *secret() const { return _Secret.c_str(); }
const char *lastUrl() const { return _LastUrl.c_str(); }
const char *lastLink() const { return _LastLink.c_str(); }
const char *lastResponse() const { return _LastHttpResponse.c_str(); }
const char *lastError() const { return _LastError.c_str(); }
const char *uid() const { return _Uid.c_str(); }
TaskList getCurrentTask() const { return _CurrentTask; }
void setLastUrl(char* url) { _LastUrl = std::string(url); }
void setLastLink(char* link) { _LastLink = std::string(link); }
void setCurrentTask(TaskList task) { _CurrentTask = task; }
bool makeUrl (std::map<std::string, const char *> * moreArgs, CHttpClient * httpClient);
bool sendHttpRequest(CHttpClient * httpClient);
static unsigned __stdcall backgroundTask(void *params);
bool saveSettings ();
bool loadSettings ();
bool resetSettings ();
bool isRunning, isSuccess, isChecked;
private:
HANDLE _FacebookThread;
std::string _SessionKey;
std::string _Secret;
std::string _Uid;
std::string _LastUrl;
std::string _LastLink;
bool _NoExpire;
std::string _LastHttpResponse;
std::string _LastError;
// Task list ..
TaskList _CurrentTask;
};
#endif // ACCOUNT_H