/*
 * carot.cpp : ここうさぎウィザード carot
 *      アプリケーション メイン
 *          written by H.Tsujimura  15 Oct 2004
 *
 * $Log: /makeRSS/carot/carot.cpp $
 * 
 * 17    07/10/18 0:21 Tsujimura543
 * バージョン管理用コメント、IDを入れるようにする
 */

#include "carot.h"
#include "carotDlg.h"
#include "ProxyInfoDialog.h"

#ifndef	lint
static char	*rcs_id =
"$Header: /makeRSS/carot/carot.cpp 17    07/10/18 0:21 Tsujimura543 $";
#endif

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CCarotApp

BEGIN_MESSAGE_MAP(CCarotApp, CWinApp)
	//{{AFX_MSG_MAP(CCarotApp)
	ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
	//}}AFX_MSG
    ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CCarotApp クラスの構築

CCarotApp::CCarotApp()
{
    m_proxyType       = autoDetect; // ここではとりあえず、暫定的な初期化をし
    m_useProxy        = false;      // ておき、CCarotDlg::OnInitialUpdate()
	m_proxyServerName = _T("");     // にて実際の値を設定する
	m_proxyPortNumber = 0;
	m_proxyUserName   = _T("");
	m_proxyPassword   = _T("");

 // m_useProxy = isUsedProxy() == TRUE ? true : false;
 // setUseProxy( m_useProxy );
}

/////////////////////////////////////////////////////////////////////////////
// 唯一の CCarotApp オブジェクト

CCarotApp theApp;

/////////////////////////////////////////////////////////////////////////////
// CCarotApp クラスの初期化

BOOL CCarotApp::InitInstance()
{
	AfxEnableControlContainer();

#ifdef _AFXDLL
	Enable3dControls();			// 共有 DLL 内で MFC を使う場合
#else
	Enable3dControlsStatic();	// MFC と静的にリンクする場合
#endif

    m_numOfBlogPets = 0;
    m_blogPetList   = NULL;

    m_numOfBlogs    = 0;
    m_blogList      = NULL;

	CCarotDlg dlg;
	m_pMainWnd = &dlg;
	int nResponse = dlg.DoModal();
	if (nResponse == IDOK)
	{
	}
	else if (nResponse == IDCANCEL)
	{
	}

    if ( m_blogPetList )
        delete [] m_blogPetList;

    if ( m_blogList ) {
        for ( int i = 0; i < m_numOfBlogs; i++ ) {
            if ( m_blogList[i].numOfCategories > 0 ) {
                for ( int j = 0; j < m_blogList[i].numOfCategories; j++ )
                    free( m_blogList[i].catagory[j] );
                free( m_blogList[i].catagory );
                m_blogList[i].numOfCategories = 0;
                m_blogList[i].catagory        = NULL;
            }
        }
        delete [] m_blogList;

        base64( NULL, 0 );
        encodeURL( NULL );
        translateURL( NULL );
    }

	return FALSE;
}

#ifdef  _MSC_VER
#pragma warning ( disable: 4100 )
#endif
void CCarotApp::WinHelp(DWORD dwData, UINT nCmd) 
{
 // CWinApp::WinHelp(dwData, nCmd);
}
#ifdef  _MSC_VER
#pragma warning ( default: 4100 )
#endif


