bool TorrentManager::AddTorrent(QString& path, QString& save_path, error_code& ec, QString name, QMap<QString, quint8> filePriorities, QString group, AddTorrentFlags flags)

{
	boost::intrusive_ptr<torrent_info> t;
	t = new torrent_info(path.toUtf8().data(), ec);

	if (ec != 0)
	{
		return false;
	}

	add_torrent_params p;
	QString dataDir = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
	QString infoHash = QString::fromStdString(to_hex(t->info_hash().to_string()));
	std::string resumeFileName = StaticHelpers::CombinePathes(dataDir, "BtSessionData", infoHash + ".resume").toStdString();
	std::vector<char> buf;
	bool isPreviousSeed = false;

	if (load_file(resumeFileName.c_str(), buf, ec) == 0)
	{
#if LIBTORRENT_VERSION_NUM >= 10000
		p.resume_data = buf;
#else
		p.resume_data = &buf;
#endif
		entry e = bdecode(buf.begin(), buf.end());

		if (entry* i = e.find_key("torrent_name"))
		{
			std::string stdName = i->string();
			name = QString::fromUtf8(stdName.c_str());
		}

		if (entry* i = e.find_key("torrent_group"))
		{
			std::string string = i->string();
			group = QString::fromUtf8(string.c_str());
		}

		if (entry* i = e.find_key("save_path"))
		{
			save_path = QString::fromUtf8(i->string().c_str());
		}

		if (entry* i = e.find_key("is_previous_seed"))
		{
			isPreviousSeed = (i->integer() == 1);
		}
	}

	if (!filePriorities.isEmpty())
	{
		std::vector<uint8_t> filepriorities;
		file_storage storrage = t->files();
		int filesCount = storrage.num_files();

		for (int i = 0; i < filesCount; i++)
		{
			file_entry file = storrage.at(i);
			QString filePath = QDir::toNativeSeparators(file.path.c_str());

			if (filePriorities.contains(filePath))
			{
				filepriorities.push_back(filePriorities[filePath]);
			}
			else
			{
				filepriorities.push_back(1);
			}
		}

#if LIBTORRENT_VERSION_NUM >= 10000
		p.file_priorities = filepriorities;
#else
		p.file_priorities = &filepriorities;
#endif
	}

	if (!name.isEmpty())
	{
		p.name = name.toUtf8().data();
		file_storage fs = t->files();
		fs.set_name(p.name);
		t->remap_files(fs);
	}

	p.ti = t;
	p.save_path = std::string(save_path.toUtf8().data());
	p.storage_mode = storage_mode_t(m_pTorrentSessionSettings->valueInt("Torrent", "file_allocation_mode", storage_mode_sparse));
	
	p.flags = add_torrent_params::flag_duplicate_is_error | add_torrent_params::flag_update_subscribe;
	if (flags.testFlag(PAUSED_MODE))
	{
		p.flags |= add_torrent_params::flag_paused;
	}
	if (flags.testFlag(SEED_MODE))
	{
		p.flags |= add_torrent_params::flag_seed_mode;
	}
	if (flags.testFlag(SUPER_SEED_MODE))
	{
		p.flags |= add_torrent_params::flag_super_seeding;
	}
#if LIBTORRENT_VERSION_NUM >= 10000

	if (flags.testFlag(SEQUENTIAL_MODE))
	{
		p.flags |= add_torrent_params::flag_sequential_download;
	}
	
#else
	p.flags |= add_torrent_params::flag_paused;
#endif
	p.userdata = static_cast<void*>(strdup(path.toLatin1().data()));
	torrent_handle h = m_pTorrentSession->add_torrent(p, ec);

	if (ec || !h.is_valid())
	{
		//	QMessageBox::warning(0,"Error",ec.message().c_str());
		return false;
	}

#if LIBTORRENT_VERSION_NUM < 10000
	if (flags.testFlag(SEQUENTIAL_MODE))
	{
		h.set_sequential_download(true);
	}
	h.resume();	
#endif
	Torrent* current = new Torrent(h.status(), group);
	current->setIsPrevioslySeeded(isPreviousSeed);
	m_pTorrentStorrage->append(current);
	emit AddTorrentGui(current);
	h.set_max_connections(max_connections_per_torrent);
	QFile::copy(path, StaticHelpers::CombinePathes(dataDir, "BtSessionData", infoHash + ".torrent"));

	return true;
}
void TorrentManager::handle_alert(alert* a)
{
	QString dataDir = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
	TORRENT_TRY
	{
		switch (a->type())
		{
			case tracker_reply_alert::alert_type:
			{
				tracker_reply_alert* p = alert_cast<tracker_reply_alert>(a);
				Torrent* pTorrent = m_pTorrentStorrage->getTorrent(QString::fromStdString(to_hex(p->handle.info_hash().to_string())));

				if (pTorrent != NULL)
				{
					pTorrent->SetTrackerPeersCnt(QString::fromStdString(p->url), p->num_peers);
				}

				break;
			}

			case file_error_alert::alert_type:
			{
				file_error_alert* p = alert_cast<file_error_alert>(a);
				QString message = StaticHelpers::translateLibTorrentError(p->error);
				message.append(QString::fromUtf8(p->message().c_str()));
				emit Notify(NotificationSystem::DISK_ERROR, message, QVariant());
				break;
			}

			case torrent_finished_alert::alert_type:
			{
				torrent_finished_alert* p = alert_cast<torrent_finished_alert>(a);
				p->handle.set_max_connections(max_connections_per_torrent / 2);
				torrent_handle h = p->handle;
				QString infoHash = QString::fromStdString(to_hex(h.info_hash().to_string()));
				Torrent* pTorrent = m_pTorrentStorrage->getTorrent(infoHash);

				if (pTorrent != NULL)
				{
					if (pTorrent->isSquential())
					{
						pTorrent->seqensialDownload();
					}

					if (!pTorrent->isPrevioslySeeded())
					{
						emit Notify(NotificationSystem::TORRENT_COMPLETED, tr("TORRENT_COMPLETED %1").arg(pTorrent->GetName()), StaticHelpers::CombinePathes(pTorrent->GetSavePath(), pTorrent->GetName()));
					}
				}

				h.save_resume_data();
				break;
			}

			case save_resume_data_failed_alert::alert_type:
			{
				save_resume_data_failed_alert* p = alert_cast<save_resume_data_failed_alert>(a);
				p->handle.save_resume_data();
				break;
			}

			case save_resume_data_alert::alert_type:
			{
				save_resume_data_alert* p = alert_cast<save_resume_data_alert>(a);
				torrent_handle h = p->handle;

				if (p->resume_data)
				{
					std::vector<char> out;
					entry e = *p->resume_data;
					QString info_hash = QString::fromStdString(to_hex(h.info_hash().to_string()));
					Torrent* torrent = m_pTorrentStorrage->getTorrent(info_hash);

					if (torrent != NULL)
					{
						bool isSeed = torrent->isSeeding();
						e["torrent_group"] = torrent->GetGroup().toUtf8().data();
						e["torrent_name"] =
#if LIBTORRENT_VERSION_NUM >= 10000
						    h.status(torrent_handle::query_name).name;
#else
						    h.name();
#endif
						e["is_previous_seed"] = isSeed ? 1 : 0;
						torrent->setIsPrevioslySeeded(isSeed);
					}

					bencode(back_inserter(out), e);
					save_file(StaticHelpers::CombinePathes(dataDir, "BtSessionData", info_hash + ".resume").toStdString(), out);

					if (m_bIsSaveSessionInitiated)
					{
						num_outstanding_resume_data--;
					}
				}

				break;
			}

			case tracker_error_alert::alert_type:
			{
				tracker_error_alert* p = alert_cast<tracker_error_alert>(a);
				QString message = StaticHelpers::translateLibTorrentError(p->error);
				message.append(QString::fromLocal8Bit(p->message().c_str()));
				emit Notify(NotificationSystem::TRACKER_ERROR, message, QVariant());
				break;
			}

			case storage_moved_alert::alert_type:
			{
				storage_moved_alert* p = alert_cast<storage_moved_alert>(a);
				torrent_handle h = p->handle;

				if (h.is_valid())
				{
					h.save_resume_data();
				}

				QString infoHash = QString::fromStdString(to_hex(h.info_hash().to_string()));
				Torrent* pTorrent = m_pTorrentStorrage->getTorrent(infoHash);

				if (pTorrent != NULL)
				{
					emit Notify(NotificationSystem::TORRENT_INFO, tr("MOVE_STORRAGE_COMPLETED_TO:\n%1 %2").arg(pTorrent->GetName(), pTorrent->GetSavePath()), pTorrent->GetSavePath());
					pTorrent->CompliteMoveStorrage();
				}

				break;
			}

			case fastresume_rejected_alert::alert_type:
			{
				fastresume_rejected_alert* p = alert_cast<fastresume_rejected_alert>(a);
				torrent_handle h = p->handle;
				h.auto_managed(false);
				h.pause();
				emit Notify(NotificationSystem::TORRENT_ERROR, StaticHelpers::translateLibTorrentError(p->error), QVariant());
				break;
			}

			case metadata_received_alert::alert_type:
			{
				metadata_received_alert* p = alert_cast<metadata_received_alert>(a);
				torrent_handle h = p->handle;

				if (h.is_valid())
				{
					try
					{
#if LIBTORRENT_VERSION_NUM >= 10000
						boost::intrusive_ptr<torrent_info const> ti = h.torrent_file();

						if (ti != NULL)
						{
							create_torrent ct(*ti.get());
							QString info_hash = QString::fromStdString(to_hex(ti->info_hash().to_string()));
#else
						const torrent_info ti = h.get_torrent_info();
						{
							create_torrent ct(ti);
							QString info_hash = QString::fromStdString(to_hex(ti.info_hash().to_string()));
#endif
							std::ofstream out(StaticHelpers::CombinePathes(dataDir, "BtSessionData", info_hash + ".torrent").toStdString(), std::ios_base::binary);
							bencode(std::ostream_iterator<char>(out), ct.generate());
						}
					}
					catch (...)
					{
						qCritical() << "Exception in metadata_received_alert";
					}
				}

				break;
			}

			case portmap_alert::alert_type:
			{
				portmap_alert* alert = alert_cast<portmap_alert>(a);
				emit Notify(NotificationSystem::SYSTEM_ERROR, QString::fromUtf8(alert->message().c_str()), QVariant());
			}

			case state_update_alert::alert_type:
			{
				state_update_alert* p = alert_cast<state_update_alert>(a);
				for (int i = 0; i < p->status.size(); i++)
				{
					torrent_status status = p->status[i];
					QString infoHash = QString::fromStdString(to_hex(status.info_hash.to_string()));
					Torrent* torrent = m_pTorrentStorrage->getTorrent(infoHash);
					if (torrent != NULL)
					{
						torrent->UpdateStatus(status);
					}
					
				}
				break;
			}

			case performance_alert::alert_type:

			/*{
				performance_alert* p=alert_cast<performance_alert>(a);
				session_settings settings = ses->settings();
				switch (p->warning_code)
				{
				case performance_alert::outstanding_disk_buffer_limit_reached:
				{

				settings.max_queued_disk_bytes+=settings.max_queued_disk_bytes/4;
				break;
				}
				case performance_alert::outstanding_request_limit_reached:
				{

				settings.max_out_request_queue+=settings.max_out_request_queue/4;
				break;
				}
				case performance_alert::upload_limit_too_low:
				{

				settings.upload_rate_limit+=settings.upload_rate_limit*5/100;
				break;
				}
				case performance_alert::download_limit_too_low:
				{

				settings.download_rate_limit+=settings.download_rate_limit*5/100;
				break;
				}
				case performance_alert::send_buffer_watermark_too_low:
				{

				settings.send_buffer_watermark+=settings.send_buffer_watermark/4;
				break;
				}
				case performance_alert::too_many_optimistic_unchoke_slots:
				{

				settings.unchoke_slots_limit+= settings.unchoke_slots_limit/4;
				break;
				}
				case performance_alert::too_high_disk_queue_limit:
				{


				if (settings.max_queued_disk_bytes-settings.max_queued_disk_bytes/4 < 16*KbInt)
				{
				settings.max_queued_disk_bytes=settings.max_queued_disk_bytes-settings.max_queued_disk_bytes/4;
				}
				else
				{
				settings.cache_size+=32;
				}
				break;
				}
				}
				ses->set_settings(settings);
				}*/
			case add_torrent_alert::alert_type:
			case listen_succeeded_alert::alert_type:
			case state_changed_alert::alert_type:
			case torrent_added_alert::alert_type:
			case torrent_checked_alert::alert_type:
			case torrent_resumed_alert::alert_type:
			case torrent_paused_alert::alert_type:
			case torrent_removed_alert::alert_type:
			case cache_flushed_alert::alert_type:
			case torrent_deleted_alert::alert_type:
			case external_ip_alert::alert_type:
			case udp_error_alert::alert_type:
			case dht_reply_alert::alert_type:
			case tracker_announce_alert::alert_type:
				break;

			default:
			{
				QString information = QString::fromUtf8(a->message().c_str());

				if ((a->category() & alert::error_notification) == alert::error_notification)
				{
					emit Notify(NotificationSystem::ERRORS, information, QVariant());
				}
				else
				{
					emit Notify(NotificationSystem::TORRENT_INFO, information, QVariant());
				}

				break;
			}
	}
	}
	TORRENT_CATCH(std::exception & e)
	{
		qCritical() << "exception in handle_alert" << e.what();
	}
}