Esempio n. 1
0
//Downloads all the data from YahooFinance.
void StockSearch::on_btnFind_clicked()
{
    //QTimer tT;
    //QEventLoop q;


    QString input = ui->lineEditSearch->text();
    QString baseURL = "http://download.finance.yahoo.com/d/quotes.txt?s=";
    QString urlFormatting = "&f=sl1d1t1c1ohgv&e=.txt";

    QUrl thisURL = (QUrl) (baseURL + input + urlFormatting);
    DownloadManager manager;
    manager.doDownload(thisURL);

    //tT.start(3000);
    //q.processEvents();
    //q.exec();
    //q.wakeUp();

    //q.exit(0);

    //This dummy window has to open in order to download Data from YahooFinance...Click EXIT once immediately.
    dummyWindow = new DummyForDownload(this);
    dummyWindow->exec();
    dummyWindow->close();

    parseData();
}
Esempio n. 2
0
void WebView::downloadLinkToDisk()
{
    if (QAction* action = qobject_cast<QAction*>(sender())) {
        DownloadManager* dManager = mApp->downManager();
        QNetworkRequest request(action->data().toUrl());
        dManager->download(request, qobject_cast<WebPage*>(page()), false);
    }
}
Esempio n. 3
0
void WebView::downloadUrlToDisk()
{
    if (QAction* action = qobject_cast<QAction*>(sender())) {
        QNetworkRequest request(action->data().toUrl());

        DownloadManager::DownloadInfo info;
        info.page = page();
        info.suggestedFileName = QString();
        info.askWhatToDo = false;
        info.forceChoosingPath = true;

        DownloadManager* dManager = mApp->downloadManager();
        dManager->download(request, info);
    }
}
Esempio n. 4
0
void WebPage::handleUnsupportedContent(QNetworkReply* reply)
{
    if (!reply) {
        return;
    }

    const QUrl url = reply->url();

    switch (reply->error()) {
    case QNetworkReply::NoError:
        if (reply->header(QNetworkRequest::ContentTypeHeader).isValid()) {
            QString requestUrl = reply->request().url().toString(QUrl::RemoveFragment | QUrl::RemoveQuery);
            if (requestUrl.endsWith(QLatin1String(".swf"))) {
                const QWebElement docElement = mainFrame()->documentElement();
                const QWebElement object = docElement.findFirst(QString("object[src=\"%1\"]").arg(requestUrl));
                const QWebElement embed = docElement.findFirst(QString("embed[src=\"%1\"]").arg(requestUrl));

                if (!object.isNull() || !embed.isNull()) {
                    qDebug() << "WebPage::UnsupportedContent" << url << "Attempt to download flash object on site!";
                    reply->deleteLater();
                    return;
                }
            }
            DownloadManager* dManager = mApp->downloadManager();
            dManager->handleUnsupportedContent(reply, this);
            return;
        }
        // Falling unsupported content with invalid ContentTypeHeader to be handled as UnknownProtocol

    case QNetworkReply::ProtocolUnknownError: {
        if (url.scheme() == QLatin1String("file")) {
            FileSchemeHandler::handleUrl(url);
            return;
        }

        qDebug() << "WebPage::UnsupportedContent" << url << "ProtocolUnknowError";
        desktopServicesOpen(url);

        reply->deleteLater();
        return;
    }
    default:
        break;
    }

    qDebug() << "WebPage::UnsupportedContent error" << url << reply->errorString();
    reply->deleteLater();
}
Esempio n. 5
0
void WebView::savePageAs()
{
    QNetworkRequest request(url());
    QString suggestedFileName = qz_getFileNameFromUrl(url());
    if (!suggestedFileName.contains(QLatin1Char('.'))) {
        suggestedFileName.append(QLatin1String(".html"));
    }

    DownloadManager::DownloadInfo info;
    info.page = page();
    info.suggestedFileName = suggestedFileName;
    info.askWhatToDo = false;
    info.forceChoosingPath = true;

    DownloadManager* dManager = mApp->downManager();
    dManager->download(request, info);
}
void SettingsDialog::load()
{
    SettingsManager * manager = SettingsManager::settingsManager();
    HistoryManager * historyManager = HistoryManager::historyManager();
    DownloadManager * downloadManager = DownloadManager::downloadManager();
    NetworkAccessManager * networkAccessManager = NetworkAccessManager::networkAccessManager();
    TabManager * tabManager = TabManager::tabManager();
    m_imagesCheckBox->setChecked(manager->isImagesEnabled());
    m_javascriptCheckBox->setChecked(manager->isJavascriptEnabled());
    m_javaCheckBox->setChecked(manager->isJavaEnabled());
    m_pluginsCheckBox->setChecked(manager->isPluginsEnabled());
    m_sansFontComboBox->setCurrentFont(QFont(manager->sansFontFamily()));
    m_serifFontComboBox->setCurrentFont(QFont(manager->serifFontFamily()));
    m_monoFontComboBox->setCurrentFont(QFont(manager->monoFontFamily()));
    m_standardFontSpinBox->setValue(manager->standardFontSize());
    m_monoFontSpinBox->setValue(manager->monoFontSize());
    m_privateBrowsingCheckBox->setChecked(historyManager->isPrivateBrowsingEnabled());
    m_historyExpirationComboBox->setCurrentIndex(2);
    for(int i = 0; i < 8; i++)
    {
        if(m_historyExpirationComboBox->itemData(i).toInt() ==
           historyManager->expirationDays())
        {
            m_historyExpirationComboBox->setCurrentIndex(i);
            break;
        }
    }
    QString path = downloadManager->standardPath();
    if(path.isEmpty())
    {
        m_downloadCheckBox->setChecked(false);
    }
    else
    {
        m_downloadCheckBox->setChecked(true);
        m_downloadLineEdit->setText(path);
    }
    m_cacheSizeSpinBox->setValue(networkAccessManager->cacheSize() / 1024 / 1024);
    QUrl url(networkAccessManager->proxy());
    if(!url.isEmpty())
    {
        m_proxyLineEdit->setText(url.host());
        m_proxySpinBox->setValue(url.port());
    }
    m_addTabPolicyComboBox->setCurrentIndex(tabManager->addTabPolicy() == TabManager::AddAfterLast ? 0 : 1);
}
Esempio n. 7
0
//--------------------------------------------------------------------------------------------------------------
int CL_CanUseHTTPDownload(void)
{
	if ( sv_downloadurl.GetString()[0] )
	{
		const char *serverMapName = va( "%s:%s", sv_downloadurl.GetString(), cl.m_szLevelName );
		return !TheDownloadManager.HasMapBeenDownloadedFromServer( serverMapName );
	}
	return 0;
}
Esempio n. 8
0
void WebView::savePageAs()
{
    if (url().isEmpty() || url().toString() == QLatin1String("about:blank")) {
        return;
    }

    QNetworkRequest request(url());
    QString suggestedFileName = QzTools::getFileNameFromUrl(url());
    if (!suggestedFileName.contains(QLatin1Char('.'))) {
        suggestedFileName.append(QLatin1String(".html"));
    }

    DownloadManager::DownloadInfo info;
    info.page = page();
    info.suggestedFileName = suggestedFileName;
    info.askWhatToDo = false;
    info.forceChoosingPath = true;

    DownloadManager* dManager = mApp->downloadManager();
    dManager->download(request, info);
}
void SettingsDialog::save()
{
    SettingsManager * manager = SettingsManager::settingsManager();
    HistoryManager * historyManager = HistoryManager::historyManager();
    DownloadManager * downloadManager = DownloadManager::downloadManager();
    NetworkAccessManager * networkAccessManager = NetworkAccessManager::networkAccessManager();
    TabManager * tabManager = TabManager::tabManager();
    manager->setImagesEnabled(m_imagesCheckBox->isChecked());
    manager->setJavascriptEnabled(m_javascriptCheckBox->isChecked());
    manager->setJavaEnabled(m_javaCheckBox->isChecked());
    manager->setPluginsEnabled(m_pluginsCheckBox->isChecked());
    manager->setSansFontFamily(m_sansFontComboBox->currentFont().family());
    manager->setSerifFontFamily(m_serifFontComboBox->currentFont().family());
    manager->setMonoFontFamily(m_monoFontComboBox->currentFont().family());
    manager->setStandardFontSize(m_standardFontSpinBox->value());
    manager->setMonoFontSize(m_monoFontSpinBox->value());
    historyManager->setPrivateBrowsingEnabled(m_privateBrowsingCheckBox->isChecked());
    int index = m_historyExpirationComboBox->currentIndex();
    int days = m_historyExpirationComboBox->itemData(index).toInt();
    historyManager->setExpirationDays(days);
    QString path;
    if(m_downloadCheckBox->isChecked())
    {
        path = m_downloadLineEdit->text();
    }
    else
    {
        path = "";
    }
    downloadManager->setStandardPath(path);
    networkAccessManager->setCacheSize(m_cacheSizeSpinBox->value() * 1024 * 1024);
    QUrl url;
    if(!m_proxyLineEdit->text().isEmpty())
    {
        url.setHost(m_proxyLineEdit->text());
        url.setPort(m_proxySpinBox->value());
    }
    networkAccessManager->setProxy(url);
    tabManager->setAddTabPolicy(TabManager::AddTabPolicy(m_addTabPolicyComboBox->currentIndex()));
}
Esempio n. 10
0
int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);
    QStringList arguments = app.arguments();
    arguments.takeFirst();      // remove the first argument, which is the program's name

    if (arguments.isEmpty()) {
        printf("Qt Download example\n"
               "Usage: downloadmanager url1 [url2... urlN]\n"
               "\n"
               "Downloads the URLs passed in the command-line to the local directory\n"
               "If the target file already exists, a .0, .1, .2, etc. is appended to\n"
               "differentiate.\n");
        return 0;
    }

    DownloadManager manager;
    manager.append(arguments);

    QObject::connect(&manager, SIGNAL(finished()), &app, SLOT(quit()));
    app.exec();
}
Esempio n. 11
0
void MainWindow::downComponents(QString url, int postOp)
{
    // paso 2: Descargar la actualizacion
    DownloadManager *downManager = new DownloadManager(this);
    if(!proxyHostName.isNull() && proxyPort > -1){
        downManager->setProxy(proxyHostName, proxyPort);
        QTextStream(stdout)<<"New Proxy!"<<endl;
    }

    const QUrl iUrl(url);
    downManager->doDownload(iUrl);
    switch(postOp)
    {
    case 0:
        writeText("Descargando en ../temp/soft-emg-version.xml", msg_notify);
        connect(downManager, SIGNAL(downFinished(bool, QString)), this, SLOT(compararVersiones(bool,QString)) );
        break;

    case 1:
        writeText("Descargando archivo "+url+"", msg_notify);
        connect(downManager, SIGNAL(downFinished(bool, QString)), this, SLOT(execBatchFile(bool, QString)) );
        break;

    case 2:
        writeText("Descargando componentes de la actualizacion...", msg_notify);
        connect(downManager, SIGNAL(downFinished(bool, QString)), this, SLOT(actualizarComboBox(bool, QString)) );
        break;

    case 3:
        writeText("Descargando desde "+url, msg_notify);
        downComponents("https://github.com/dkmpos89/softEGM_updates/raw/master/soft-updates.zip", execBatch);
        break;
    default:
        break;
    }
}
Esempio n. 12
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    downloadManager.addNewDownload("http://stream.get-tune.net/file/84506369/17645845/3257725966/298c3e49b56edbb5/Nirvana_-_In_Bloom_(get-tune.net).mp3","E:/");
    downloadManager.addNewDownload("http://r17---sn-5hn7snel.c.youtube.com/videoplayback?ratebypass=yes&ipbits=8&sparams=cp%2Cid%2Cip%2Cipbits%2Citag%2Cratebypass%2Csource%2Cupn%2Cexpire&newshard=yes&fexp=901448%2C932000%2C932004%2C906383%2C902000%2C901208%2C919512%2C929903%2C925714%2C931202%2C900821%2C900823%2C931203%2C931401%2C906090%2C909419%2C908529%2C930807%2C919373%2C930803%2C906836%2C920201%2C929602%2C930101%2C926403%2C900824%2C910223&expire=1365533546&key=yt1&ip=194.110.219.32&mt=1365509064&sver=3&cp=U0hVSlVOUV9JUENONV9NSFVGOldxYTUyQUY5SHRD&source=youtube&id=2b50e7631777893c&upn=05_U661I2dg&mv=m&ms=au&itag=22&signature=1FAA16502CD0A5758B2D9BC81210D570058CD8A1.B1256CB3D261128FDBF969AE01C8EC0BE6ACF74D&title=Blender+Basics+-+03+-+Modeling","E:/");
    downloadManager.startDownload(downloadManager.downloadAt(0).value);
    downloadManager.startDownload(downloadManager.downloadAt(1).value);
    downloadManager.startDownload(downloadManager.addNewDownload("http://cs416327.vk.me/v416327355/492f/zYtqx5wz9qA.jpg","E:/").value);


    
    return a.exec();
}
Esempio n. 13
0
//--------------------------------------------------------------------------------------------------------------
bool CL_DownloadUpdate(void)
{
	return TheDownloadManager.Update();
}
Esempio n. 14
0
void WebPage::downloadRequested(const QNetworkRequest &request)
{
    DownloadManager* dManager = mApp->downloadManager();
    dManager->download(request, this);
}
Esempio n. 15
0
bool CL_FileDenied( const char *filename, unsigned int requestID )
{
	return TheDownloadManager.FileDenied( filename, requestID );
}
Esempio n. 16
0
//--------------------------------------------------------------------------------------------------------------
void CL_HTTPStop_f(void)
{
	TheDownloadManager.Stop();
}
Esempio n. 17
0
static LRESULT WINAPI HiddenWndProc(HWND hwnd, 
                                    UINT msg, 
                                    WPARAM wParam, 
                                    LPARAM lParam )
{
    LRESULT result = 0;
    FAContext* context = (FAContext*)GetWindowLong(hwnd, GWL_USERDATA);
    static bool replaceCurrentQueue = true;

    switch (msg)
    {
        case WM_CREATE:
        {
            context = (FAContext*)((LPCREATESTRUCT)lParam)->lpCreateParams;

            assert(context != NULL);
          
            result = SetWindowLong(hwnd, GWL_USERDATA, (LONG)context);
                        
            break;
        }

        case WM_TIMER:
        {
            KillTimer(hwnd, 1);
            replaceCurrentQueue = true;
            break;
        }

        case WM_COPYDATA:
        {
            COPYDATASTRUCT* pcds = (COPYDATASTRUCT*)lParam;
            int32 count = pcds->dwData;
            char* array = (char*)pcds->lpData;
            char path[MAX_PATH];
            char url[MAX_PATH + 7];
            uint32 length = sizeof(url);
            int offset = 0;

            KillTimer(hwnd, 1);

            bool playNow = false;

            context->prefs->GetPrefBoolean(kPlayImmediatelyPref, &playNow);
            
            // If a single theme or rpm file gets passed, don't affect 
            // the play queue
            if (strcasecmp("fat", array + strlen(array) - 3) == 0 ||
                strcasecmp("rmp", array + strlen(array) - 3) == 0)
                playNow = false;

            if(playNow)
            {
                if(replaceCurrentQueue)
                {
                    context->target->AcceptEvent(new Event(CMD_Stop));
                    context->plm->RemoveAll();

                    replaceCurrentQueue = false;
                }
            }

            for(int32 i = 0; i < count; i++)
            {
                strcpy(path, array + offset);
                offset += strlen(path) + 1;

                // is this a URL we know how to handle
                if( !strncasecmp(path, "http://", 7) ||
                    !strncasecmp(path, "rtp://", 6))
                {
                    context->plm->AddItem(path);

                    if(playNow)
                    {
                        SetTimer(hwnd, 1, 1000, NULL);
                    }

                    continue;
                }

                HANDLE handle;
                WIN32_FIND_DATA data;

                handle = FindFirstFile(path, &data);

                if(handle != INVALID_HANDLE_VALUE)
                {
                    char* cp = NULL;

                    cp = strrchr(path, '\\');

                    if(cp)
                    {
                        strcpy(cp + 1, data.cFileName);
                    }

                    FindClose(handle);
                }

                FilePathToURL(path, url, &length);

                // who needs to get this, plm or dlm?
                bool giveToDLM = false;
                bool giveToTheme = false;
                char* extension = NULL;
                PlaylistManager* plm = context->plm;
                DownloadManager* dlm = context->downloadManager;

                extension = strrchr(url, '.');
                if(extension)
                {
                    DownloadFormatInfo dlfi;
                    uint32 i = 0;

                    extension++;

                    while(IsntError(dlm->GetSupportedDownloadFormats(&dlfi, i++)))
                    {
                        if(!strcasecmp(extension, dlfi.GetExtension()))
                        {
                            giveToDLM = true;
                            break;
                        }
                    }
                    if (strcasecmp(extension, themeExtension) == 0)
                        giveToTheme = true; 
                }

                if(giveToDLM)
                    dlm->ReadDownloadFile(url);
                else if(giveToTheme)
                    context->player->AddTheme(url);
                else
                    plm->AddItem(url);

                if(playNow)
                {
                    SetTimer(hwnd, 1, 1000, NULL);
                }
            }
            
            break;
        }
        
        case WM_DISPLAYCHANGE:
        {
            context->target->AcceptEvent(new Event(INFO_PrefsChanged));
            break;
        }
        default:
            result = DefWindowProc(hwnd, msg, wParam, lParam);
            break;

    }

    return result;
}
Esempio n. 18
0
void BufferedSocket::threadRead() throw(SocketException) {
	dcassert(sock);
	if(!sock)
		return;
	DownloadManager *dm = DownloadManager::getInstance();
	size_t readsize = inbuf.size();
	bool throttling = false;
	if(mode == MODE_DATA)
	{
		uint32_t getMaximum;
        throttling = dm && dm->throttle() && getSuperUser() == false;
		if (throttling)
		{
			getMaximum = dm->throttleGetSlice();
			readsize = (uint32_t)min((int64_t)inbuf.size(), (int64_t)getMaximum);
			if (readsize <= 0  || readsize > inbuf.size()) { // FIX
				Thread::sleep(dm->throttleCycleTime());
				return;
			}
		}
	}
	int left = sock->read(&inbuf[0], (int)readsize);
	if(left == -1) {
	// EWOULDBLOCK, no data received...
		return;
	} else if(left == 0) {
		// This socket has been closed...
		throw EOFSocketException();
	}
	int bufpos = 0;
	const int total = left;

	while (left > 0) {
		switch (mode) {
			case MODE_ZPIPE:
				if (filterIn != NULL){
				    const int BufSize = 1024;
					AutoArray<uint8_t> buffer (BufSize);
					string l = line;
					// decompress all input data and store in l.
					while (left) {
						size_t in = BufSize;
						size_t used = left;
						bool ret = (*filterIn) ((void *)(&inbuf[0] + total - left), used, &buffer[0], in);
						left -= used;
						l.append ((const char *)&buffer[0], in);
						// if the stream ends before the data runs out, keep remainder of data in inbuf
						if (!ret) {
							bufpos = total-left;
							setMode (MODE_LINE, rollback);
							break;
						}
					}
					// process all lines
					string::size_type pos;
					while ((pos = l.find(separator)) != string::npos) {
                       	if(pos > 0) // check empty (only pipe) command and don't waste cpu with it ;o)
							fire(BufferedSocketListener::Line(), l.substr(0, pos));
						l.erase (0, pos + 1 /* seperator char */);
					}
					// store remainder
					line = l;

					break;
				}
			case MODE_LINE:
				// Special to autodetect nmdc connections...
				if(separator == 0) {
					if(inbuf[0] == '$') {
						separator = '|';
					} else {
						separator = '\n';
					}
				}
				{
#if 0
					string l = line + string((char*)&inbuf[bufpos], left);
					size_t linePos = 0;
					string::size_type pos;
					while ((pos = l.find(separator, linePos)) != string::npos) {
						if(pos > linePos) // check empty (only pipe) command and don't waste cpu with it ;o)
							fire(BufferedSocketListener::Line(), l.substr(linePos, pos - linePos));
						left -= (pos - linePos + 1);
						if (mode != MODE_LINE) {
							// we changed mode; remainder of line is invalid.
							line.clear();
							bufpos = total - left;
							break;
						}
						linePos = pos + 1;
					}
					if (pos == string::npos) {
						// no more separators; keep remainder of line
						left = 0;
						line = l.substr(linePos);
					}
#else
					string l = line + string ((char*)&inbuf[bufpos], left);
					string::size_type pos;
					while ((pos = l.find(separator)) != string::npos) {
						if(pos > 0) // check empty (only pipe) command and don't waste cpu with it ;o)
							fire(BufferedSocketListener::Line(), l.substr(0, pos));
						l.erase (0, pos + 1 /* separator char */);
						if (l.length() < (size_t)left) left = l.length();
						if (mode != MODE_LINE) {
							// we changed mode; remainder of l is invalid.
							l.clear();
							bufpos = total - left;
							break;
						}
					}
					if (pos == string::npos) 
						left = 0;
					line = l;
#endif
				}
				break;
			case MODE_DATA:
				while(left > 0) {
					if(dataBytes == -1) {
						fire(BufferedSocketListener::Data(), &inbuf[bufpos], left);
						bufpos += (left - rollback);
						left = rollback;
						rollback = 0;
					} else {
						int high = (int)min(dataBytes, (int64_t)left);
						fire(BufferedSocketListener::Data(), &inbuf[bufpos], high);
						bufpos += high;
						left -= high;

						dataBytes -= high;
						if(dataBytes == 0) {
							mode = MODE_LINE;
							fire(BufferedSocketListener::ModeChange());
						}
					}
					if (throttling) {
						if (left > 0 && left < (int)readsize) {
							dm->throttleReturnBytes(left - readsize);
						}
						Thread::sleep(dm->throttleCycleTime());
					}
				}
				break;
		}
	}
	
	if(mode == MODE_LINE && line.size() > 16777216) {
		throw SocketException(STRING(COMMAND_TOO_LONG));
	}	
}
Esempio n. 19
0
//--------------------------------------------------------------------------------------------------------------
void CL_MarkMapAsUsingHTTPDownload(void)
{
	const char *serverMapName = va( "%s:%s", sv_downloadurl.GetString(), cl.m_szLevelName );
	TheDownloadManager.MarkMapAsDownloadedFromServer( serverMapName );
}
Esempio n. 20
0
//--------------------------------------------------------------------------------------------------------------
int CL_GetDownloadQueueSize(void)
{
	return TheDownloadManager.GetQueueSize();
}
Esempio n. 21
0
void CL_QueueDownload( const char *filename )
{
	TheDownloadManager.Queue( sv_downloadurl.GetString(), filename );
}
Esempio n. 22
0
void MainMenu::showDownloadManager()
{
    DownloadManager* m = mApp->downloadManager();
    m->show();
    m->raise();
}
Esempio n. 23
0
void BufferedSocket::threadRead() throw(SocketException) {
	if(state != RUNNING)
		return;

	DownloadManager *dm = DownloadManager::getInstance();
	size_t readsize = inbuf.size();
	bool throttling = false;
	if(mode == MODE_DATA)
	{
		uint32_t getMaximum;
		throttling = dm->throttle();
		if (throttling)
		{
			getMaximum = dm->throttleGetSlice();
			readsize = (uint32_t)min((int64_t)inbuf.size(), (int64_t)getMaximum);
			if (readsize <= 0  || readsize > inbuf.size()) { // FIX
				sleep(dm->throttleCycleTime());
				return;
			}
		}
	}
	int left = sock->read(&inbuf[0], (int)readsize);
	if(left == -1) {
		// EWOULDBLOCK, no data received...
		return;
	} else if(left == 0) {
		// This socket has been closed...
		throw SocketException(_("Connection closed"));
	}
	string::size_type pos = 0;
	// always uncompressed data
	string l;
	int bufpos = 0, total = left;

	while (left > 0) {
		switch (mode) {
			case MODE_ZPIPE: {
					const int BUF_SIZE = 1024;
					// Special to autodetect nmdc connections...
					string::size_type pos = 0;
					boost::scoped_array<char> buffer(new char[BUF_SIZE]);
					l = line;
					// decompress all input data and store in l.
					while (left) {
						size_t in = BUF_SIZE;
						size_t used = left;
						bool ret = (*filterIn) (&inbuf[0] + total - left, used, &buffer[0], in);
						left -= used;
						l.append (&buffer[0], in);
						// if the stream ends before the data runs out, keep remainder of data in inbuf
						if (!ret) {
							bufpos = total-left;
							setMode (MODE_LINE, rollback);
							break;
						}
					}
					// process all lines
					while ((pos = l.find(separator)) != string::npos) {
						fire(BufferedSocketListener::Line(), l.substr(0, pos));
						l.erase (0, pos + 1 /* separator char */);
					}
					// store remainder
					line = l;

					break;
				}
			case MODE_LINE:
				// Special to autodetect nmdc connections...
				if(separator == 0) {
					if(inbuf[0] == '$') {
						separator = '|';
					} else {
						separator = '\n';
					}
				}
				l = line + string ((char*)&inbuf[bufpos], left);
				while ((pos = l.find(separator)) != string::npos) {
					fire(BufferedSocketListener::Line(), l.substr(0, pos));
					l.erase (0, pos + 1 /* separator char */);
					if (l.length() < (size_t)left) left = l.length();
					if (mode != MODE_LINE) {
						// we changed mode; remainder of l is invalid.
						l.clear();
						bufpos = total - left;
						break;
					}
				}
				if (pos == string::npos)
					left = 0;
				line = l;
				break;
			case MODE_DATA:
				while(left > 0) {
					if(dataBytes == -1) {
						fire(BufferedSocketListener::Data(), &inbuf[bufpos], left);
						bufpos += (left - rollback);
						left = rollback;
						rollback = 0;
					} else {
						int high = (int)min(dataBytes, (int64_t)left);
						fire(BufferedSocketListener::Data(), &inbuf[bufpos], high);
						bufpos += high;
						left -= high;

						dataBytes -= high;
						if(dataBytes == 0) {
							mode = MODE_LINE;
							fire(BufferedSocketListener::ModeChange());
						}
					}
					if (throttling) {
						if (left > 0 && left < (int)readsize) {
							dm->throttleReturnBytes(left - readsize);
						}
						uint32_t sleep_interval =  dm->throttleCycleTime();
						Thread::sleep(sleep_interval);
					}
				}
				break;
		}
	}

	if(mode == MODE_LINE && line.size() > static_cast<size_t>(SETTING(MAX_COMMAND_LENGTH))) {
		throw SocketException(_("Maximum command length exceeded"));
	}
}