/* BlogPet 管理画面 に login する */
int
CCarotApp::LoginBlogPet(
        const char *userName,   // (I)   ユーザ名
        const char *password,   // (I)   パスワード
        char       *request,    // (I/O) httpリクエスト本体格納領域
        char       *response,   // (I/O) httpレスポンス本体格納領域
        char       *cookie,     // (I/O) クッキー
        char       *userID      // (O)   ユーザID
    )
{
    int     ret   = 0;
    int     retry = 5;
    char    url[MAX_URLLENGTH];
    size_t  sz = MAX_CONTENT_SIZE * 4;

    if ( !cookie   || !request     || !response ||
         !userName || !(*userName) ||
         !password || !(*password)    )
         return ( ret );

    do {
        memset( request, 0x00, MAX_CONTENT_SIZE );
        strcpy( url, "https://www.blogpet.net/login" );
        setTargetURL( url );
        setUpReceiveBuffer( response, MAX_CONTENT_SIZE * 4 );
        sprintf( request,
                 "username=%s&"
                 "password=%s&"
                 "remember=1&"
                 "jump_url=%%2Fhome",
                 userName, password );
        http_postEx( url, "application/x-www-form-urlencoded",
                     request, response, cookie );

        if ( *response ) {
            if ( strstr( response, "/logout" ) != NULL )
                ret = 1;    /* ログイン成功 */
            else
                ret = 0;    /* ログイン失敗 */
        }
        else
            ret = 0;        /* ログイン失敗 */

        if ( ret == 0 ) {
            retry--;
            if ( retry <= 0 )
                break;
            Sleep( 2000 );
        }
    } while ( ret == 0 );

    if ( ret == 1 ) {
        setUpReceiveBuffer( response, sz );
        http_getEx( "http://www.blogpet.net/home", response, cookie );
        if ( *response ) {
            char    *p;

            p = strstr( response, "/profile/friends/" );
            if ( !p )
                p = strstr( response, "/profile/groups/" );
            if ( !p )
                p = strstr( response,
                            "<script type=\"text/javascript\" src=\"/js/" );
            if ( p ) {
                char    *q;

                p = strstr( p, "s/" ) + 2;
                q = strchr( p, '"' );
                if ( q ) {
                    strncpy( userID, p, q - p );
                    userID[q - p] = NUL;
                }
            }
        }
    }

    return ( ret );
}

/* BlogPet 管理画面 から logout する */
void
CCarotApp::LogoutBlogPet(
        char *request,  // (I/O) httpリクエスト本体格納領域
        char *response, // (I/O) httpレスポンス本体格納領域
        char *cookie    // (I/O) クッキー
    )
{
    setUpReceiveBuffer( response, MAX_CONTENT_SIZE * 4 );
    sprintf( request, "jump_url=%s", encodeURL( "/home" ) );
    http_postEx( "http://www.blogpet.net/logout",
                 "application/x-www-form-urlencoded",
                 request, response, cookie );
}

/* BlogPet 管理画面 に login し、ID を取得 */
void CCarotApp::GetBlogPetID( const char *username,
                              const char *password,
                              char       *blogPetID )
{
    if ( !username  || !(*username) ||
         !password  || !(*password) ||
         !blogPetID                    )
        return;

    // BlogPet オフィシャルページにログインし、BlogPet の ID を取得
    char    userID[MAX_KEYLENGTH];
    char    *cookie   = new char[MAX_COOKIE_LEN];
    char    *request  = new char[MAX_CONTENT_SIZE];
    char    *response = new char[MAX_CONTENT_SIZE * 4];
    bool    status    = false;

    CWaitCursor cur;    // マウスカーソルを砂時計表示

    // -- login
    cookie[0] = NUL;
    userID[0] = NUL;
    LoginBlogPet( username, password, request, response, cookie, userID );

    if ( userID[0] ) {
        strcpy( blogPetID, userID );

        // logout
        LogoutBlogPet( request, response, cookie );

        MessageBox( NULL,
                    "BlogPet ID の取得に成功しました。    ",
                    "取得成功", MB_OK|MB_ICONINFORMATION );
        status = true;
    }

    if ( status == false )
        MessageBox( NULL,
                    "BlogPet ID の取得に失敗しました。    ",
                    "取得失敗", MB_OK|MB_ICONWARNING );

    delete [] response;
    delete [] request;
    delete [] cookie;
}

/* proxy情報ファイルの生成 (for BBAuth) */
#define FILE_CONFIG_PROXY   "proxy.txt" // proxyサーバ情報設定ファイル

