Upstream tarball 9706
[amule.git] / src / amule-remote-gui.cpp
blob93be322b4af9b6625134d70370d43f3218cb7210
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 <wx/ipc.h>
30 #include <wx/cmdline.h> // Needed for wxCmdLineParser
31 #include <wx/config.h> // Do_not_auto_remove (win32)
32 #include <wx/fileconf.h> // Needed for wxFileConfig
35 #include <common/Format.h>
36 #include <common/StringFunctions.h>
37 #include <common/MD5Sum.h>
40 #include <include/common/EventIDs.h>
43 #include "amule.h" // Interface declarations.
44 #include "amuleDlg.h" // Needed for CamuleDlg
45 #include "ClientCredits.h"
46 #include "ClientListCtrl.h"
47 #include "DataToText.h" // Needed for GetSoftName()
48 #include "DownloadListCtrl.h" // Needed for CDownloadListCtrl
49 #include "GuiEvents.h"
50 #ifdef ENABLE_IP2COUNTRY
51 #include "IP2Country.h" // Needed for IP2Country
52 #endif
53 #include "InternalEvents.h" // Needed for wxEVT_CORE_FINISHED_HTTP_DOWNLOAD
54 #include "Logger.h"
55 #include "muuli_wdr.h" // Needed for IDs
56 #include "PartFile.h" // Needed for CPartFile
57 #include "SearchDlg.h" // Needed for CSearchDlg
58 #include "Server.h" // Needed for GetListName
59 #include "ServerWnd.h" // Needed for CServerWnd
60 #include "SharedFilesCtrl.h" // Needed for CSharedFilesCtrl
61 #include "SharedFilesWnd.h" // Needed for CSharedFilesWnd
62 #include "TransferWnd.h" // Needed for CTransferWnd
63 #include "updownclient.h"
64 #include "ServerListCtrl.h" // Needed for CServerListCtrl
65 #include "MagnetURI.h" // Needed for CMagnetURI
66 #include "ScopedPtr.h"
69 CEConnectDlg::CEConnectDlg()
71 wxDialog(theApp->amuledlg, -1, _("Connect to remote amule"), wxDefaultPosition)
73 CoreConnect(this, true);
75 wxString pref_host, pref_port;
76 wxConfig::Get()->Read(wxT("/EC/Host"), &pref_host, wxT("localhost"));
77 wxConfig::Get()->Read(wxT("/EC/Port"), &pref_port, wxT("4712"));
78 wxConfig::Get()->Read(wxT("/EC/Password"), &pwd_hash);
80 CastChild(ID_REMOTE_HOST, wxTextCtrl)->SetValue(pref_host);
81 CastChild(ID_REMOTE_PORT, wxTextCtrl)->SetValue(pref_port);
82 CastChild(ID_EC_PASSWD, wxTextCtrl)->SetValue(pwd_hash);
84 CentreOnParent();
88 wxString CEConnectDlg::PassHash()
90 return pwd_hash;
94 BEGIN_EVENT_TABLE(CEConnectDlg, wxDialog)
95 EVT_BUTTON(wxID_OK, CEConnectDlg::OnOK)
96 END_EVENT_TABLE()
99 void CEConnectDlg::OnOK(wxCommandEvent& evt)
101 wxString s_port = CastChild(ID_REMOTE_PORT, wxTextCtrl)->GetValue();
102 port = StrToLong(s_port);
104 host = CastChild(ID_REMOTE_HOST, wxTextCtrl)->GetValue();
105 passwd = CastChild(ID_EC_PASSWD, wxTextCtrl)->GetValue();
107 if (passwd != pwd_hash) {
108 pwd_hash = MD5Sum(passwd).GetHash();
110 m_save_user_pass = CastChild(ID_EC_SAVE, wxCheckBox)->IsChecked();
111 evt.Skip();
115 DEFINE_LOCAL_EVENT_TYPE(wxEVT_EC_INIT_DONE)
118 BEGIN_EVENT_TABLE(CamuleRemoteGuiApp, wxApp)
119 // Core timer
120 EVT_TIMER(ID_CORE_TIMER_EVENT, CamuleRemoteGuiApp::OnPollTimer)
122 EVT_CUSTOM(wxEVT_EC_CONNECTION, -1, CamuleRemoteGuiApp::OnECConnection)
123 EVT_CUSTOM(wxEVT_EC_INIT_DONE, -1, CamuleRemoteGuiApp::OnECInitDone)
125 EVT_MULE_NOTIFY(CamuleRemoteGuiApp::OnNotifyEvent)
127 #ifdef ENABLE_IP2COUNTRY
128 // HTTPDownload finished
129 EVT_MULE_INTERNAL(wxEVT_CORE_FINISHED_HTTP_DOWNLOAD, -1, CamuleRemoteGuiApp::OnFinishedHTTPDownload)
130 #endif
131 END_EVENT_TABLE()
134 IMPLEMENT_APP(CamuleRemoteGuiApp)
137 int CamuleRemoteGuiApp::OnExit()
139 StopTickTimer();
141 return wxApp::OnExit();
145 void CamuleRemoteGuiApp::OnPollTimer(wxTimerEvent&)
147 static int request_step = 0;
149 if (m_connect->RequestFifoFull()) {
150 return;
153 switch (request_step) {
154 case 0:
155 serverconnect->ReQuery();
156 serverlist->UpdateUserFileStatus(serverconnect->GetCurrentServer());
157 request_step++;
158 break;
159 case 1: {
160 CECPacket stats_req(EC_OP_STAT_REQ);
161 m_connect->SendRequest(&m_stats_updater, &stats_req);
162 amuledlg->ShowTransferRate();
163 request_step++;
164 break;
166 case 2:
167 if (amuledlg->m_sharedfileswnd->IsShown()) {
168 sharedfiles->DoRequery(EC_OP_GET_SHARED_FILES, EC_TAG_KNOWNFILE);
169 } else if (amuledlg->m_serverwnd->IsShown()) {
170 //serverlist->FullReload(EC_OP_GET_SERVER_LIST);
171 } else if (amuledlg->m_transferwnd->IsShown()) {
172 downloadqueue->DoRequery(EC_OP_GET_DLOAD_QUEUE,
173 EC_TAG_PARTFILE, EC_DETAIL_INC_UPDATE);
174 switch(amuledlg->m_transferwnd->clientlistctrl->GetListView()) {
175 case vtUploading:
176 uploadqueue->ReQueryUp();
177 break;
178 case vtQueued:
179 uploadqueue->ReQueryWait();
180 break;
181 case vtClients:
182 break;
183 case vtNone:
184 break;
186 amuledlg->m_transferwnd->ShowQueueCount(theStats::GetWaitingUserCount());
187 } else if (amuledlg->m_searchwnd->IsShown()) {
188 if (searchlist->m_curr_search != -1) {
189 searchlist->DoRequery(EC_OP_SEARCH_RESULTS, EC_TAG_SEARCHFILE);
192 // Back to the roots
193 request_step = 0;
194 break;
195 default:
196 AddLogLineCS(wxT("WTF?")); // should not happen. :-)
197 request_step = 0;
202 void CamuleRemoteGuiApp::OnFinishedHTTPDownload(CMuleInternalEvent& event)
204 #ifdef ENABLE_IP2COUNTRY
205 if (event.GetInt() == HTTP_GeoIP) {
206 amuledlg->IP2CountryDownloadFinished(event.GetExtraLong());
207 // If we updated, the dialog is already up. Redraw it to show the flags.
208 amuledlg->Refresh();
210 #endif
214 void CamuleRemoteGuiApp::ShutDown(wxCloseEvent &WXUNUSED(evt))
216 // Stop the Core Timer
217 delete poll_timer;
218 poll_timer = NULL;
220 // Destroy the EC socket
221 m_connect->Destroy();
222 m_connect = NULL;
225 if (amuledlg) {
226 amuledlg->DlgShutDown();
227 amuledlg->Destroy();
228 amuledlg = NULL;
233 bool CamuleRemoteGuiApp::OnInit()
235 StartTickTimer();
236 amuledlg = NULL;
237 if ( !wxApp::OnInit() ) {
238 return false;
241 // Get theApp
242 theApp = &wxGetApp();
244 // Handle uncaught exceptions
245 InstallMuleExceptionHandler();
247 // Create the polling timer
248 poll_timer = new wxTimer(this,ID_CORE_TIMER_EVENT);
249 if (!poll_timer) {
250 AddLogLineCS(_("Fatal Error: Failed to create Poll Timer"));
251 OnExit();
254 m_connect = new CRemoteConnect(this);
255 SetAppName(wxT("aMule"));
257 // Load Preferences
258 // This creates the CFG file we shall use
259 ConfigDir = GetConfigDir();
260 if (!wxDirExists(ConfigDir)) {
261 wxMkdir(ConfigDir);
264 wxConfig::Set(new wxFileConfig(wxEmptyString, wxEmptyString,
265 ConfigDir + wxT("remote.conf")));
267 glob_prefs = new CPreferencesRem(m_connect);
269 InitCustomLanguages();
270 InitLocale(m_locale, StrLang2wx(thePrefs::GetLanguageID()));
272 bool result = ShowConnectionDialog();
274 AddLogLineNS(_("Going to event loop..."));
276 return result;
280 bool CamuleRemoteGuiApp::CryptoAvailable() const
282 return thePrefs::IsSecureIdentEnabled(); // good enough
286 bool CamuleRemoteGuiApp::ShowConnectionDialog() {
288 dialog = new CEConnectDlg;
290 if (dialog->ShowModal() != wxID_OK) {
291 dialog->Destroy();
293 return false;
295 AddLogLineNS(_("Connecting..."));
296 if (!m_connect->ConnectToCore(dialog->Host(), dialog->Port(),
297 dialog->Login(), dialog->PassHash(),
298 wxT("amule-remote"), wxT("0x0001"))) {
299 wxMessageBox(_("Connection failed "),_("ERROR"),wxOK);
301 return false;
304 return true;
308 void CamuleRemoteGuiApp::OnECConnection(wxEvent& event) {
309 wxECSocketEvent& evt = *((wxECSocketEvent*)&event);
310 AddLogLineNS(_("Remote GUI EC event handler"));
311 wxString reply = evt.GetServerReply();
312 AddLogLineM(true, reply);
313 if (evt.GetResult() == true) {
314 // Connected - go to next init step
315 glob_prefs->LoadRemote();
316 } else {
317 AddLogLineNS(_("Going down"));
318 if (dialog) { // connect failed
319 wxMessageBox(
320 (CFormat(_("Connection Failed. Unable to connect to %s:%d\n")) % dialog->Host() % dialog->Port()) + reply,
321 _("ERROR"), wxOK);
322 } else { // server disconnected (probably terminated) later
323 wxMessageBox(_("Connection closed - aMule has terminated probably."), _("ERROR"), wxOK);
325 ExitMainLoop();
330 void CamuleRemoteGuiApp::OnECInitDone(wxEvent& )
332 Startup();
336 void CamuleRemoteGuiApp::OnNotifyEvent(CMuleGUIEvent& evt)
338 evt.Notify();
342 void CamuleRemoteGuiApp::Startup() {
344 if (dialog->SaveUserPass()) {
345 wxConfig::Get()->Write(wxT("/EC/Host"), dialog->Host());
346 wxConfig::Get()->Write(wxT("/EC/Port"), dialog->Port());
347 wxConfig::Get()->Write(wxT("/EC/Password"), dialog->PassHash());
349 dialog->Destroy();
350 dialog = NULL;
352 m_ConnState = 0;
353 m_clientID = 0;
355 serverconnect = new CServerConnectRem(m_connect);
356 m_statistics = new CStatistics(*m_connect);
358 clientlist = new CClientListRem(m_connect);
359 searchlist = new CSearchListRem(m_connect);
360 serverlist = new CServerListRem(m_connect);
362 sharedfiles = new CSharedFilesRem(m_connect);
363 knownfiles = new CKnownFilesRem(sharedfiles);
365 // bugfix - do this before creating the uploadqueue
366 downloadqueue = new CDownQueueRem(m_connect);
367 uploadqueue = new CUpQueueRem(m_connect);
368 ipfilter = new CIPFilterRem(m_connect);
370 // Parse cmdline arguments.
371 wxCmdLineParser cmdline(wxApp::argc, wxApp::argv);
372 cmdline.AddSwitch(wxT("v"), wxT("version"),
373 wxT("Displays the current version number."));
374 cmdline.AddSwitch(wxT("h"), wxT("help"),
375 wxT("Displays this information."));
376 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>]"));
377 cmdline.Parse();
379 bool geometry_enabled = false;
380 wxString geom_string;
381 if (cmdline.Found(wxT("geometry"), &geom_string)) {
382 geometry_enabled = true;
385 // Create main dialog
386 InitGui(0, geom_string);
388 // Forward wxLog events to CLogger
389 wxLog::SetActiveTarget(new CLoggerTarget);
390 serverlist->FullReload(EC_OP_GET_SERVER_LIST);
391 sharedfiles->DoRequery(EC_OP_GET_SHARED_FILES, EC_TAG_KNOWNFILE);
393 // Start the Poll Timer
394 poll_timer->Start(1000);
395 amuledlg->StartGuiTimer();
397 // Now activate GeoIP, so that the download dialog doesn't get destroyed immediately
398 #ifdef ENABLE_IP2COUNTRY
399 if (thePrefs::IsGeoIPEnabled()) {
400 amuledlg->m_IP2Country->Enable();
402 #endif
406 int CamuleRemoteGuiApp::ShowAlert(wxString msg, wxString title, int flags)
408 return CamuleGuiBase::ShowAlert(msg, title, flags);
412 void CamuleRemoteGuiApp::AddRemoteLogLine(const wxString& line)
414 amuledlg->AddLogLine(line);
417 int CamuleRemoteGuiApp::InitGui(bool geometry_enabled, wxString &geom_string)
419 CamuleGuiBase::InitGui(geometry_enabled, geom_string);
420 SetTopWindow(amuledlg);
421 AddLogLineN(_("Ready")); // The first log line after the window is up triggers output of all the ones before
422 return 0;
426 bool CamuleRemoteGuiApp::CopyTextToClipboard(wxString strText)
428 return CamuleGuiBase::CopyTextToClipboard(strText);
432 uint32 CamuleRemoteGuiApp::GetPublicIP()
434 return 0;
438 wxString CamuleRemoteGuiApp::GetLog(bool)
440 return wxEmptyString;
444 wxString CamuleRemoteGuiApp::GetServerLog(bool)
446 return wxEmptyString;
450 wxString CamuleRemoteGuiApp::CreateMagnetLink(const CAbstractFile* f)
452 // TODO: Remove duplicate code (also in amule.cpp) ...
453 CMagnetURI uri;
455 uri.AddField(wxT("dn"), f->GetFileName().Cleanup(false).GetPrintable());
456 uri.AddField(wxT("xt"), wxString(wxT("urn:ed2k:")) + f->GetFileHash().Encode().Lower());
457 uri.AddField(wxT("xt"), wxString(wxT("urn:ed2khash:")) + f->GetFileHash().Encode().Lower());
458 uri.AddField(wxT("xl"), wxString::Format(wxT("%") wxLongLongFmtSpec wxT("u"), f->GetFileSize()));
460 return uri.GetLink();
463 wxString CamuleRemoteGuiApp::CreateED2kLink(const CAbstractFile* f, bool add_source, bool use_hostname, bool addcryptoptions)
465 // TODO: Avoid duplicate code (also in amule.cpp) ...
466 wxASSERT(!(!add_source && (use_hostname || addcryptoptions)));
467 // Construct URL like this: ed2k://|file|<filename>|<size>|<hash>|/
468 wxString strURL = CFormat(wxT("ed2k://|file|%s|%i|%s|/"))
469 % f->GetFileName().Cleanup(false)
470 % f->GetFileSize() % f->GetFileHash().Encode();
472 if (add_source && IsConnected() && !IsFirewalled()) {
473 // Create the first part of the URL
474 strURL << wxT("|sources,");
476 if (use_hostname) {
477 strURL << thePrefs::GetYourHostname();
478 } else {
479 uint32 clientID = GetID();
480 strURL << (uint8) clientID << wxT(".") <<
481 (uint8)(clientID >> 8) << wxT(".") <<
482 (uint8)(clientID >> 16) << wxT(".") <<
483 (uint8)(clientID >> 24);
486 strURL << wxT(":") <<
487 thePrefs::GetPort();
489 if (addcryptoptions) {
490 const uint8 uSupportsCryptLayer = thePrefs::IsClientCryptLayerSupported() ? 1 : 0;
491 const uint8 uRequestsCryptLayer = thePrefs::IsClientCryptLayerRequested() ? 1 : 0;
492 const uint8 uRequiresCryptLayer = thePrefs::IsClientCryptLayerRequired() ? 1 : 0;
493 const uint8 byCryptOptions = (uRequiresCryptLayer << 2) | (uRequestsCryptLayer << 1) | (uSupportsCryptLayer << 0) | (uSupportsCryptLayer ? 0x80 : 0x00);
495 strURL << wxT(":") << byCryptOptions;
497 if (byCryptOptions & 0x80) {
498 strURL << wxT(":") << thePrefs::GetUserHash().Encode();
502 strURL << wxT("|/");
503 } else if (add_source) {
504 AddLogLineM(true, _("WARNING: You can't add yourself as a source for an eD2k link while having a lowid."));
507 // Result is "ed2k://|file|<filename>|<size>|<hash>|/|sources,[(<ip>|<hostname>):<port>[:cryptoptions[:hash]]]|/"
508 return strURL;
512 wxString CamuleRemoteGuiApp::CreateED2kAICHLink(const CKnownFile* f)
514 // TODO: Avoid duplicate code (also in amule.cpp) ...
515 // Create the first part of the URL
516 wxString strURL = CreateED2kLink(f);
517 // Append the AICH info
518 if (f->HasProperAICHHashSet()) {
519 strURL.RemoveLast(); // remove trailing '/'
520 strURL << wxT("h=") << f->GetAICHMasterHash() << wxT("|/");
523 // Result is "ed2k://|file|<filename>|<size>|<hash>|h=<AICH master hash>|/"
524 return strURL;
528 bool CamuleRemoteGuiApp::AddServer(CServer *, bool)
530 // #warning TODO: Add remote command
531 return true;
535 bool CamuleRemoteGuiApp::IsFirewalled() const
537 if (IsConnectedED2K() && !serverconnect->IsLowID()) {
538 return false;
541 return IsFirewalledKad();
545 bool CamuleRemoteGuiApp::IsConnectedED2K() const {
546 return serverconnect && serverconnect->IsConnected();
550 void CamuleRemoteGuiApp::StartKad() {
551 m_connect->StartKad();
555 void CamuleRemoteGuiApp::StopKad() {
556 m_connect->StopKad();
560 void CamuleRemoteGuiApp::BootstrapKad(uint32 ip, uint16 port)
562 CECPacket req(EC_OP_KAD_BOOTSTRAP_FROM_IP);
563 req.AddTag(CECTag(EC_TAG_BOOTSTRAP_IP, ip));
564 req.AddTag(CECTag(EC_TAG_BOOTSTRAP_PORT, port));
566 m_connect->SendPacket(&req);
570 void CamuleRemoteGuiApp::UpdateNotesDat(const wxString& url)
572 CECPacket req(EC_OP_KAD_UPDATE_FROM_URL);
573 req.AddTag(CECTag(EC_TAG_KADEMLIA_UPDATE_URL, url));
575 m_connect->SendPacket(&req);
579 void CamuleRemoteGuiApp::DisconnectED2K() {
580 if (IsConnectedED2K()) {
581 m_connect->DisconnectED2K();
586 uint32 CamuleRemoteGuiApp::GetED2KID() const
588 return serverconnect ? serverconnect->GetClientID() : 0;
592 uint32 CamuleRemoteGuiApp::GetID() const
594 return m_clientID;
598 void CamuleRemoteGuiApp::ShowUserCount() {
599 wxString buffer;
601 static const wxString s_singlenetstatusformat = _("Users: %s | Files: %s");
602 static const wxString s_bothnetstatusformat = _("Users: E: %s K: %s | Files: E: %s K: %s");
604 if (thePrefs::GetNetworkED2K() && thePrefs::GetNetworkKademlia()) {
605 buffer = CFormat(s_bothnetstatusformat) % CastItoIShort(theStats::GetED2KUsers()) % CastItoIShort(theStats::GetKadUsers()) % CastItoIShort(theStats::GetED2KFiles()) % CastItoIShort(theStats::GetKadFiles());
606 } else if (thePrefs::GetNetworkED2K()) {
607 buffer = CFormat(s_singlenetstatusformat) % CastItoIShort(theStats::GetED2KUsers()) % CastItoIShort(theStats::GetED2KFiles());
608 } else if (thePrefs::GetNetworkKademlia()) {
609 buffer = CFormat(s_singlenetstatusformat) % CastItoIShort(theStats::GetKadUsers()) % CastItoIShort(theStats::GetKadFiles());
610 } else {
611 buffer = _("No networks selected");
614 Notify_ShowUserCount(buffer);
619 * Preferences: holds both local and remote settings.
621 * First, everything is loaded from local config file. Later, settings
622 * that are relevant on remote side only are loaded thru EC
624 CPreferencesRem::CPreferencesRem(CRemoteConnect *conn)
626 m_conn = conn;
628 CPreferences::BuildItemList(theApp->ConfigDir);
629 CPreferences::LoadAllItems(wxConfigBase::Get());
632 // Settings queried from remote side
634 m_exchange_send_selected_prefs =
635 EC_PREFS_GENERAL |
636 EC_PREFS_CONNECTIONS |
637 EC_PREFS_MESSAGEFILTER |
638 EC_PREFS_ONLINESIG |
639 EC_PREFS_SERVERS |
640 EC_PREFS_FILES |
641 EC_PREFS_SRCDROP |
642 EC_PREFS_SECURITY |
643 EC_PREFS_CORETWEAKS |
644 EC_PREFS_REMOTECONTROLS |
645 EC_PREFS_KADEMLIA;
646 m_exchange_recv_selected_prefs =
647 m_exchange_send_selected_prefs |
648 EC_PREFS_CATEGORIES;
652 void CPreferencesRem::HandlePacket(const CECPacket *packet)
654 ((CEC_Prefs_Packet *)packet)->Apply();
656 if ( packet->GetTagByName(EC_TAG_PREFS_CATEGORIES) != 0 ) {
657 for (size_t i = 0; i < packet->GetTagByName(EC_TAG_PREFS_CATEGORIES)->GetTagCount(); i++) {
658 const CECTag *cat_tag = packet->GetTagByName(EC_TAG_PREFS_CATEGORIES)->GetTagByIndex(i);
659 Category_Struct *cat = new Category_Struct;
660 cat->title = cat_tag->GetTagByName(EC_TAG_CATEGORY_TITLE)->GetStringData();
661 cat->path = CPath(cat_tag->GetTagByName(EC_TAG_CATEGORY_PATH)->GetStringData());
662 cat->comment = cat_tag->GetTagByName(EC_TAG_CATEGORY_COMMENT)->GetStringData();
663 cat->color = cat_tag->GetTagByName(EC_TAG_CATEGORY_COLOR)->GetInt();
664 cat->prio = cat_tag->GetTagByName(EC_TAG_CATEGORY_PRIO)->GetInt();
665 theApp->glob_prefs->AddCat(cat);
667 } else {
668 Category_Struct *cat = new Category_Struct;
669 cat->title = _("All");
670 cat->color = 0;
671 cat->prio = PR_NORMAL;
672 theApp->glob_prefs->AddCat(cat);
674 wxECInitDoneEvent event;
675 theApp->AddPendingEvent(event);
680 bool CPreferencesRem::LoadRemote()
683 // override local settings with remote
684 CECPacket req(EC_OP_GET_PREFERENCES, EC_DETAIL_UPDATE);
686 // bring categories too
687 req.AddTag(CECTag(EC_TAG_SELECT_PREFS, m_exchange_recv_selected_prefs));
689 m_conn->SendRequest(this, &req);
691 return true;
695 void CPreferencesRem::SendToRemote()
697 CEC_Prefs_Packet pref_packet(m_exchange_send_selected_prefs, EC_DETAIL_UPDATE, EC_DETAIL_FULL);
698 m_conn->SendPacket(&pref_packet);
702 Category_Struct *CPreferencesRem::CreateCategory(
703 const wxString& name,
704 const CPath& path,
705 const wxString& comment,
706 uint32 color,
707 uint8 prio)
709 CECPacket req(EC_OP_CREATE_CATEGORY);
710 CEC_Category_Tag tag(0xffffffff, name, path.GetRaw(), comment, color, prio);
711 req.AddTag(tag);
712 m_conn->SendPacket(&req);
714 Category_Struct *category = new Category_Struct();
715 category->path = path;
716 category->title = name;
717 category->comment = comment;
718 category->color = color;
719 category->prio = prio;
721 AddCat(category);
723 return category;
727 void CPreferencesRem::UpdateCategory(
728 uint8 cat,
729 const wxString& name,
730 const CPath& path,
731 const wxString& comment,
732 uint32 color,
733 uint8 prio)
735 CECPacket req(EC_OP_UPDATE_CATEGORY);
736 CEC_Category_Tag tag(cat, name, path.GetRaw(), comment, color, prio);
737 req.AddTag(tag);
738 m_conn->SendPacket(&req);
740 Category_Struct *category = m_CatList[cat];
741 category->path = path;
742 category->title = name;
743 category->comment = comment;
744 category->color = color;
745 category->prio = prio;
749 void CPreferencesRem::RemoveCat(uint8 cat)
751 CECPacket req(EC_OP_DELETE_CATEGORY);
752 CEC_Category_Tag tag(cat, EC_DETAIL_CMD);
753 req.AddTag(tag);
754 m_conn->SendPacket(&req);
755 CPreferences::RemoveCat(cat);
760 // Container implementation
762 CServerConnectRem::CServerConnectRem(CRemoteConnect *conn)
764 m_CurrServer = 0;
765 m_Conn = conn;
769 void CServerConnectRem::ConnectToAnyServer()
771 CECPacket req(EC_OP_SERVER_CONNECT);
772 m_Conn->SendPacket(&req);
776 void CServerConnectRem::StopConnectionTry()
778 // lfroen: isn't Disconnect the same ?
782 void CServerConnectRem::Disconnect()
784 CECPacket req(EC_OP_SERVER_DISCONNECT);
785 m_Conn->SendPacket(&req);
789 void CServerConnectRem::ConnectToServer(CServer *server)
791 m_Conn->ConnectED2K(server->GetIP(), server->GetPort());
795 bool CServerConnectRem::ReQuery()
797 CECPacket stat_req(EC_OP_GET_CONNSTATE);
798 m_Conn->SendRequest(this, &stat_req);
800 return true;
804 void CServerConnectRem::HandlePacket(const CECPacket *packet)
806 CEC_ConnState_Tag *tag =
807 (CEC_ConnState_Tag *)packet->GetTagByName(EC_TAG_CONNSTATE);
808 if (!tag) {
809 return;
812 theApp->m_ConnState = 0;
813 CServer *server;
814 m_ID = tag->GetEd2kId();
815 theApp->m_clientID = tag->GetClientId();
817 if (tag->IsConnectedED2K()) {
818 CECTag *srvtag = tag->GetTagByName(EC_TAG_SERVER);
819 if (!srvtag) {
820 return;
822 server = theApp->serverlist->GetByID(srvtag->GetIPv4Data().IP());
823 if (m_CurrServer && (server != m_CurrServer)) {
824 theApp->amuledlg->m_serverwnd->serverlistctrl->
825 HighlightServer(m_CurrServer, false);
827 theApp->amuledlg->m_serverwnd->serverlistctrl->
828 HighlightServer(server, true);
829 m_CurrServer = server;
830 theApp->m_ConnState |= CONNECTED_ED2K;
831 } else {
832 if ( m_CurrServer ) {
833 theApp->amuledlg->m_serverwnd->serverlistctrl->
834 HighlightServer(m_CurrServer, false);
835 m_CurrServer = 0;
839 if (tag->IsConnectedKademlia()) {
840 if (tag->IsKadFirewalled()) {
841 theApp->m_ConnState |= CONNECTED_KAD_FIREWALLED;
842 } else {
843 theApp->m_ConnState |= CONNECTED_KAD_OK;
845 } else {
846 if (tag->IsKadRunning()) {
847 theApp->m_ConnState |= CONNECTED_KAD_NOT;
851 theApp->amuledlg->ShowConnectionState();
856 * Server list: host list of ed2k servers.
858 CServerListRem::CServerListRem(CRemoteConnect *conn)
860 CRemoteContainer<CServer, uint32, CEC_Server_Tag>(conn)
865 void CServerListRem::HandlePacket(const CECPacket *packet)
867 CRemoteContainer<CServer, uint32, CEC_Server_Tag>::HandlePacket(packet);
868 ReloadControl();
872 void CServerListRem::UpdateServerMetFromURL(wxString url)
874 CECPacket req(EC_OP_SERVER_UPDATE_FROM_URL);
875 req.AddTag(CECTag(EC_TAG_SERVERS_UPDATE_URL, url));
877 m_conn->SendPacket(&req);
881 void CServerListRem::SaveServerMet()
883 // lfroen: stub, nothing to do
887 void CServerListRem::FilterServers()
889 // FIXME: add code
890 //wxFAIL;
894 void CServerListRem::RemoveServer(CServer* server)
896 m_conn->RemoveServer(server->GetIP(),server->GetPort());
900 void CServerListRem::UpdateUserFileStatus(CServer *server)
902 if (server) {
903 m_TotalUser = server->GetUsers();
904 m_TotalFile = server->GetFiles();
906 wxString buffer =
907 CFormat(_("Total Users: %s | Total Files: %s")) % CastItoIShort(m_TotalUser) % CastItoIShort(m_TotalFile);
909 Notify_ShowUserCount(buffer);
914 CServer *CServerListRem::GetServerByAddress(const wxString& WXUNUSED(address), uint16 WXUNUSED(port)) const
916 // It's ok to return 0 for context where this code is used in remote gui
917 return 0;
920 CServer *CServerListRem::GetServerByIPTCP(uint32 WXUNUSED(nIP), uint16 WXUNUSED(nPort)) const
922 // It's ok to return 0 for context where this code is used in remote gui
923 return 0;
926 CServer *CServerListRem::CreateItem(CEC_Server_Tag *tag)
928 return new CServer(tag);
932 void CServerListRem::DeleteItem(CServer *in_srv)
934 CScopedPtr<CServer> srv(in_srv);
935 theApp->amuledlg->m_serverwnd->serverlistctrl->RemoveServer(srv.get());
939 uint32 CServerListRem::GetItemID(CServer *server)
941 return server->GetIP();
945 void CServerListRem::ProcessItemUpdate(CEC_Server_Tag *, CServer *)
947 // server list is always realoaded from scratch
948 wxFAIL;
952 void CServerListRem::ReloadControl()
954 for(uint32 i = 0;i < GetCount(); i++) {
955 CServer *srv = GetByIndex(i);
956 theApp->amuledlg->m_serverwnd->serverlistctrl->RefreshServer(srv);
961 CIPFilterRem::CIPFilterRem(CRemoteConnect* conn)
963 m_conn = conn;
967 void CIPFilterRem::Reload()
969 CECPacket req(EC_OP_IPFILTER_RELOAD);
970 m_conn->SendPacket(&req);
974 void CIPFilterRem::Update(wxString WXUNUSED(url))
976 // FIXME: add command
977 //wxFAIL;
982 * Shared files list
984 CSharedFilesRem::CSharedFilesRem(CRemoteConnect *conn) : CRemoteContainer<CKnownFile, CMD4Hash, CEC_SharedFile_Tag>(conn, true)
986 m_rename_file = NULL;
990 void CSharedFilesRem::Reload(bool, bool)
992 CECPacket req(EC_OP_SHAREDFILES_RELOAD);
994 m_conn->SendPacket(&req);
998 void CSharedFilesRem::AddFilesFromDirectory(const CPath& path)
1000 CECPacket req(EC_OP_SHAREDFILES_ADD_DIRECTORY);
1002 req.AddTag(CECTag(EC_TAG_PREFS_DIRECTORIES, path.GetRaw()));
1004 m_conn->SendPacket(&req);
1008 bool CSharedFilesRem::RenameFile(CKnownFile* file, const CPath& newName)
1010 // We use the printable name, as the filename originated from user input,
1011 // and the filesystem name might not be valid on the remote host.
1012 const wxString strNewName = newName.GetPrintable();
1014 CECPacket request(EC_OP_RENAME_FILE);
1015 request.AddTag(CECTag(EC_TAG_KNOWNFILE, file->GetFileHash()));
1016 request.AddTag(CECTag(EC_TAG_PARTFILE_NAME, strNewName));
1018 m_conn->SendRequest(this, &request);
1019 m_rename_file = file;
1020 m_new_name = strNewName;
1022 return true;
1026 void CSharedFilesRem::HandlePacket(const CECPacket *packet)
1028 if (m_rename_file && (packet->GetOpCode() == EC_OP_NOOP)) {
1029 m_rename_file->SetFileName(CPath(m_new_name));
1030 m_rename_file = NULL;
1031 } else if (packet->GetOpCode() != EC_OP_FAILED) {
1032 CRemoteContainer<CKnownFile, CMD4Hash, CEC_SharedFile_Tag>::HandlePacket(packet);
1037 CKnownFile *CSharedFilesRem::CreateItem(CEC_SharedFile_Tag *tag)
1039 CKnownFile *file = new CKnownFile(tag);
1041 m_enc_map[file->GetFileHash()] = RLE_Data(file->GetPartCount(), true);
1043 ProcessItemUpdate(tag, file);
1045 theApp->amuledlg->m_sharedfileswnd->sharedfilesctrl->ShowFile(file);
1047 return file;
1051 void CSharedFilesRem::DeleteItem(CKnownFile *in_file)
1053 CScopedPtr<CKnownFile> file(in_file);
1055 m_enc_map.erase(file->GetFileHash());
1057 theApp->amuledlg->m_sharedfileswnd->sharedfilesctrl->RemoveFile(file.get());
1061 CMD4Hash CSharedFilesRem::GetItemID(CKnownFile *file)
1063 return file->GetFileHash();
1067 void CSharedFilesRem::ProcessItemUpdate(CEC_SharedFile_Tag *tag, CKnownFile *file)
1069 CECTag *parttag = tag->GetTagByName(EC_TAG_PARTFILE_PART_STATUS);
1070 const unsigned char *data =
1071 m_enc_map[file->GetFileHash()].Decode(
1072 (unsigned char *)parttag->GetTagData(),
1073 parttag->GetTagDataLen());
1074 for(int i = 0; i < file->GetPartCount(); ++i) {
1075 file->m_AvailPartFrequency[i] = data[i];
1077 if (m_inc_tags) {
1078 tag->SetRequests(file->statistic.requested);
1079 tag->SetAllRequests(file->statistic.alltimerequested);
1080 tag->SetAccepts(file->statistic.accepted);
1081 tag->SetAllAccepts(file->statistic.alltimeaccepted);
1082 tag->SetXferred(file->statistic.transferred );
1083 tag->SetAllXferred(file->statistic.alltimetransferred);
1084 tag->SetPrio(file->m_iUpPriority);
1085 } else {
1086 file->statistic.requested = tag->GetRequests();
1087 file->statistic.alltimerequested = tag->GetAllRequests();
1088 file->statistic.accepted = tag->GetAccepts();
1089 file->statistic.alltimeaccepted = tag->GetAllAccepts();
1090 file->statistic.transferred = tag->GetXferred();
1091 file->statistic.alltimetransferred = tag->GetAllXferred();
1092 file->m_iUpPriority = tag->Prio();
1094 if (file->m_iUpPriority >= 10) {
1095 file->m_iUpPriority -= 10;
1096 file->m_bAutoUpPriority = true;
1097 } else {
1098 file->m_bAutoUpPriority = false;
1101 theApp->knownfiles->requested += file->statistic.requested;
1102 theApp->knownfiles->transferred += file->statistic.transferred;
1103 theApp->knownfiles->accepted += file->statistic.transferred;
1105 theApp->amuledlg->m_sharedfileswnd->sharedfilesctrl->UpdateItem(file);
1108 bool CSharedFilesRem::Phase1Done(const CECPacket *)
1110 theApp->knownfiles->requested = 0;
1111 theApp->knownfiles->transferred = 0;
1112 theApp->knownfiles->accepted = 0;
1114 return true;
1117 void CSharedFilesRem::SetFilePrio(CKnownFile *file, uint8 prio)
1119 CECPacket req(EC_OP_SHARED_SET_PRIO);
1121 CECTag hashtag(EC_TAG_PARTFILE, file->GetFileHash());
1122 hashtag.AddTag(CECTag(EC_TAG_PARTFILE_PRIO, prio));
1124 req.AddTag(hashtag);
1126 m_conn->SendPacket(&req);
1130 * List of uploading and waiting clients.
1132 CUpDownClientListRem::CUpDownClientListRem(CRemoteConnect *conn, int viewtype)
1134 CRemoteContainer<CUpDownClient, uint32, CEC_UpDownClient_Tag>(conn)
1136 m_viewtype = viewtype;
1140 CUpDownClient::CUpDownClient(CEC_UpDownClient_Tag *tag)
1142 m_bRemoteQueueFull = false;
1143 m_nUserIDHybrid = tag->ID();
1144 m_Username = tag->ClientName();
1145 m_score = tag->Score();
1146 m_clientSoft = tag->ClientSoftware();
1147 m_clientVersionString = GetSoftName(m_clientSoft);
1148 m_clientSoftString = m_clientVersionString;
1149 m_identState = tag->GetCurrentIdentState();
1150 m_hasbeenobfuscatinglately = tag->HasObfuscatedConnection();
1152 // The functions to retrieve m_clientVerString information are
1153 // currently in BaseClient.cpp, which is not linked in remote-gui app.
1154 // So, in the meantime, we use a tag sent from core.
1155 m_clientVerString = tag->SoftVerStr();
1156 m_strModVersion = wxEmptyString;
1157 wxString clientModString;
1158 if (!clientModString.IsEmpty()) {
1159 m_clientVerString += wxT(" - ") + clientModString;
1161 m_fullClientVerString = m_clientSoftString + wxT(" ") + m_clientVerString;
1163 // User hash
1164 m_UserHash = tag->UserID();
1166 // User IP:Port
1167 m_nConnectIP = m_dwUserIP = tag->UserIP();
1168 m_nUserPort = tag->UserPort();
1169 m_FullUserIP = m_nConnectIP;
1171 // Server IP:Port
1172 m_dwServerIP = tag->ServerIP();
1173 m_nServerPort = tag->ServerPort();
1174 m_ServerName = tag->ServerName();
1176 m_waitingPosition = tag->WaitingPosition();
1178 m_Friend = 0;
1179 if (tag->HaveFile()) {
1180 CMD4Hash filehash = tag->FileID();
1181 m_uploadingfile = theApp->sharedfiles->GetByID(filehash);
1182 if (!m_uploadingfile) {
1183 m_uploadingfile = theApp->downloadqueue->GetByID(filehash);
1185 } else {
1186 m_uploadingfile = NULL;
1189 m_nCurSessionUp = 0;
1191 credits = new CClientCredits(new CreditStruct());
1194 uint16 CUpQueueRem::GetWaitingPosition(const CUpDownClient *client) const
1196 return client->GetWaitingPosition();
1199 /* Warning: do common base */
1202 bool CUpDownClient::IsIdentified() const
1204 return m_identState == IS_IDENTIFIED;
1208 bool CUpDownClient::IsBadGuy() const
1210 return m_identState == IS_IDBADGUY;
1214 bool CUpDownClient::SUIFailed() const
1216 return m_identState == IS_IDFAILED;
1220 bool CUpDownClient::SUINeeded() const
1222 return m_identState == IS_IDNEEDED;
1226 bool CUpDownClient::SUINotSupported() const
1228 return m_identState == IS_NOTAVAILABLE;
1232 uint64 CUpDownClient::GetDownloadedTotal() const
1234 return credits->GetDownloadedTotal();
1238 uint64 CUpDownClient::GetUploadedTotal() const
1240 return credits->GetUploadedTotal();
1244 double CUpDownClient::GetScoreRatio() const
1246 return credits->GetScoreRatio(GetIP(), theApp->CryptoAvailable());
1249 /* End Warning */
1252 CUpDownClient::~CUpDownClient()
1254 delete credits;
1258 CUpDownClient *CUpDownClientListRem::CreateItem(CEC_UpDownClient_Tag *tag)
1260 CUpDownClient *client = new CUpDownClient(tag);
1261 ProcessItemUpdate(tag, client);
1263 theApp->amuledlg->m_transferwnd->clientlistctrl->InsertClient(client, (ViewType)m_viewtype);
1265 return client;
1269 void CUpDownClientListRem::DeleteItem(CUpDownClient *client)
1271 theApp->amuledlg->m_transferwnd->clientlistctrl->
1272 RemoveClient(client, (ViewType)m_viewtype);
1273 delete client;
1277 uint32 CUpDownClientListRem::GetItemID(CUpDownClient *client)
1279 return client->GetUserIDHybrid();
1283 void CUpDownClientListRem::ProcessItemUpdate(
1284 CEC_UpDownClient_Tag *tag,
1285 CUpDownClient *client)
1287 uint16 state = tag->ClientState();
1289 client->m_nDownloadState = state & 0xff;
1290 client->m_nUploadState = (state >> 8) & 0xff;
1292 client->m_nUpDatarate = tag->SpeedUp();
1293 if ( client->m_nDownloadState == DS_DOWNLOADING ) {
1294 client->kBpsDown = tag->SpeedDown() / 1024.0;
1295 } else {
1296 client->kBpsDown = 0;
1299 client->m_WaitTime = tag->WaitTime();
1300 client->m_UpStartTimeDelay = tag->XferTime();
1301 client->m_dwLastUpRequest = tag->LastReqTime();
1302 client->m_WaitStartTime = tag->QueueTime();
1304 CreditStruct *credit_struct =
1305 (CreditStruct *)client->credits->GetDataStruct();
1306 credit_struct->uploaded = tag->XferUp();
1307 client->m_nTransferredUp = tag->XferUpSession();
1309 credit_struct->downloaded = tag->XferDown();
1310 client->m_nTransferredDown = tag->XferDownSession();
1312 client->m_score = tag->Score();
1313 client->m_rating = tag->Rating();
1317 CUpQueueRem::CUpQueueRem(CRemoteConnect *conn)
1319 m_up_list(conn, vtUploading), m_wait_list(conn, vtQueued)
1325 * Download queue container: hold PartFiles with progress status
1330 CDownQueueRem::CDownQueueRem(CRemoteConnect *conn)
1332 CRemoteContainer<CPartFile, CMD4Hash, CEC_PartFile_Tag>(conn, true)
1337 bool CDownQueueRem::AddLink(const wxString &link, int)
1339 CECPacket req(EC_OP_ADD_LINK);
1340 req.AddTag(CECTag(EC_TAG_STRING, link));
1342 m_conn->SendPacket(&req);
1343 return true;
1347 void CDownQueueRem::StopUDPRequests()
1349 // have no idea what is it about
1353 void CDownQueueRem::ResetCatParts(int)
1355 // called when category being deleted. Command will be performed on remote side
1359 bool CDownQueueRem::IsPartFile(const CKnownFile *) const
1361 // hope i understand it right
1362 return true;
1366 void CDownQueueRem::OnConnectionState(bool)
1371 CPartFile *CDownQueueRem::CreateItem(CEC_PartFile_Tag *tag)
1373 CPartFile *file = new CPartFile(tag);
1374 m_enc_map[file->GetFileHash()] = PartFileEncoderData(file->GetPartCount(), 10);
1375 ProcessItemUpdate(tag, file);
1377 theApp->amuledlg->m_transferwnd->downloadlistctrl->AddFile(file);
1378 return file;
1382 void CDownQueueRem::DeleteItem(CPartFile *in_file)
1384 CScopedPtr<CPartFile> file(in_file);
1386 theApp->amuledlg->m_transferwnd->downloadlistctrl->RemoveFile(file.get());
1388 m_enc_map.erase(file->GetFileHash());
1392 CMD4Hash CDownQueueRem::GetItemID(CPartFile *file)
1394 return file->GetFileHash();
1398 void CDownQueueRem::ProcessItemUpdate(CEC_PartFile_Tag *tag, CPartFile *file)
1401 // update status
1403 tag->Speed(&file->m_kbpsDown);
1404 file->kBpsDown = file->m_kbpsDown / 1024.0;
1406 tag->SizeXfer(&file->transferred);
1407 tag->SizeDone(&file->completedsize);
1408 tag->SourceXferCount(&file->transferingsrc);
1409 tag->SourceNotCurrCount(&file->m_notCurrentSources);
1410 tag->SourceCount(&file->m_source_count);
1411 tag->SourceCountA4AF(&file->m_a4af_source_count);
1412 tag->FileStatus(&file->status);
1413 tag->Stopped(&file->m_stopped);
1415 tag->LastSeenComplete(&file->lastseencomplete);
1416 tag->LastDateChanged(&file->m_lastDateChanged);
1417 tag->DownloadActiveTime(&file->m_nDlActiveTime);
1419 tag->GetLostDueToCorruption(&file->m_iLostDueToCorruption);
1420 tag->GetGainDueToCompression(&file->m_iGainDueToCompression);
1421 tag->TotalPacketsSavedDueToICH(&file->m_iTotalPacketsSavedDueToICH);
1423 tag->FileCat(&file->m_category);
1425 tag->Prio(&file->m_iDownPriorityEC);
1426 if ( file->m_iDownPriorityEC >= 10 ) {
1427 file->m_iDownPriority = file->m_iDownPriorityEC - 10;
1428 file->m_bAutoDownPriority = true;
1429 } else {
1430 file->m_iDownPriority = file->m_iDownPriorityEC;
1431 file->m_bAutoDownPriority = false;
1434 file->percentcompleted = (100.0*file->GetCompletedSize()) / file->GetFileSize();
1437 // Copy part/gap status
1439 CECTag *gaptag = tag->GetTagByName(EC_TAG_PARTFILE_GAP_STATUS);
1440 CECTag *parttag = tag->GetTagByName(EC_TAG_PARTFILE_PART_STATUS);
1441 CECTag *reqtag = tag->GetTagByName(EC_TAG_PARTFILE_REQ_STATUS);
1442 if (gaptag && parttag && reqtag) {
1443 wxASSERT(m_enc_map.count(file->GetFileHash()));
1445 PartFileEncoderData &encoder = m_enc_map[file->GetFileHash()];
1446 encoder.Decode(
1447 (unsigned char *)gaptag->GetTagData(), gaptag->GetTagDataLen(),
1448 (unsigned char *)parttag->GetTagData(), parttag->GetTagDataLen());
1450 const uint64 *reqparts = (const uint64 *)reqtag->GetTagData();
1451 unsigned reqcount = reqtag->GetTagDataLen() / (2 * sizeof(uint64));
1453 unsigned gap_size = encoder.m_gap_status.Size() / (2 * sizeof(uint64));
1454 // clear gaplist
1455 file->m_gaplist.Init(file->GetFileSize(), false);
1457 // and refill it
1458 const uint64 *gap_info = (const uint64 *)encoder.m_gap_status.Buffer();
1459 for (unsigned j = 0; j < gap_size;j++) {
1460 file->m_gaplist.AddGap(ENDIAN_NTOHLL(gap_info[2*j]), ENDIAN_NTOHLL(gap_info[2*j+1]));
1463 // adjust size of requested block list
1464 while ( file->m_requestedblocks_list.size() > reqcount ) {
1465 delete file->m_requestedblocks_list.front();
1466 file->m_requestedblocks_list.pop_front();
1468 while ( file->m_requestedblocks_list.size() != reqcount ) {
1469 file->m_requestedblocks_list.push_front(new Requested_Block_Struct);
1472 std::list<Requested_Block_Struct*>::iterator it2 = file->m_requestedblocks_list.begin();
1473 for (unsigned i = 0; i < reqcount; ++i) {
1474 Requested_Block_Struct* block = *it2++;
1475 block->StartOffset = ENDIAN_NTOHLL(reqparts[2*i]);
1476 block->EndOffset = ENDIAN_NTOHLL(reqparts[2*i+1]);
1478 // copy parts frequency
1479 const unsigned char *part_info = encoder.m_part_status.Buffer();
1480 for(int i = 0; i < file->GetPartCount(); ++i) {
1481 file->m_SrcpartFrequency[i] = part_info[i];
1483 } else {
1484 AddLogLineNS(CFormat(wxT("ERROR: %X %X %X")) % (size_t)gaptag % (size_t)parttag % (size_t)reqtag);
1487 // Get source names
1488 CECTag *srcnametag = tag->GetTagByName(EC_TAG_PARTFILE_SOURCE_NAMES);
1489 if (srcnametag) {
1490 file->ClearSourcenameItemList();
1491 int max = srcnametag->GetTagCount();
1492 for (int i = 0; i < max - 1; ) {
1493 wxString name = srcnametag->GetTagByIndex(i++)->GetStringData();
1494 long count = srcnametag->GetTagByIndex(i++)->GetInt();
1495 file->AddSourcenameItemList(name, count);
1499 // Get comments
1500 CECTag *commenttag = tag->GetTagByName(EC_TAG_PARTFILE_COMMENTS);
1501 if (commenttag) {
1502 file->ClearFileRatingList();
1503 int max = commenttag->GetTagCount();
1504 for (int i = 0; i < max - 3; ) {
1505 wxString u = commenttag->GetTagByIndex(i++)->GetStringData();
1506 wxString f = commenttag->GetTagByIndex(i++)->GetStringData();
1507 int r = commenttag->GetTagByIndex(i++)->GetInt();
1508 wxString c = commenttag->GetTagByIndex(i++)->GetStringData();
1509 file->AddFileRatingList(u, f, r, c);
1511 file->UpdateFileRatingCommentAvail();
1514 theApp->amuledlg->m_transferwnd->downloadlistctrl->UpdateItem(file);
1518 bool CDownQueueRem::Phase1Done(const CECPacket *)
1520 return true;
1524 void CDownQueueRem::SendFileCommand(CPartFile *file, ec_tagname_t cmd)
1526 CECPacket req(cmd);
1527 req.AddTag(CECTag(EC_TAG_PARTFILE, file->GetFileHash()));
1529 m_conn->SendPacket(&req);
1533 void CDownQueueRem::Prio(CPartFile *file, uint8 prio)
1535 CECPacket req(EC_OP_PARTFILE_PRIO_SET);
1537 CECTag hashtag(EC_TAG_PARTFILE, file->GetFileHash());
1538 hashtag.AddTag(CECTag(EC_TAG_PARTFILE_PRIO, prio));
1539 req.AddTag(hashtag);
1541 m_conn->SendPacket(&req);
1545 void CDownQueueRem::AutoPrio(CPartFile *file, bool flag)
1547 CECPacket req(EC_OP_PARTFILE_PRIO_SET);
1549 CECTag hashtag(EC_TAG_PARTFILE, file->GetFileHash());
1551 hashtag.AddTag(CECTag(EC_TAG_PARTFILE_PRIO,
1552 (uint8)(flag ? PR_AUTO : file->GetDownPriority())));
1553 req.AddTag(hashtag);
1555 m_conn->SendPacket(&req);
1559 void CDownQueueRem::Category(CPartFile *file, uint8 cat)
1561 CECPacket req(EC_OP_PARTFILE_SET_CAT);
1562 file->m_category = cat;
1564 CECTag hashtag(EC_TAG_PARTFILE, file->GetFileHash());
1565 hashtag.AddTag(CECTag(EC_TAG_PARTFILE_CAT, cat));
1566 req.AddTag(hashtag);
1568 m_conn->SendPacket(&req);
1572 void CDownQueueRem::AddSearchToDownload(CSearchFile* file, uint8 category)
1574 CECPacket req(EC_OP_DOWNLOAD_SEARCH_RESULT);
1575 CECTag hashtag(EC_TAG_PARTFILE, file->GetFileHash());
1576 hashtag.AddTag(CECTag(EC_TAG_PARTFILE_CAT, category));
1577 req.AddTag(hashtag);
1579 m_conn->SendPacket(&req);
1583 CClientListRem::CClientListRem(CRemoteConnect *conn)
1585 m_conn = conn;
1589 void CClientListRem::FilterQueues()
1591 // FIXME: add code
1592 //wxFAIL;
1596 CSearchListRem::CSearchListRem(CRemoteConnect *conn) : CRemoteContainer<CSearchFile, CMD4Hash, CEC_SearchFile_Tag>(conn)
1598 m_curr_search = -1;
1602 wxString CSearchListRem::StartNewSearch(
1603 uint32* nSearchID, SearchType search_type,
1604 const CSearchList::CSearchParams& params)
1606 CECPacket search_req(EC_OP_SEARCH_START);
1607 EC_SEARCH_TYPE ec_search_type = EC_SEARCH_LOCAL;
1608 switch(search_type) {
1609 case LocalSearch: ec_search_type = EC_SEARCH_LOCAL; break;
1610 case GlobalSearch: ec_search_type = EC_SEARCH_GLOBAL; break;
1611 case KadSearch: ec_search_type = EC_SEARCH_KAD; break;
1613 search_req.AddTag(
1614 CEC_Search_Tag(params.searchString, ec_search_type,
1615 params.typeText, params.extension, params.availability,
1616 params.minSize, params.maxSize));
1618 m_conn->SendPacket(&search_req);
1619 m_curr_search = *(nSearchID); // No kad remote search yet.
1621 Flush();
1623 return wxEmptyString; // EC reply will have the error mesg is needed.
1627 void CSearchListRem::StopGlobalSearch()
1629 if (m_curr_search != -1) {
1630 CECPacket search_req(EC_OP_SEARCH_STOP);
1631 m_conn->SendPacket(&search_req);
1636 void CSearchListRem::HandlePacket(const CECPacket *packet)
1638 if ( packet->GetOpCode() == EC_OP_SEARCH_PROGRESS ) {
1639 CoreNotify_Search_Update_Progress(packet->GetTagByIndex(0)->GetInt());
1640 } else {
1641 CRemoteContainer<CSearchFile, CMD4Hash, CEC_SearchFile_Tag>::HandlePacket(packet);
1646 CSearchFile::CSearchFile(CEC_SearchFile_Tag *tag)
1648 m_parent(NULL),
1649 m_showChildren(false),
1650 m_sourceCount(0),
1651 m_completeSourceCount(0),
1652 m_kademlia(false),
1653 m_clientID(0),
1654 m_clientPort(0)
1656 SetFileName(CPath(tag->FileName()));
1657 m_abyFileHash = tag->ID();
1658 SetFileSize(tag->SizeFull());
1660 m_searchID = theApp->searchlist->m_curr_search;
1665 // dtor is virtual - must be implemented
1666 CSearchFile::~CSearchFile()
1671 CSearchFile *CSearchListRem::CreateItem(CEC_SearchFile_Tag *tag)
1673 CSearchFile *file = new CSearchFile(tag);
1674 ProcessItemUpdate(tag, file);
1676 theApp->amuledlg->m_searchwnd->AddResult(file);
1678 return file;
1682 void CSearchListRem::DeleteItem(CSearchFile *file)
1684 delete file;
1688 CMD4Hash CSearchListRem::GetItemID(CSearchFile *file)
1690 return file->GetFileHash();
1694 void CSearchListRem::ProcessItemUpdate(CEC_SearchFile_Tag *tag, CSearchFile *file)
1696 file->m_sourceCount = tag->SourceCount();
1697 file->m_completeSourceCount = tag->CompleteSourceCount();
1701 bool CSearchListRem::Phase1Done(const CECPacket *WXUNUSED(reply))
1703 CECPacket progress_req(EC_OP_SEARCH_PROGRESS);
1704 m_conn->SendRequest(this, &progress_req);
1706 return true;
1710 void CSearchListRem::RemoveResults(long nSearchID)
1712 ResultMap::iterator it = m_results.find(nSearchID);
1713 if (it != m_results.end()) {
1714 CSearchResultList& list = it->second;
1715 for (unsigned int i = 0; i < list.size(); ++i) {
1716 delete list[i];
1718 m_results.erase(it);
1723 const CSearchResultList& CSearchListRem::GetSearchResults(long nSearchID)
1725 ResultMap::const_iterator it = m_results.find(nSearchID);
1726 if (it != m_results.end()) {
1727 return it->second;
1730 // TODO: Should we assert in this case?
1731 static CSearchResultList list;
1732 return list;
1736 void CStatsUpdaterRem::HandlePacket(const CECPacket *packet)
1738 theStats::UpdateStats(packet);
1739 theApp->ShowUserCount(); // maybe there should be a check if a usercount changed ?
1743 bool CUpDownClient::IsBanned() const
1745 // FIXME: add code
1746 return false;
1751 // Those functions have different implementation in remote gui
1753 void CUpDownClient::Ban()
1755 // FIXME: add code
1756 wxFAIL;
1760 void CUpDownClient::UnBan()
1762 // FIXME: add code
1763 wxFAIL;
1767 void CUpDownClient::RequestSharedFileList()
1769 // FIXME: add code
1770 wxFAIL;
1774 void CKnownFile::SetFileComment(const wxString &)
1776 // FIXME: add code
1777 wxMessageBox(_("Comments and ratings are not supported on remote gui yet"), _("Information"), wxOK | wxICON_INFORMATION);
1781 void CKnownFile::SetFileRating(unsigned char)
1783 // FIXME: add code
1787 // I don't think it will be implemented - too match data transfer. But who knows ?
1788 wxString CUpDownClient::ShowDownloadingParts() const
1790 return wxEmptyString;
1794 bool CUpDownClient::SwapToAnotherFile(
1795 bool WXUNUSED(bIgnoreNoNeeded),
1796 bool WXUNUSED(ignoreSuspensions),
1797 bool WXUNUSED(bRemoveCompletely),
1798 CPartFile* WXUNUSED(toFile))
1800 // FIXME: add code
1801 wxFAIL;
1802 return false;
1807 // Those functions are virtual. So even they don't get called they must
1808 // be defined so linker will be happy
1810 CPacket* CKnownFile::CreateSrcInfoPacket(const CUpDownClient *, uint8 /*byRequestedVersion*/, uint16 /*nRequestedOptions*/)
1812 wxFAIL;
1813 return 0;
1817 bool CKnownFile::LoadFromFile(const class CFileDataIO*)
1819 wxFAIL;
1820 return false;
1824 void CKnownFile::UpdatePartsInfo()
1826 wxFAIL;
1830 CPacket* CPartFile::CreateSrcInfoPacket(CUpDownClient const *, uint8 /*byRequestedVersion*/, uint16 /*nRequestedOptions*/)
1832 wxFAIL;
1833 return 0;
1837 void CPartFile::UpdatePartsInfo()
1839 wxFAIL;
1843 void CPartFile::UpdateFileRatingCommentAvail()
1845 bool prevComment = m_hasComment;
1846 int prevRating = m_iUserRating;
1848 m_hasComment = false;
1849 m_iUserRating = 0;
1850 int ratingCount = 0;
1852 FileRatingList::iterator it = m_FileRatingList.begin();
1853 for (; it != m_FileRatingList.end(); ++it) {
1854 SFileRating& cur_rat = *it;
1856 if (!cur_rat.Comment.IsEmpty()) {
1857 m_hasComment = true;
1860 uint8 rating = cur_rat.Rating;
1861 if (rating) {
1862 wxASSERT(rating <= 5);
1864 ratingCount++;
1865 m_iUserRating += rating;
1869 if (ratingCount) {
1870 m_iUserRating /= ratingCount;
1871 wxASSERT(m_iUserRating > 0 && m_iUserRating <= 5);
1874 if ((prevComment != m_hasComment) || (prevRating != m_iUserRating)) {
1875 UpdateDisplayedInfo();
1879 bool CPartFile::SavePartFile(bool)
1881 wxFAIL;
1882 return false;
1887 // since gui is not linked with amule.cpp - define events here
1889 DEFINE_LOCAL_EVENT_TYPE(wxEVT_CORE_FINISHED_HTTP_DOWNLOAD)
1890 DEFINE_LOCAL_EVENT_TYPE(wxEVT_CORE_SOURCE_DNS_DONE)
1891 DEFINE_LOCAL_EVENT_TYPE(wxEVT_CORE_UDP_DNS_DONE)
1892 DEFINE_LOCAL_EVENT_TYPE(wxEVT_CORE_SERVER_DNS_DONE)
1893 // File_checked_for_headers