Upstream tarball 9536
[amule.git] / src / amule-remote-gui.cpp
blob999b74103b58d0cc099a1c43718585042661d509
1 //
2 // This file is part of the aMule Project.
3 //
4 // Copyright (c) 2005-2008 aMule Team ( admin@amule.org / http://www.amule.org )
5 //
6 // Any parts of this program derived from the xMule, lMule or eMule project,
7 // or contributed by third-party developers are copyrighted by their
8 // respective authors.
9 //
10 // This program is free software; you can redistribute it and/or modify
11 // it under the terms of the GNU General Public License as published by
12 // the Free Software Foundation; either version 2 of the License, or
13 // (at your option) any later version.
15 // This program is distributed in the hope that it will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 // GNU General Public License for more details.
19 //
20 // You should have received a copy of the GNU General Public License
21 // along with this program; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 #define AMULE_REMOTE_GUI_CPP
29 #include <memory> // Needed for auto_ptr
30 using std::auto_ptr;
33 #include <wx/ipc.h>
34 #include <wx/cmdline.h> // Needed for wxCmdLineParser
35 #include <wx/config.h> // Do_not_auto_remove (win32)
36 #include <wx/fileconf.h> // Needed for wxFileConfig
39 #include <common/Format.h>
40 #include <common/StringFunctions.h>
41 #include <common/MD5Sum.h>
44 #include <include/common/EventIDs.h>
47 #include "amule.h" // Interface declarations.
48 #include "amuleDlg.h" // Needed for CamuleDlg
49 #include "ClientCredits.h"
50 #include "ClientListCtrl.h"
51 #include "DataToText.h" // Needed for GetSoftName()
52 #include "DownloadListCtrl.h" // Needed for CDownloadListCtrl
53 #include "GuiEvents.h"
54 #ifdef ENABLE_IP2COUNTRY
55 #include "IP2Country.h" // Needed for IP2Country
56 #endif
57 #include "InternalEvents.h" // Needed for wxEVT_CORE_FINISHED_HTTP_DOWNLOAD
58 #include "Logger.h"
59 #include "muuli_wdr.h" // Needed for IDs
60 #include "PartFile.h" // Needed for CPartFile
61 #include "SearchDlg.h" // Needed for CSearchDlg
62 #include "Server.h" // Needed for GetListName
63 #include "ServerWnd.h" // Needed for CServerWnd
64 #include "SharedFilesCtrl.h" // Needed for CSharedFilesCtrl
65 #include "SharedFilesWnd.h" // Needed for CSharedFilesWnd
66 #include "TransferWnd.h" // Needed for CTransferWnd
67 #include "updownclient.h"
68 #include "ServerListCtrl.h" // Needed for CServerListCtrl
69 #include "MagnetURI.h" // Needed for CMagnetURI
72 CEConnectDlg::CEConnectDlg()
74 wxDialog(theApp->amuledlg, -1, _("Connect to remote amule"), wxDefaultPosition)
76 CoreConnect(this, true);
78 wxString pref_host, pref_port;
79 wxConfig::Get()->Read(wxT("/EC/Host"), &pref_host, wxT("localhost"));
80 wxConfig::Get()->Read(wxT("/EC/Port"), &pref_port, wxT("4712"));
81 wxConfig::Get()->Read(wxT("/EC/Password"), &pwd_hash);
83 CastChild(ID_REMOTE_HOST, wxTextCtrl)->SetValue(pref_host);
84 CastChild(ID_REMOTE_PORT, wxTextCtrl)->SetValue(pref_port);
85 CastChild(ID_EC_PASSWD, wxTextCtrl)->SetValue(pwd_hash);
87 CentreOnParent();
91 wxString CEConnectDlg::PassHash()
93 return pwd_hash;
97 BEGIN_EVENT_TABLE(CEConnectDlg, wxDialog)
98 EVT_BUTTON(wxID_OK, CEConnectDlg::OnOK)
99 END_EVENT_TABLE()
102 void CEConnectDlg::OnOK(wxCommandEvent& evt)
104 wxString s_port = CastChild(ID_REMOTE_PORT, wxTextCtrl)->GetValue();
105 port = StrToLong(s_port);
107 host = CastChild(ID_REMOTE_HOST, wxTextCtrl)->GetValue();
108 passwd = CastChild(ID_EC_PASSWD, wxTextCtrl)->GetValue();
110 if (passwd != pwd_hash) {
111 pwd_hash = MD5Sum(passwd).GetHash();
113 m_save_user_pass = CastChild(ID_EC_SAVE, wxCheckBox)->IsChecked();
114 evt.Skip();
118 DEFINE_LOCAL_EVENT_TYPE(wxEVT_EC_INIT_DONE)
121 BEGIN_EVENT_TABLE(CamuleRemoteGuiApp, wxApp)
122 // Core timer
123 EVT_TIMER(ID_CORE_TIMER_EVENT, CamuleRemoteGuiApp::OnPollTimer)
125 EVT_CUSTOM(wxEVT_EC_CONNECTION, -1, CamuleRemoteGuiApp::OnECConnection)
126 EVT_CUSTOM(wxEVT_EC_INIT_DONE, -1, CamuleRemoteGuiApp::OnECInitDone)
128 EVT_MULE_NOTIFY(CamuleRemoteGuiApp::OnNotifyEvent)
130 #ifdef ENABLE_IP2COUNTRY
131 // HTTPDownload finished
132 EVT_MULE_INTERNAL(wxEVT_CORE_FINISHED_HTTP_DOWNLOAD, -1, CamuleRemoteGuiApp::OnFinishedHTTPDownload)
133 #endif
134 END_EVENT_TABLE()
137 IMPLEMENT_APP(CamuleRemoteGuiApp)
140 int CamuleRemoteGuiApp::OnExit()
142 StopTickTimer();
144 return wxApp::OnExit();
148 void CamuleRemoteGuiApp::OnPollTimer(wxTimerEvent&)
150 static int request_step = 0;
152 if (m_connect->RequestFifoFull()) {
153 return;
156 switch (request_step) {
157 case 0:
158 serverconnect->ReQuery();
159 serverlist->UpdateUserFileStatus(serverconnect->GetCurrentServer());
160 request_step++;
161 break;
162 case 1: {
163 CECPacket stats_req(EC_OP_STAT_REQ);
164 m_connect->SendRequest(&m_stats_updater, &stats_req);
165 amuledlg->ShowTransferRate();
166 request_step++;
167 break;
169 case 2:
170 if (amuledlg->m_sharedfileswnd->IsShown()) {
171 sharedfiles->DoRequery(EC_OP_GET_SHARED_FILES, EC_TAG_KNOWNFILE);
172 } else if (amuledlg->m_serverwnd->IsShown()) {
173 //serverlist->FullReload(EC_OP_GET_SERVER_LIST);
174 } else if (amuledlg->m_transferwnd->IsShown()) {
175 static bool firstcall = true;
176 downloadqueue->DoRequery(
177 theApp->m_FileDetailDialogActive || firstcall ?
178 EC_OP_GET_DLOAD_QUEUE_DETAIL : EC_OP_GET_DLOAD_QUEUE,
179 EC_TAG_PARTFILE);
180 firstcall = false;
181 switch(amuledlg->m_transferwnd->clientlistctrl->GetListView()) {
182 case vtUploading:
183 uploadqueue->ReQueryUp();
184 break;
185 case vtQueued:
186 uploadqueue->ReQueryWait();
187 break;
188 case vtClients:
189 break;
190 case vtNone:
191 break;
193 amuledlg->m_transferwnd->ShowQueueCount(theStats::GetWaitingUserCount());
194 } else if (amuledlg->m_searchwnd->IsShown()) {
195 if (searchlist->m_curr_search != -1) {
196 searchlist->DoRequery(EC_OP_SEARCH_RESULTS, EC_TAG_SEARCHFILE);
199 // Back to the roots
200 request_step = 0;
201 break;
202 default:
203 AddLogLineCS(wxT("WTF?")); // should not happen. :-)
204 request_step = 0;
209 void CamuleRemoteGuiApp::OnFinishedHTTPDownload(CMuleInternalEvent& event)
211 #ifdef ENABLE_IP2COUNTRY
212 if (event.GetInt() == HTTP_GeoIP) {
213 amuledlg->IP2CountryDownloadFinished(event.GetExtraLong());
214 // If we updated, the dialog is already up. Redraw it to show the flags.
215 amuledlg->Refresh();
217 #endif
221 void CamuleRemoteGuiApp::ShutDown(wxCloseEvent &WXUNUSED(evt))
223 // Stop the Core Timer
224 delete poll_timer;
225 poll_timer = NULL;
227 // Destroy the EC socket
228 m_connect->Destroy();
229 m_connect = NULL;
232 if (amuledlg) {
233 amuledlg->DlgShutDown();
234 amuledlg->Destroy();
235 amuledlg = NULL;
240 bool CamuleRemoteGuiApp::OnInit()
242 StartTickTimer();
243 amuledlg = NULL;
244 if ( !wxApp::OnInit() ) {
245 return false;
248 // Get theApp
249 theApp = &wxGetApp();
251 // Handle uncaught exceptions
252 InstallMuleExceptionHandler();
254 // Create the polling timer
255 poll_timer = new wxTimer(this,ID_CORE_TIMER_EVENT);
256 if (!poll_timer) {
257 AddLogLineCS(_("Fatal Error: Failed to create Poll Timer"));
258 OnExit();
261 m_connect = new CRemoteConnect(this);
262 SetAppName(wxT("aMule"));
264 // Load Preferences
265 // This creates the CFG file we shall use
266 ConfigDir = GetConfigDir();
267 if (!wxDirExists(ConfigDir)) {
268 wxMkdir(ConfigDir);
271 wxConfig::Set(new wxFileConfig(wxEmptyString, wxEmptyString,
272 ConfigDir + wxT("remote.conf")));
274 glob_prefs = new CPreferencesRem(m_connect);
276 InitCustomLanguages();
277 InitLocale(m_locale, StrLang2wx(thePrefs::GetLanguageID()));
279 bool result = ShowConnectionDialog();
281 AddLogLineNS(_("Going to event loop..."));
283 return result;
287 bool CamuleRemoteGuiApp::CryptoAvailable() const
289 return clientcredits && clientcredits->CryptoAvailable();
293 bool CamuleRemoteGuiApp::ShowConnectionDialog() {
295 dialog = new CEConnectDlg;
297 if (dialog->ShowModal() != wxID_OK) {
298 dialog->Destroy();
300 return false;
302 AddLogLineNS(_("Connecting..."));
303 if (!m_connect->ConnectToCore(dialog->Host(), dialog->Port(),
304 dialog->Login(), dialog->PassHash(),
305 wxT("amule-remote"), wxT("0x0001"))) {
306 wxMessageBox(_("Connection failed "),_("ERROR"),wxOK);
308 return false;
311 return true;
315 void CamuleRemoteGuiApp::OnECConnection(wxEvent& event) {
316 wxECSocketEvent& evt = *((wxECSocketEvent*)&event);
317 AddLogLineNS(_("Remote GUI EC event handler"));
318 wxString reply = evt.GetServerReply();
319 AddLogLineM(true, reply);
320 if (evt.GetResult() == true) {
321 // Connected - go to next init step
322 glob_prefs->LoadRemote();
323 } else {
324 AddLogLineNS(_("Going down"));
325 wxMessageBox(
326 (CFormat(_("Connection Failed. Unable to connect to %s:%d\n")) % dialog->Host() % dialog->Port()) + reply,
327 _("ERROR"), wxOK);
328 ExitMainLoop();
333 void CamuleRemoteGuiApp::OnECInitDone(wxEvent& )
335 Startup();
339 void CamuleRemoteGuiApp::OnNotifyEvent(CMuleGUIEvent& evt)
341 evt.Notify();
345 void CamuleRemoteGuiApp::Startup() {
347 if (dialog->SaveUserPass()) {
348 wxConfig::Get()->Write(wxT("/EC/Host"), dialog->Host());
349 wxConfig::Get()->Write(wxT("/EC/Port"), dialog->Port());
350 wxConfig::Get()->Write(wxT("/EC/Password"), dialog->PassHash());
352 dialog->Destroy();
354 m_ConnState = 0;
355 m_clientID = 0;
357 serverconnect = new CServerConnectRem(m_connect);
358 m_statistics = new CStatistics(*m_connect);
360 clientlist = new CClientListRem(m_connect);
361 searchlist = new CSearchListRem(m_connect);
362 serverlist = new CServerListRem(m_connect);
364 sharedfiles = new CSharedFilesRem(m_connect);
365 knownfiles = new CKnownFilesRem(sharedfiles);
367 clientcredits = new CClientCreditsRem();
369 // bugfix - do this before creating the uploadqueue
370 downloadqueue = new CDownQueueRem(m_connect);
371 uploadqueue = new CUpQueueRem(m_connect);
372 ipfilter = new CIPFilterRem(m_connect);
374 // Parse cmdline arguments.
375 wxCmdLineParser cmdline(wxApp::argc, wxApp::argv);
376 cmdline.AddSwitch(wxT("v"), wxT("version"),
377 wxT("Displays the current version number."));
378 cmdline.AddSwitch(wxT("h"), wxT("help"),
379 wxT("Displays this information."));
380 cmdline.AddOption(wxT("geometry"), wxEmptyString, wxT("Sets the geometry of the app.\n\t\t\t<str> uses the same format as standard X11 apps:\n\t\t\t[=][<width>{xX}<height>][{+-}<xoffset>{+-}<yoffset>]"));
381 cmdline.Parse();
383 bool geometry_enabled = false;
384 wxString geom_string;
385 if (cmdline.Found(wxT("geometry"), &geom_string)) {
386 geometry_enabled = true;
389 // Create main dialog
390 InitGui(0, geom_string);
392 // Forward wxLog events to CLogger
393 wxLog::SetActiveTarget(new CLoggerTarget);
394 serverlist->FullReload(EC_OP_GET_SERVER_LIST);
395 sharedfiles->DoRequery(EC_OP_GET_SHARED_FILES, EC_TAG_KNOWNFILE);
397 // Start the Poll Timer
398 poll_timer->Start(1000);
399 amuledlg->StartGuiTimer();
401 // Now activate GeoIP, so that the download dialog doesn't get destroyed immediately
402 #ifdef ENABLE_IP2COUNTRY
403 if (thePrefs::IsGeoIPEnabled()) {
404 amuledlg->m_IP2Country->Enable();
406 #endif
410 void CamuleRemoteGuiApp::ShowAlert(wxString msg, wxString title, int flags)
412 CamuleGuiBase::ShowAlert(msg, title, flags);
416 void CamuleRemoteGuiApp::AddRemoteLogLine(const wxString& line)
418 amuledlg->AddLogLine(line);
421 int CamuleRemoteGuiApp::InitGui(bool geometry_enabled, wxString &geom_string)
423 CamuleGuiBase::InitGui(geometry_enabled, geom_string);
424 SetTopWindow(amuledlg);
425 AddLogLineN(_("Ready")); // The first log line after the window is up triggers output of all the ones before
426 return 0;
430 bool CamuleRemoteGuiApp::CopyTextToClipboard(wxString strText)
432 return CamuleGuiBase::CopyTextToClipboard(strText);
436 uint32 CamuleRemoteGuiApp::GetPublicIP()
438 return 0;
442 wxString CamuleRemoteGuiApp::GetLog(bool)
444 return wxEmptyString;
448 wxString CamuleRemoteGuiApp::GetServerLog(bool)
450 return wxEmptyString;
454 wxString CamuleRemoteGuiApp::CreateMagnetLink(const CAbstractFile* f)
456 // TODO: Remove duplicate code (also in amule.cpp) ...
457 CMagnetURI uri;
459 uri.AddField(wxT("dn"), f->GetFileName().Cleanup(false).GetPrintable());
460 uri.AddField(wxT("xt"), wxString(wxT("urn:ed2k:")) + f->GetFileHash().Encode().Lower());
461 uri.AddField(wxT("xt"), wxString(wxT("urn:ed2khash:")) + f->GetFileHash().Encode().Lower());
462 uri.AddField(wxT("xl"), wxString::Format(wxT("%") wxLongLongFmtSpec wxT("u"), f->GetFileSize()));
464 return uri.GetLink();
467 wxString CamuleRemoteGuiApp::CreateED2kLink(const CAbstractFile* f, bool add_source, bool use_hostname, bool addcryptoptions)
469 // TODO: Avoid duplicate code (also in amule.cpp) ...
470 wxASSERT(!(!add_source && (use_hostname || addcryptoptions)));
471 // Construct URL like this: ed2k://|file|<filename>|<size>|<hash>|/
472 wxString strURL = CFormat(wxT("ed2k://|file|%s|%i|%s|/"))
473 % f->GetFileName().Cleanup(false)
474 % f->GetFileSize() % f->GetFileHash().Encode();
476 if (add_source && IsConnected() && !IsFirewalled()) {
477 // Create the first part of the URL
478 strURL << wxT("|sources,");
480 if (use_hostname) {
481 strURL << thePrefs::GetYourHostname();
482 } else {
483 uint32 clientID = GetID();
484 strURL << (uint8) clientID << wxT(".") <<
485 (uint8)(clientID >> 8) << wxT(".") <<
486 (uint8)(clientID >> 16) << wxT(".") <<
487 (uint8)(clientID >> 24);
490 strURL << wxT(":") <<
491 thePrefs::GetPort();
493 if (addcryptoptions) {
494 const uint8 uSupportsCryptLayer = thePrefs::IsClientCryptLayerSupported() ? 1 : 0;
495 const uint8 uRequestsCryptLayer = thePrefs::IsClientCryptLayerRequested() ? 1 : 0;
496 const uint8 uRequiresCryptLayer = thePrefs::IsClientCryptLayerRequired() ? 1 : 0;
497 const uint8 byCryptOptions = (uRequiresCryptLayer << 2) | (uRequestsCryptLayer << 1) | (uSupportsCryptLayer << 0) | (uSupportsCryptLayer ? 0x80 : 0x00);
499 strURL << wxT(":") << byCryptOptions;
501 if (byCryptOptions & 0x80) {
502 strURL << wxT(":") << thePrefs::GetUserHash().Encode();
506 strURL << wxT("|/");
507 } else if (add_source) {
508 AddLogLineM(true, _("WARNING: You can't add yourself as a source for an eD2k link while having a lowid."));
511 // Result is "ed2k://|file|<filename>|<size>|<hash>|/|sources,[(<ip>|<hostname>):<port>[:cryptoptions[:hash]]]|/"
512 return strURL;
516 wxString CamuleRemoteGuiApp::CreateED2kAICHLink(const CKnownFile* f)
518 // TODO: Avoid duplicate code (also in amule.cpp) ...
519 // Create the first part of the URL
520 wxString strURL = CreateED2kLink(f);
521 // Append the AICH info
522 if (f->HasProperAICHHashSet()) {
523 strURL.RemoveLast(); // remove trailing '/'
524 strURL << wxT("h=") << f->GetAICHMasterHash() << wxT("|/");
527 // Result is "ed2k://|file|<filename>|<size>|<hash>|h=<AICH master hash>|/"
528 return strURL;
532 bool CamuleRemoteGuiApp::AddServer(CServer *, bool)
534 // #warning TODO: Add remote command
535 return true;
539 bool CamuleRemoteGuiApp::IsFirewalled() const
541 if (IsConnectedED2K() && !serverconnect->IsLowID()) {
542 return false;
545 return IsFirewalledKad();
549 bool CamuleRemoteGuiApp::IsConnectedED2K() const {
550 return serverconnect && serverconnect->IsConnected();
554 void CamuleRemoteGuiApp::StartKad() {
555 m_connect->StartKad();
559 void CamuleRemoteGuiApp::StopKad() {
560 m_connect->StopKad();
564 void CamuleRemoteGuiApp::BootstrapKad(uint32 ip, uint16 port)
566 CECPacket req(EC_OP_KAD_BOOTSTRAP_FROM_IP);
567 req.AddTag(CECTag(EC_TAG_BOOTSTRAP_IP, ip));
568 req.AddTag(CECTag(EC_TAG_BOOTSTRAP_PORT, port));
570 m_connect->SendPacket(&req);
574 void CamuleRemoteGuiApp::UpdateNotesDat(const wxString& url)
576 CECPacket req(EC_OP_KAD_UPDATE_FROM_URL);
577 req.AddTag(CECTag(EC_TAG_KADEMLIA_UPDATE_URL, url));
579 m_connect->SendPacket(&req);
583 void CamuleRemoteGuiApp::DisconnectED2K() {
584 if (IsConnectedED2K()) {
585 m_connect->DisconnectED2K();
590 uint32 CamuleRemoteGuiApp::GetED2KID() const
592 return serverconnect ? serverconnect->GetClientID() : 0;
596 uint32 CamuleRemoteGuiApp::GetID() const
598 return m_clientID;
602 void CamuleRemoteGuiApp::ShowUserCount() {
603 wxString buffer =
604 CFormat(_("Users: E: %s K: %s | Files E: %s K: %s")) % CastItoIShort(theStats::GetED2KUsers()) %
605 CastItoIShort(theStats::GetKadUsers()) % CastItoIShort(theStats::GetED2KFiles()) % CastItoIShort(theStats::GetKadFiles());
607 Notify_ShowUserCount(buffer);
612 * Preferences: holds both local and remote settings.
614 * First, everything is loaded from local config file. Later, settings
615 * that are relevant on remote side only are loaded thru EC
617 CPreferencesRem::CPreferencesRem(CRemoteConnect *conn)
619 m_conn = conn;
621 CPreferences::BuildItemList(theApp->ConfigDir);
622 CPreferences::LoadAllItems(wxConfigBase::Get());
625 // Settings queried from remote side
627 m_exchange_send_selected_prefs =
628 EC_PREFS_GENERAL |
629 EC_PREFS_CONNECTIONS |
630 EC_PREFS_MESSAGEFILTER |
631 EC_PREFS_ONLINESIG |
632 EC_PREFS_SERVERS |
633 EC_PREFS_FILES |
634 EC_PREFS_SRCDROP |
635 EC_PREFS_SECURITY |
636 EC_PREFS_CORETWEAKS |
637 EC_PREFS_REMOTECONTROLS |
638 EC_PREFS_KADEMLIA;
639 m_exchange_recv_selected_prefs =
640 m_exchange_send_selected_prefs |
641 EC_PREFS_CATEGORIES;
645 void CPreferencesRem::HandlePacket(const CECPacket *packet)
647 ((CEC_Prefs_Packet *)packet)->Apply();
649 if ( packet->GetTagByName(EC_TAG_PREFS_CATEGORIES) != 0 ) {
650 for (size_t i = 0; i < packet->GetTagByName(EC_TAG_PREFS_CATEGORIES)->GetTagCount(); i++) {
651 const CECTag *cat_tag = packet->GetTagByName(EC_TAG_PREFS_CATEGORIES)->GetTagByIndex(i);
652 Category_Struct *cat = new Category_Struct;
653 cat->title = cat_tag->GetTagByName(EC_TAG_CATEGORY_TITLE)->GetStringData();
654 cat->path = CPath(cat_tag->GetTagByName(EC_TAG_CATEGORY_PATH)->GetStringData());
655 cat->comment = cat_tag->GetTagByName(EC_TAG_CATEGORY_COMMENT)->GetStringData();
656 cat->color = cat_tag->GetTagByName(EC_TAG_CATEGORY_COLOR)->GetInt();
657 cat->prio = cat_tag->GetTagByName(EC_TAG_CATEGORY_PRIO)->GetInt();
658 theApp->glob_prefs->AddCat(cat);
660 } else {
661 Category_Struct *cat = new Category_Struct;
662 cat->title = _("All");
663 cat->color = 0;
664 cat->prio = PR_NORMAL;
665 theApp->glob_prefs->AddCat(cat);
667 wxECInitDoneEvent event;
668 theApp->AddPendingEvent(event);
673 bool CPreferencesRem::LoadRemote()
676 // override local settings with remote
677 CECPacket req(EC_OP_GET_PREFERENCES, EC_DETAIL_UPDATE);
679 // bring categories too
680 req.AddTag(CECTag(EC_TAG_SELECT_PREFS, m_exchange_recv_selected_prefs));
682 m_conn->SendRequest(this, &req);
684 return true;
688 void CPreferencesRem::SendToRemote()
690 CEC_Prefs_Packet pref_packet(m_exchange_send_selected_prefs, EC_DETAIL_UPDATE, EC_DETAIL_FULL);
691 m_conn->SendPacket(&pref_packet);
695 Category_Struct *CPreferencesRem::CreateCategory(
696 const wxString& name,
697 const CPath& path,
698 const wxString& comment,
699 uint32 color,
700 uint8 prio)
702 CECPacket req(EC_OP_CREATE_CATEGORY);
703 CEC_Category_Tag tag(0xffffffff, name, path.GetRaw(), comment, color, prio);
704 req.AddTag(tag);
705 m_conn->SendPacket(&req);
707 Category_Struct *category = new Category_Struct();
708 category->path = path;
709 category->title = name;
710 category->comment = comment;
711 category->color = color;
712 category->prio = prio;
714 AddCat(category);
716 return category;
720 void CPreferencesRem::UpdateCategory(
721 uint8 cat,
722 const wxString& name,
723 const CPath& path,
724 const wxString& comment,
725 uint32 color,
726 uint8 prio)
728 CECPacket req(EC_OP_UPDATE_CATEGORY);
729 CEC_Category_Tag tag(cat, name, path.GetRaw(), comment, color, prio);
730 req.AddTag(tag);
731 m_conn->SendPacket(&req);
733 Category_Struct *category = m_CatList[cat];
734 category->path = path;
735 category->title = name;
736 category->comment = comment;
737 category->color = color;
738 category->prio = prio;
742 void CPreferencesRem::RemoveCat(uint8 cat)
744 CECPacket req(EC_OP_DELETE_CATEGORY);
745 CEC_Category_Tag tag(cat, EC_DETAIL_CMD);
746 req.AddTag(tag);
747 m_conn->SendPacket(&req);
748 CPreferences::RemoveCat(cat);
753 // Container implementation
755 CServerConnectRem::CServerConnectRem(CRemoteConnect *conn)
757 m_CurrServer = 0;
758 m_Conn = conn;
762 void CServerConnectRem::ConnectToAnyServer()
764 CECPacket req(EC_OP_SERVER_CONNECT);
765 m_Conn->SendPacket(&req);
769 void CServerConnectRem::StopConnectionTry()
771 // lfroen: isn't Disconnect the same ?
775 void CServerConnectRem::Disconnect()
777 CECPacket req(EC_OP_SERVER_DISCONNECT);
778 m_Conn->SendPacket(&req);
782 void CServerConnectRem::ConnectToServer(CServer *server)
784 m_Conn->ConnectED2K(server->GetIP(), server->GetPort());
788 bool CServerConnectRem::ReQuery()
790 CECPacket stat_req(EC_OP_GET_CONNSTATE);
791 m_Conn->SendRequest(this, &stat_req);
793 return true;
797 void CServerConnectRem::HandlePacket(const CECPacket *packet)
799 CEC_ConnState_Tag *tag =
800 (CEC_ConnState_Tag *)packet->GetTagByName(EC_TAG_CONNSTATE);
801 if (!tag) {
802 return;
805 theApp->m_ConnState = 0;
806 CServer *server;
807 m_ID = tag->GetEd2kId();
808 theApp->m_clientID = tag->GetClientId();
810 if (tag->IsConnectedED2K()) {
811 CECTag *srvtag = tag->GetTagByName(EC_TAG_SERVER);
812 if (!srvtag) {
813 return;
815 server = theApp->serverlist->GetByID(srvtag->GetIPv4Data().IP());
816 if (m_CurrServer && (server != m_CurrServer)) {
817 theApp->amuledlg->m_serverwnd->serverlistctrl->
818 HighlightServer(m_CurrServer, false);
820 theApp->amuledlg->m_serverwnd->serverlistctrl->
821 HighlightServer(server, true);
822 m_CurrServer = server;
823 theApp->m_ConnState |= CONNECTED_ED2K;
824 } else {
825 if ( m_CurrServer ) {
826 theApp->amuledlg->m_serverwnd->serverlistctrl->
827 HighlightServer(m_CurrServer, false);
828 m_CurrServer = 0;
832 if (tag->IsConnectedKademlia()) {
833 if (tag->IsKadFirewalled()) {
834 theApp->m_ConnState |= CONNECTED_KAD_FIREWALLED;
835 } else {
836 theApp->m_ConnState |= CONNECTED_KAD_OK;
838 } else {
839 if (tag->IsKadRunning()) {
840 theApp->m_ConnState |= CONNECTED_KAD_NOT;
844 theApp->amuledlg->ShowConnectionState();
849 * Server list: host list of ed2k servers.
851 CServerListRem::CServerListRem(CRemoteConnect *conn)
853 CRemoteContainer<CServer, uint32, CEC_Server_Tag>(conn)
858 void CServerListRem::HandlePacket(const CECPacket *packet)
860 CRemoteContainer<CServer, uint32, CEC_Server_Tag>::HandlePacket(packet);
861 ReloadControl();
865 void CServerListRem::UpdateServerMetFromURL(wxString url)
867 CECPacket req(EC_OP_SERVER_UPDATE_FROM_URL);
868 req.AddTag(CECTag(EC_TAG_SERVERS_UPDATE_URL, url));
870 m_conn->SendPacket(&req);
874 void CServerListRem::SaveServerMet()
876 // lfroen: stub, nothing to do
880 void CServerListRem::FilterServers()
882 // FIXME: add code
883 //wxFAIL;
887 void CServerListRem::RemoveServer(CServer* server)
889 m_conn->RemoveServer(server->GetIP(),server->GetPort());
893 void CServerListRem::UpdateUserFileStatus(CServer *server)
895 if (server) {
896 m_TotalUser = server->GetUsers();
897 m_TotalFile = server->GetFiles();
899 wxString buffer =
900 CFormat(_("Total Users: %s | Total Files: %s")) % CastItoIShort(m_TotalUser) % CastItoIShort(m_TotalFile);
902 Notify_ShowUserCount(buffer);
907 CServer *CServerListRem::GetServerByAddress(const wxString& WXUNUSED(address), uint16 WXUNUSED(port)) const
909 // It's ok to return 0 for context where this code is used in remote gui
910 return 0;
913 CServer *CServerListRem::GetServerByIPTCP(uint32 WXUNUSED(nIP), uint16 WXUNUSED(nPort)) const
915 // It's ok to return 0 for context where this code is used in remote gui
916 return 0;
919 CServer *CServerListRem::CreateItem(CEC_Server_Tag *tag)
921 return new CServer(tag);
925 void CServerListRem::DeleteItem(CServer *in_srv)
927 auto_ptr<CServer> srv(in_srv);
928 theApp->amuledlg->m_serverwnd->serverlistctrl->RemoveServer(srv.get());
932 uint32 CServerListRem::GetItemID(CServer *server)
934 return server->GetIP();
938 void CServerListRem::ProcessItemUpdate(CEC_Server_Tag *, CServer *)
940 // server list is always realoaded from scratch
941 wxFAIL;
945 void CServerListRem::ReloadControl()
947 for(uint32 i = 0;i < GetCount(); i++) {
948 CServer *srv = GetByIndex(i);
949 theApp->amuledlg->m_serverwnd->serverlistctrl->RefreshServer(srv);
954 CIPFilterRem::CIPFilterRem(CRemoteConnect* conn)
956 m_conn = conn;
960 void CIPFilterRem::Reload()
962 CECPacket req(EC_OP_IPFILTER_RELOAD);
963 m_conn->SendPacket(&req);
967 void CIPFilterRem::Update(wxString WXUNUSED(url))
969 // FIXME: add command
970 //wxFAIL;
975 * Shared files list
977 CSharedFilesRem::CSharedFilesRem(CRemoteConnect *conn) : CRemoteContainer<CKnownFile, CMD4Hash, CEC_SharedFile_Tag>(conn, true)
979 m_rename_file = NULL;
983 void CSharedFilesRem::Reload(bool, bool)
985 CECPacket req(EC_OP_SHAREDFILES_RELOAD);
987 m_conn->SendPacket(&req);
991 void CSharedFilesRem::AddFilesFromDirectory(const CPath& path)
993 CECPacket req(EC_OP_SHAREDFILES_ADD_DIRECTORY);
995 req.AddTag(CECTag(EC_TAG_PREFS_DIRECTORIES, path.GetRaw()));
997 m_conn->SendPacket(&req);
1001 bool CSharedFilesRem::RenameFile(CKnownFile* file, const CPath& newName)
1003 // We use the printable name, as the filename originated from user input,
1004 // and the filesystem name might not be valid on the remote host.
1005 const wxString strNewName = newName.GetPrintable();
1007 CECPacket request(EC_OP_RENAME_FILE);
1008 request.AddTag(CECTag(EC_TAG_KNOWNFILE, file->GetFileHash()));
1009 request.AddTag(CECTag(EC_TAG_PARTFILE_NAME, strNewName));
1011 m_conn->SendRequest(this, &request);
1012 m_rename_file = file;
1013 m_new_name = strNewName;
1015 return true;
1019 void CSharedFilesRem::HandlePacket(const CECPacket *packet)
1021 if (m_rename_file && (packet->GetOpCode() == EC_OP_NOOP)) {
1022 m_rename_file->SetFileName(CPath(m_new_name));
1023 m_rename_file = NULL;
1024 } else if (packet->GetOpCode() != EC_OP_FAILED) {
1025 CRemoteContainer<CKnownFile, CMD4Hash, CEC_SharedFile_Tag>::HandlePacket(packet);
1030 CKnownFile *CSharedFilesRem::CreateItem(CEC_SharedFile_Tag *tag)
1032 CKnownFile *file = new CKnownFile(tag);
1034 m_enc_map[file->GetFileHash()] = RLE_Data(file->GetPartCount(), true);
1036 ProcessItemUpdate(tag, file);
1038 theApp->amuledlg->m_sharedfileswnd->sharedfilesctrl->ShowFile(file);
1040 return file;
1044 void CSharedFilesRem::DeleteItem(CKnownFile *in_file)
1046 auto_ptr<CKnownFile> file(in_file);
1048 m_enc_map.erase(file->GetFileHash());
1050 theApp->amuledlg->m_sharedfileswnd->sharedfilesctrl->RemoveFile(file.get());
1054 CMD4Hash CSharedFilesRem::GetItemID(CKnownFile *file)
1056 return file->GetFileHash();
1060 void CSharedFilesRem::ProcessItemUpdate(CEC_SharedFile_Tag *tag, CKnownFile *file)
1062 CECTag *parttag = tag->GetTagByName(EC_TAG_PARTFILE_PART_STATUS);
1063 const unsigned char *data =
1064 m_enc_map[file->GetFileHash()].Decode(
1065 (unsigned char *)parttag->GetTagData(),
1066 parttag->GetTagDataLen());
1067 for(int i = 0; i < file->GetPartCount(); ++i) {
1068 file->m_AvailPartFrequency[i] = data[i];
1070 if (m_inc_tags) {
1071 tag->SetRequests(file->statistic.requested);
1072 tag->SetAllRequests(file->statistic.alltimerequested);
1073 tag->SetAccepts(file->statistic.accepted);
1074 tag->SetAllAccepts(file->statistic.alltimeaccepted);
1075 tag->SetXferred(file->statistic.transferred );
1076 tag->SetAllXferred(file->statistic.alltimetransferred);
1077 tag->SetPrio(file->m_iUpPriority);
1078 } else {
1079 file->statistic.requested = tag->GetRequests();
1080 file->statistic.alltimerequested = tag->GetAllRequests();
1081 file->statistic.accepted = tag->GetAccepts();
1082 file->statistic.alltimeaccepted = tag->GetAllAccepts();
1083 file->statistic.transferred = tag->GetXferred();
1084 file->statistic.alltimetransferred = tag->GetAllXferred();
1085 file->m_iUpPriority = tag->Prio();
1087 if (file->m_iUpPriority >= 10) {
1088 file->m_iUpPriority -= 10;
1089 file->m_bAutoUpPriority = true;
1090 } else {
1091 file->m_bAutoUpPriority = false;
1094 theApp->knownfiles->requested += file->statistic.requested;
1095 theApp->knownfiles->transferred += file->statistic.transferred;
1096 theApp->knownfiles->accepted += file->statistic.transferred;
1098 theApp->amuledlg->m_sharedfileswnd->sharedfilesctrl->UpdateItem(file);
1101 bool CSharedFilesRem::Phase1Done(const CECPacket *)
1103 theApp->knownfiles->requested = 0;
1104 theApp->knownfiles->transferred = 0;
1105 theApp->knownfiles->accepted = 0;
1107 return true;
1110 void CSharedFilesRem::SetFilePrio(CKnownFile *file, uint8 prio)
1112 CECPacket req(EC_OP_SHARED_SET_PRIO);
1114 CECTag hashtag(EC_TAG_PARTFILE, file->GetFileHash());
1115 hashtag.AddTag(CECTag(EC_TAG_PARTFILE_PRIO, prio));
1117 req.AddTag(hashtag);
1119 m_conn->SendPacket(&req);
1123 * List of uploading and waiting clients.
1125 CUpDownClientListRem::CUpDownClientListRem(CRemoteConnect *conn, int viewtype)
1127 CRemoteContainer<CUpDownClient, uint32, CEC_UpDownClient_Tag>(conn)
1129 m_viewtype = viewtype;
1133 CUpDownClient::CUpDownClient(CEC_UpDownClient_Tag *tag)
1135 m_bRemoteQueueFull = false;
1136 m_nUserIDHybrid = tag->ID();
1137 m_Username = tag->ClientName();
1138 m_score = tag->Score();
1139 m_clientSoft = tag->ClientSoftware();
1140 m_clientVersionString = GetSoftName(m_clientSoft);
1141 m_clientSoftString = m_clientVersionString;
1143 // The functions to retrieve m_clientVerString information are
1144 // currently in BaseClient.cpp, which is not linked in remote-gui app.
1145 // So, in the meantime, we use a tag sent from core.
1146 m_clientVerString = tag->SoftVerStr();
1147 m_strModVersion = wxEmptyString;
1148 wxString clientModString;
1149 if (!clientModString.IsEmpty()) {
1150 m_clientVerString += wxT(" - ") + clientModString;
1152 m_fullClientVerString = m_clientSoftString + wxT(" ") + m_clientVerString;
1154 // User hash
1155 m_UserHash = tag->UserID();
1157 // User IP:Port
1158 m_nConnectIP = m_dwUserIP = tag->UserIP();
1159 m_nUserPort = tag->UserPort();
1160 m_FullUserIP = m_nConnectIP;
1162 // Server IP:Port
1163 m_dwServerIP = tag->ServerIP();
1164 m_nServerPort = tag->ServerPort();
1165 m_ServerName = tag->ServerName();
1167 m_waitingPosition = tag->WaitingPosition();
1169 m_Friend = 0;
1170 if (tag->HaveFile()) {
1171 CMD4Hash filehash = tag->FileID();
1172 m_uploadingfile = theApp->sharedfiles->GetByID(filehash);
1173 if (!m_uploadingfile) {
1174 m_uploadingfile = theApp->downloadqueue->GetByID(filehash);
1176 } else {
1177 m_uploadingfile = NULL;
1180 m_nCurSessionUp = 0;
1182 credits = new CClientCredits(new CreditStruct());
1185 uint16 CUpQueueRem::GetWaitingPosition(const CUpDownClient *client) const
1187 return client->GetWaitingPosition();
1190 /* Warning: do common base */
1193 bool CUpDownClient::IsIdentified() const
1195 return (credits && credits->GetCurrentIdentState(GetIP()) == IS_IDENTIFIED);
1199 bool CUpDownClient::IsBadGuy() const
1201 return (credits && credits->GetCurrentIdentState(GetIP()) == IS_IDBADGUY);
1205 bool CUpDownClient::SUIFailed() const
1207 return (credits && credits->GetCurrentIdentState(GetIP()) == IS_IDFAILED);
1211 bool CUpDownClient::SUINeeded() const
1213 return (credits && credits->GetCurrentIdentState(GetIP()) == IS_IDNEEDED);
1217 bool CUpDownClient::SUINotSupported() const
1219 return (credits && credits->GetCurrentIdentState(GetIP()) == IS_NOTAVAILABLE);
1223 uint64 CUpDownClient::GetDownloadedTotal() const
1225 return credits ? credits->GetDownloadedTotal() : 0;
1229 uint64 CUpDownClient::GetUploadedTotal() const
1231 return credits ? credits->GetUploadedTotal() : 0;
1235 double CUpDownClient::GetScoreRatio() const
1237 return credits ? credits->GetScoreRatio(GetIP(), theApp->CryptoAvailable()) : 0;
1240 /* End Warning */
1243 CUpDownClient::~CUpDownClient()
1245 if (credits) {
1246 delete credits;
1251 CUpDownClient *CUpDownClientListRem::CreateItem(CEC_UpDownClient_Tag *tag)
1253 CUpDownClient *client = new CUpDownClient(tag);
1254 ProcessItemUpdate(tag, client);
1256 theApp->amuledlg->m_transferwnd->clientlistctrl->InsertClient(client, (ViewType)m_viewtype);
1258 return client;
1262 void CUpDownClientListRem::DeleteItem(CUpDownClient *client)
1264 theApp->amuledlg->m_transferwnd->clientlistctrl->
1265 RemoveClient(client, (ViewType)m_viewtype);
1266 delete client;
1270 uint32 CUpDownClientListRem::GetItemID(CUpDownClient *client)
1272 return client->GetUserIDHybrid();
1276 void CUpDownClientListRem::ProcessItemUpdate(
1277 CEC_UpDownClient_Tag *tag,
1278 CUpDownClient *client)
1280 uint16 state = tag->ClientState();
1282 client->m_nDownloadState = state & 0xff;
1283 client->m_nUploadState = (state >> 8) & 0xff;
1285 client->m_nUpDatarate = tag->SpeedUp();
1286 if ( client->m_nDownloadState == DS_DOWNLOADING ) {
1287 client->kBpsDown = tag->SpeedDown() / 1024.0;
1288 } else {
1289 client->kBpsDown = 0;
1292 client->m_WaitTime = tag->WaitTime();
1293 client->m_UpStartTimeDelay = tag->XferTime();
1294 client->m_dwLastUpRequest = tag->LastReqTime();
1295 client->m_WaitStartTime = tag->QueueTime();
1297 CreditStruct *credit_struct =
1298 (CreditStruct *)client->credits->GetDataStruct();
1299 credit_struct->uploaded = tag->XferUp();
1300 client->m_nTransferredUp = tag->XferUpSession();
1302 credit_struct->downloaded = tag->XferDown();
1306 CUpQueueRem::CUpQueueRem(CRemoteConnect *conn)
1308 m_up_list(conn, vtUploading), m_wait_list(conn, vtQueued)
1314 * Download queue container: hold PartFiles with progress status
1319 CDownQueueRem::CDownQueueRem(CRemoteConnect *conn)
1321 CRemoteContainer<CPartFile, CMD4Hash, CEC_PartFile_Tag>(conn, true)
1326 bool CDownQueueRem::AddLink(const wxString &link, int)
1328 CECPacket req(EC_OP_ADD_LINK);
1329 req.AddTag(CECTag(EC_TAG_STRING, link));
1331 m_conn->SendPacket(&req);
1332 return true;
1336 void CDownQueueRem::StopUDPRequests()
1338 // have no idea what is it about
1342 void CDownQueueRem::ResetCatParts(int)
1344 // called when category being deleted. Command will be performed on remote side
1348 bool CDownQueueRem::IsPartFile(const CKnownFile *) const
1350 // hope i understand it right
1351 return true;
1355 void CDownQueueRem::OnConnectionState(bool)
1360 CPartFile *CDownQueueRem::CreateItem(CEC_PartFile_Tag *tag)
1362 CPartFile *file = new CPartFile(tag);
1363 m_enc_map[file->GetFileHash()] = PartFileEncoderData(file->GetPartCount(), 10);
1364 ProcessItemUpdate(tag, file);
1366 theApp->amuledlg->m_transferwnd->downloadlistctrl->AddFile(file);
1367 return file;
1371 void CDownQueueRem::DeleteItem(CPartFile *in_file)
1373 auto_ptr<CPartFile> file(in_file);
1375 theApp->amuledlg->m_transferwnd->downloadlistctrl->RemoveFile(file.get());
1377 m_enc_map.erase(file->GetFileHash());
1381 CMD4Hash CDownQueueRem::GetItemID(CPartFile *file)
1383 return file->GetFileHash();
1387 void CDownQueueRem::ProcessItemUpdate(CEC_PartFile_Tag *tag, CPartFile *file)
1390 // update status
1392 if (m_inc_tags) {
1393 uint32 tmpval = (uint32)(file->kBpsDown * 1024);
1394 tag->SetSpeed(tmpval);
1395 file->kBpsDown = tmpval / 1024.0;
1397 tag->SetSizeXfer(file->transferred);
1398 tag->SetSizeDone(file->completedsize);
1399 tag->SetSourceXferCount(file->transferingsrc);
1400 tag->SetSourceNotCurrCount(file->m_notCurrentSources);
1401 tag->SetSourceCount(file->m_source_count);
1402 tag->SetSourceCountA4AF(file->m_a4af_source_count);
1403 tag->SetFileStatus(file->status);
1405 tag->SetLastSeenComplete(file->lastseencomplete);
1407 tag->SetFileCat(file->m_category);
1409 tag->SetPrio(file->m_iDownPriority);
1410 } else {
1411 file->kBpsDown = tag->Speed() / 1024.0;
1413 if ( file->kBpsDown > 0 ) {
1414 file->transferred = tag->SizeXfer();
1415 file->SetCompletedSize(tag->SizeDone());
1418 file->transferingsrc = tag->SourceXferCount();
1419 file->m_notCurrentSources = tag->SourceNotCurrCount();
1420 file->m_source_count = tag->SourceCount();
1421 file->m_a4af_source_count = tag->SourceCountA4AF();
1422 file->status = tag->FileStatus();
1424 file->lastseencomplete = tag->LastSeenComplete();
1426 file->m_category = tag->FileCat();
1428 file->m_iDownPriority = tag->Prio();
1429 if ( file->m_iDownPriority >= 10 ) {
1430 file->m_iDownPriority-= 10;
1431 file->m_bAutoDownPriority = true;
1432 } else {
1433 file->m_bAutoDownPriority = false;
1436 file->percentcompleted = (100.0*file->GetCompletedSize()) / file->GetFileSize();
1437 if ( file->m_iDownPriority >= 10 ) {
1438 file->m_iDownPriority -= 10;
1439 file->m_bAutoUpPriority = true;
1440 } else {
1441 file->m_bAutoUpPriority = false;
1445 // Copy part/gap status
1447 CECTag *gaptag = tag->GetTagByName(EC_TAG_PARTFILE_GAP_STATUS);
1448 CECTag *parttag = tag->GetTagByName(EC_TAG_PARTFILE_PART_STATUS);
1449 CECTag *reqtag = tag->GetTagByName(EC_TAG_PARTFILE_REQ_STATUS);
1450 if (gaptag && parttag && reqtag) {
1451 wxASSERT(m_enc_map.count(file->GetFileHash()));
1453 PartFileEncoderData &encoder = m_enc_map[file->GetFileHash()];
1454 encoder.Decode(
1455 (unsigned char *)gaptag->GetTagData(), gaptag->GetTagDataLen(),
1456 (unsigned char *)parttag->GetTagData(), parttag->GetTagDataLen());
1458 const uint64 *reqparts = (const uint64 *)reqtag->GetTagData();
1459 unsigned reqcount = reqtag->GetTagDataLen() / (2 * sizeof(uint64));
1461 unsigned gap_size = encoder.m_gap_status.Size() / (2 * sizeof(uint64));
1462 // clear gaplist
1463 file->m_gaplist.Init(file->GetFileSize(), false);
1465 // and refill it
1466 const uint64 *gap_info = (const uint64 *)encoder.m_gap_status.Buffer();
1467 for (unsigned j = 0; j < gap_size;j++) {
1468 file->m_gaplist.AddGap(ENDIAN_NTOHLL(gap_info[2*j]), ENDIAN_NTOHLL(gap_info[2*j+1]));
1471 // adjust size of requested block list
1472 while ( file->m_requestedblocks_list.size() > reqcount ) {
1473 delete file->m_requestedblocks_list.front();
1474 file->m_requestedblocks_list.pop_front();
1476 while ( file->m_requestedblocks_list.size() != reqcount ) {
1477 file->m_requestedblocks_list.push_front(new Requested_Block_Struct);
1480 std::list<Requested_Block_Struct*>::iterator it2 = file->m_requestedblocks_list.begin();
1481 for (unsigned i = 0; i < reqcount; ++i) {
1482 Requested_Block_Struct* block = *it2++;
1483 block->StartOffset = ENDIAN_NTOHLL(reqparts[2*i]);
1484 block->EndOffset = ENDIAN_NTOHLL(reqparts[2*i+1]);
1486 // copy parts frequency
1487 const unsigned char *part_info = encoder.m_part_status.Buffer();
1488 for(int i = 0; i < file->GetPartCount(); ++i) {
1489 file->m_SrcpartFrequency[i] = part_info[i];
1491 } else {
1492 AddLogLineNS(CFormat(wxT("ERROR: %X %X %X")) % (size_t)gaptag % (size_t)parttag % (size_t)reqtag);
1495 // Get source names
1496 CECTag *srcnametag = tag->GetTagByName(EC_TAG_PARTFILE_SOURCE_NAMES);
1497 if (srcnametag) {
1498 file->ClearSourcenameItemList();
1499 int max = srcnametag->GetTagCount();
1500 for (int i = 0; i < max - 1; ) {
1501 wxString name = srcnametag->GetTagByIndex(i++)->GetStringData();
1502 long count = srcnametag->GetTagByIndex(i++)->GetInt();
1503 file->AddSourcenameItemList(name, count);
1507 // Get comments
1508 CECTag *commenttag = tag->GetTagByName(EC_TAG_PARTFILE_COMMENTS);
1509 if (commenttag) {
1510 file->ClearFileRatingList();
1511 int max = commenttag->GetTagCount();
1512 for (int i = 0; i < max - 3; ) {
1513 wxString u = commenttag->GetTagByIndex(i++)->GetStringData();
1514 wxString f = commenttag->GetTagByIndex(i++)->GetStringData();
1515 int r = commenttag->GetTagByIndex(i++)->GetInt();
1516 wxString c = commenttag->GetTagByIndex(i++)->GetStringData();
1517 file->AddFileRatingList(u, f, r, c);
1519 file->UpdateFileRatingCommentAvail();
1522 theApp->amuledlg->m_transferwnd->downloadlistctrl->UpdateItem(file);
1526 bool CDownQueueRem::Phase1Done(const CECPacket *)
1528 return true;
1532 void CDownQueueRem::SendFileCommand(CPartFile *file, ec_tagname_t cmd)
1534 CECPacket req(cmd);
1535 req.AddTag(CECTag(EC_TAG_PARTFILE, file->GetFileHash()));
1537 m_conn->SendPacket(&req);
1541 void CDownQueueRem::Prio(CPartFile *file, uint8 prio)
1543 CECPacket req(EC_OP_PARTFILE_PRIO_SET);
1545 CECTag hashtag(EC_TAG_PARTFILE, file->GetFileHash());
1546 hashtag.AddTag(CECTag(EC_TAG_PARTFILE_PRIO, prio));
1547 req.AddTag(hashtag);
1549 m_conn->SendPacket(&req);
1553 void CDownQueueRem::AutoPrio(CPartFile *file, bool flag)
1555 CECPacket req(EC_OP_PARTFILE_PRIO_SET);
1557 CECTag hashtag(EC_TAG_PARTFILE, file->GetFileHash());
1559 hashtag.AddTag(CECTag(EC_TAG_PARTFILE_PRIO,
1560 (uint8)(flag ? PR_AUTO : file->GetDownPriority())));
1561 req.AddTag(hashtag);
1563 m_conn->SendPacket(&req);
1567 void CDownQueueRem::Category(CPartFile *file, uint8 cat)
1569 CECPacket req(EC_OP_PARTFILE_SET_CAT);
1570 file->m_category = cat;
1572 CECTag hashtag(EC_TAG_PARTFILE, file->GetFileHash());
1573 hashtag.AddTag(CECTag(EC_TAG_PARTFILE_CAT, cat));
1574 req.AddTag(hashtag);
1576 m_conn->SendPacket(&req);
1580 void CDownQueueRem::AddSearchToDownload(CSearchFile* file, uint8 category)
1582 CECPacket req(EC_OP_DOWNLOAD_SEARCH_RESULT);
1583 CECTag hashtag(EC_TAG_PARTFILE, file->GetFileHash());
1584 hashtag.AddTag(CECTag(EC_TAG_PARTFILE_CAT, category));
1585 req.AddTag(hashtag);
1587 m_conn->SendPacket(&req);
1591 CClientListRem::CClientListRem(CRemoteConnect *conn)
1593 m_conn = conn;
1597 void CClientListRem::FilterQueues()
1599 // FIXME: add code
1600 //wxFAIL;
1604 CSearchListRem::CSearchListRem(CRemoteConnect *conn) : CRemoteContainer<CSearchFile, CMD4Hash, CEC_SearchFile_Tag>(conn)
1606 m_curr_search = -1;
1610 wxString CSearchListRem::StartNewSearch(
1611 uint32* nSearchID, SearchType search_type,
1612 const CSearchList::CSearchParams& params)
1614 CECPacket search_req(EC_OP_SEARCH_START);
1615 EC_SEARCH_TYPE ec_search_type = EC_SEARCH_LOCAL;
1616 switch(search_type) {
1617 case LocalSearch: ec_search_type = EC_SEARCH_LOCAL; break;
1618 case GlobalSearch: ec_search_type = EC_SEARCH_GLOBAL; break;
1619 case KadSearch: ec_search_type = EC_SEARCH_KAD; break;
1621 search_req.AddTag(
1622 CEC_Search_Tag(params.searchString, ec_search_type,
1623 params.typeText, params.extension, params.availability,
1624 params.minSize, params.maxSize));
1626 m_conn->SendPacket(&search_req);
1627 m_curr_search = *(nSearchID); // No kad remote search yet.
1629 Flush();
1631 return wxEmptyString; // EC reply will have the error mesg is needed.
1635 void CSearchListRem::StopGlobalSearch()
1637 if (m_curr_search != -1) {
1638 CECPacket search_req(EC_OP_SEARCH_STOP);
1639 m_conn->SendPacket(&search_req);
1644 void CSearchListRem::HandlePacket(const CECPacket *packet)
1646 if ( packet->GetOpCode() == EC_OP_SEARCH_PROGRESS ) {
1647 CoreNotify_Search_Update_Progress(packet->GetTagByIndex(0)->GetInt());
1648 } else {
1649 CRemoteContainer<CSearchFile, CMD4Hash, CEC_SearchFile_Tag>::HandlePacket(packet);
1654 CSearchFile::CSearchFile(CEC_SearchFile_Tag *tag)
1656 m_parent(NULL),
1657 m_showChildren(false),
1658 m_sourceCount(0),
1659 m_completeSourceCount(0),
1660 m_kademlia(false),
1661 m_clientID(0),
1662 m_clientPort(0)
1664 SetFileName(CPath(tag->FileName()));
1665 m_abyFileHash = tag->ID();
1666 SetFileSize(tag->SizeFull());
1668 m_searchID = theApp->searchlist->m_curr_search;
1673 // dtor is virtual - must be implemented
1674 CSearchFile::~CSearchFile()
1679 CSearchFile *CSearchListRem::CreateItem(CEC_SearchFile_Tag *tag)
1681 CSearchFile *file = new CSearchFile(tag);
1682 ProcessItemUpdate(tag, file);
1684 theApp->amuledlg->m_searchwnd->AddResult(file);
1686 return file;
1690 void CSearchListRem::DeleteItem(CSearchFile *file)
1692 delete file;
1696 CMD4Hash CSearchListRem::GetItemID(CSearchFile *file)
1698 return file->GetFileHash();
1702 void CSearchListRem::ProcessItemUpdate(CEC_SearchFile_Tag *tag, CSearchFile *file)
1704 file->m_sourceCount = tag->SourceCount();
1705 file->m_completeSourceCount = tag->CompleteSourceCount();
1709 bool CSearchListRem::Phase1Done(const CECPacket *WXUNUSED(reply))
1711 CECPacket progress_req(EC_OP_SEARCH_PROGRESS);
1712 m_conn->SendRequest(this, &progress_req);
1714 return true;
1718 void CSearchListRem::RemoveResults(long nSearchID)
1720 ResultMap::iterator it = m_results.find(nSearchID);
1721 if (it != m_results.end()) {
1722 CSearchResultList& list = it->second;
1723 for (unsigned int i = 0; i < list.size(); ++i) {
1724 delete list[i];
1726 m_results.erase(it);
1731 const CSearchResultList& CSearchListRem::GetSearchResults(long nSearchID)
1733 ResultMap::const_iterator it = m_results.find(nSearchID);
1734 if (it != m_results.end()) {
1735 return it->second;
1738 // TODO: Should we assert in this case?
1739 static CSearchResultList list;
1740 return list;
1744 void CStatsUpdaterRem::HandlePacket(const CECPacket *packet)
1746 theStats::UpdateStats(packet);
1747 theApp->ShowUserCount(); // maybe there should be a check if a usercount changed ?
1751 bool CUpDownClient::IsBanned() const
1753 // FIXME: add code
1754 return false;
1759 // Those functions have different implementation in remote gui
1761 void CUpDownClient::Ban()
1763 // FIXME: add code
1764 wxFAIL;
1768 void CUpDownClient::UnBan()
1770 // FIXME: add code
1771 wxFAIL;
1775 void CUpDownClient::RequestSharedFileList()
1777 // FIXME: add code
1778 wxFAIL;
1782 void CKnownFile::SetFileComment(const wxString &)
1784 // FIXME: add code
1785 wxFAIL;
1789 void CKnownFile::SetFileRating(unsigned char)
1791 // FIXME: add code
1792 wxFAIL;
1796 // I don't think it will be implemented - too match data transfer. But who knows ?
1797 wxString CUpDownClient::ShowDownloadingParts() const
1799 return wxEmptyString;
1803 bool CUpDownClient::SwapToAnotherFile(
1804 bool WXUNUSED(bIgnoreNoNeeded),
1805 bool WXUNUSED(ignoreSuspensions),
1806 bool WXUNUSED(bRemoveCompletely),
1807 CPartFile* WXUNUSED(toFile))
1809 // FIXME: add code
1810 wxFAIL;
1811 return false;
1816 // Those functions are virtual. So even they don't get called they must
1817 // be defined so linker will be happy
1819 CPacket* CKnownFile::CreateSrcInfoPacket(const CUpDownClient *, uint8 /*byRequestedVersion*/, uint16 /*nRequestedOptions*/)
1821 wxFAIL;
1822 return 0;
1826 bool CKnownFile::LoadFromFile(const class CFileDataIO*)
1828 wxFAIL;
1829 return false;
1833 void CKnownFile::UpdatePartsInfo()
1835 wxFAIL;
1839 CPacket* CPartFile::CreateSrcInfoPacket(CUpDownClient const *, uint8 /*byRequestedVersion*/, uint16 /*nRequestedOptions*/)
1841 wxFAIL;
1842 return 0;
1846 void CPartFile::UpdatePartsInfo()
1848 wxFAIL;
1852 void CPartFile::UpdateFileRatingCommentAvail()
1854 bool prevComment = m_hasComment;
1855 int prevRating = m_iUserRating;
1857 m_hasComment = false;
1858 m_iUserRating = 0;
1859 int ratingCount = 0;
1861 FileRatingList::iterator it = m_FileRatingList.begin();
1862 for (; it != m_FileRatingList.end(); ++it) {
1863 SFileRating& cur_rat = *it;
1865 if (!cur_rat.Comment.IsEmpty()) {
1866 m_hasComment = true;
1869 uint8 rating = cur_rat.Rating;
1870 if (rating) {
1871 wxASSERT(rating <= 5);
1873 ratingCount++;
1874 m_iUserRating += rating;
1878 if (ratingCount) {
1879 m_iUserRating /= ratingCount;
1880 wxASSERT(m_iUserRating > 0 && m_iUserRating <= 5);
1883 if ((prevComment != m_hasComment) || (prevRating != m_iUserRating)) {
1884 UpdateDisplayedInfo();
1888 bool CPartFile::SavePartFile(bool)
1890 wxFAIL;
1891 return false;
1896 // since gui is not linked with amule.cpp - define events here
1898 DEFINE_LOCAL_EVENT_TYPE(wxEVT_CORE_FINISHED_HTTP_DOWNLOAD)
1899 DEFINE_LOCAL_EVENT_TYPE(wxEVT_CORE_SOURCE_DNS_DONE)
1900 DEFINE_LOCAL_EVENT_TYPE(wxEVT_CORE_UDP_DNS_DONE)
1901 DEFINE_LOCAL_EVENT_TYPE(wxEVT_CORE_SERVER_DNS_DONE)
1902 // File_checked_for_headers