void
CCarotApp::MakeProxyText( const char *dirname /* = NULL */ )
{
    if ( m_useProxy ) {
        char    filename[MAX_PATH];

        if ( dirname )
            strcpy( filename, dirname );
        else if ( __argv && __argv[0] && __argv[0][0] )
            strcpy( filename, __argv[0] );
        else
            strcpy( filename, "." );

        char    c = filename[strlen(filename) - 1];
        if ( (c != '\\') && (c != '/') )
            strcat( filename, "/" );
        strcat( filename, FILE_CONFIG_PROXY );

        FILE    *fp = fopen( filename, "w" );
        if ( fp ) {
            fprintf( fp, "%s\n", m_proxyServerName );
            fprintf( fp, "%d\n", m_proxyPortNumber );

            if ( m_proxyUserName.GetLength() > 0 ) {
                fprintf( fp, "%s\n", (const char *)m_proxyUserName );

                if ( m_proxyPassword.GetLength() > 0 )
                    fprintf( fp, "%s\n", (const char *)m_proxyPassword );
            }

            fclose( fp );
        }
    }
}

int confirmProxyInfo( int            *useProxy,
                      char           *proxyServer,
                      unsigned short *proxyPort,
                      char           *proxyUserName,
                      char           *proxyPassword )
{
    int         ret = FALSE;
    CCarotApp   *cp = (CCarotApp *)AfxGetApp();
    LCID        l = getLanguageCode();

    int r = MessageBox( NULL,
                        l == 0x0411
                            ? "proxyサーバ経由でインターネットを"
                              "利用していますか?"
                            : "Do you access the Internet via a "
                              "proxy server ?",
                        l == 0x0411
                            ? "インターネット利用形態確認"
                            : "Confirmation of proxy server",
                        MB_YESNO|MB_ICONQUESTION );

    if ( r == IDYES ) {
        CProxyInfoDialog    dlg;
        if ( proxyServer[0] ) {
            dlg.m_proxyServerName = proxyServer;
            dlg.m_proxyPortNumber = *proxyPort;
            if ( proxyUserName[0] ) {
                dlg.m_proxyUserName = proxyUserName;
                if ( proxyPassword[0] )
                    dlg.m_proxyPassword = proxyPassword;
            }
        }
        dlg.DoModal();

        *useProxy = TRUE;
        strcpy( proxyServer, dlg.m_proxyServerName );
        *proxyPort = (unsigned short)(dlg.m_proxyPortNumber);

        cp->m_proxyServerName = proxyServer;
        cp->m_proxyPortNumber = *proxyPort;

        if ( dlg.m_proxyUserName.GetLength() > 0 ) {
            cp->m_proxyUserName = dlg.m_proxyUserName;
            if ( dlg.m_proxyPassword.GetLength() > 0 )
                cp->m_proxyPassword = dlg.m_proxyPassword;
        }

        FILE    *fp;
        if ( ( fp = fopen( FILE_CONFIG_PROXY, "w" ) ) != NULL ) {
            fprintf( fp, "%s\n", proxyServer );
            fprintf( fp, "%d\n", *proxyPort );

            if ( dlg.m_proxyUserName.GetLength() > 0 ) {
                if ( proxyUserName )
                    strcpy( proxyUserName, dlg.m_proxyUserName );
                fprintf( fp, "%s\n", (const char *)dlg.m_proxyUserName );

                if ( dlg.m_proxyPassword.GetLength() > 0 ) {
                    if ( proxyPassword )
                        strcpy( proxyPassword, dlg.m_proxyPassword );
                    fprintf( fp, "%s\n", (const char *)dlg.m_proxyPassword );
                }
            }
            fclose( fp );
        }

        ret = TRUE;
    }
    else {
        *useProxy = FALSE;
        ret = TRUE;
    }

    cp->m_proxyType = CCarotApp::manualSetting;
    cp->m_useProxy  = *useProxy == TRUE ? true : false;

    return ( ret );
}

bool
checkProxyInfo()
{
    bool    ret = isNecessaryToCheckProxyInfo() ? true : false;

    if ( ret )
        initProxyInfo();

    return ( ret );
}

void
initProxyInfo()
{
    unlink( FILE_CONFIG_PROXY );
}
