Ejemplo n.º 1
0
int main(int argc, char *argv[])
{
    Settings cfg;
    Option opt(argc, argv, &cfg);
    std::string search = "";

    if(opt.doConfig()) {
        opt.configure();
        return 0;
    } else if (argc < 2) {
        printError("invalid or missing arguments");
        return 1;
    } else {
        // combine all the args in a space separated string.
        for(int i=1; i<argc; i++) {
            if(search != "") search += " ";
            search += argv[i];
        }
    }

    if(false == cfg.isValid()) {
        cout << "WARN: Invalid configuration or can't open '" << cfg.getConfigFile() << "'" << endl;
        cout << "WARN: Please create a valid configuration first.'" << endl;
        return 1;
    }

    // contains default search template strings for searching and exporting vcards
    SearchTemplates st;

    // preset search template
    bool doCache = false;

    std::string query = st.getDefaultSearchTemplate();
    if(opt.hasOption("--create-local-cache")) {
        query = st.getDefaultExportTemplate();

        // overwrite the default export template with one the user provided
        std::string templateFile = FileUtils::getHomeDir() + "/" + cfg.getConfigDir() + "/export.xml";
        if(FileUtils::fileExists(templateFile)) {
            if(false == FileUtils::getFileContent(templateFile, &query))
                return 1;
        }

        doCache = true;

    } else {
        // overwrite the default search template with one the user provided
        std::string templateFile = FileUtils::getHomeDir() + "/" + cfg.getConfigDir() + "/search.xml";
        if(FileUtils::fileExists(templateFile)) {
            if(false == FileUtils::getFileContent(templateFile, &query))
                return 1;
        }
    }

    // fetch the list of curlers (idea and partially code by Benjamin Frank <*****@*****.**> on March 9, 2013)
    std::vector<std::string> sections = cfg.getSections();

    // there is the cache ;)
    std::string cachefile = cfg.getCacheFile();
    std::vector<Person> people;

    if(true == doCache) {
        if(FileUtils::fileExists(cachefile)) {
            if(FileUtils::fileRemove(cachefile)) {
                cout << "Old cache deleted" << endl;
            } else {
                cerr << "Failed to remove old cache database: " << cachefile << endl;
                return 1;
            }
        }

        for(std::vector<std::string>::iterator it = sections.begin(); it != sections.end(); ++it) {
            std::string section(*it);

            std::string server(cfg.getProperty(section, "server"));
            std::string url(Url::removePath(server));
            std::cout << "Creating cache entries for config section [" << section << "], URL: [" << server << "]" << std::endl;

            if(url.size() > 0) {
                CardCurler cc(cfg.getProperty(section, "username"), cfg.getProperty(section, "password"), server, argv[1]);
                std::vector<Person> tmp_people = cc.getAllCards(url, query);
                people.insert(people.end(), tmp_people.begin(), tmp_people.end());
            }
        }

        if(people.size() > 0 ) {
            Cache cache;
            if(false == cache.createDatabase())
                return 1;

            int numRecords = 0;
            std::cout << "Importing vcards" << std::endl;

            for(unsigned int i=0; i<people.size(); i++) {
                Person p = people.at(i);
                cache.addVCard(
                            p.FirstName,
                            p.LastName,
                            p.Emails,
                            p.rawCardData,
                            p.lastUpdatedAt
                );
                numRecords++;
            }

            chmod(cachefile.c_str(), S_IRUSR | S_IWUSR);
            cout << "Cache created (" << numRecords << " records)" << endl;
        } else {
            cout << "Export failed, nothing found" << endl;
        }
    } else {
        // 1. look into the cache
        bool cacheMiss = false;
        if(FileUtils::fileExists(cachefile)) {
            if(Option::isVerbose()) {
                std::cout << "Cache lookup in file " << cachefile;
            }
            
            people = CardCurler::curlCache(search);

            if(Option::isVerbose()) {
                std::cout << "Cache lookup returned " << people.size() << " records";
            }
        }

        // nothing found in cache? => search online
        if(people.size() == 0) {
           cacheMiss = true;
           StringUtils::replace(&query, "%s", search);

           // isn't it a nice duplication? - so get rid of it, stupid!
           for(std::vector<std::string>::const_iterator it = sections.begin(); it != sections.end(); ++it) {
                std::string section(*it);
                std::string server(cfg.getProperty(section, "server"));

              if(server.size() > 0) {
                   CardCurler cc(cfg.getProperty(section, "username"), cfg.getProperty(section, "password"), server, argv[1]);
                   std::vector<Person> tmp_people = cc.curlCard(query);
                   people.insert(people.end(), tmp_people.begin(), tmp_people.end());
              }
           }
        }

        if(people.size() > 0) {
            std::cout << std::endl; // needed by mutt to skip below the top line
            for(unsigned int i=0; i<people.size(); i++) {
                Person p = people.at(i);
                for(unsigned int j=0; j < p.Emails.size(); j++) {
                    std::cout << p.Emails.at(j) << '\t' << p.FirstName << ' ' << p.LastName << std::endl;
                }
            }

            // now update the cache
            if(cacheMiss && FileUtils::fileExists(cachefile)) {
                Cache cache;
                cache.openDatabase();
                for(unsigned int i=0; i<people.size(); i++) {
                    Person p = people.at(i);
                    cache.addVCard(p.FirstName, p.LastName, p.Emails, p.rawCardData, p.lastUpdatedAt);
                }
            }

        } else {
            cout << "Search returned no results" << endl;
        }
    }

    return 0;
}
Ejemplo n.º 2
0
Archivo: pihmgis.cpp Proyecto: mlt/PIHM
void PIHMgis::runOnlineHelp(){
  QUrl url("http://www.pihm.psu.edu/pihmgis_documents.html");
  QDesktopServices::openUrl( url);
}
Ejemplo n.º 3
0
void KonqRun::foundMimeType(const QString & _type)
{
    //kDebug() << "KonqRun::foundMimeType " << _type << " m_req=" << m_req.debug();

    QString mimeType = _type; // this ref comes from the job, we lose it when using KIO again

    m_bFoundMimeType = true;

    if (m_pView)
        m_pView->setLoading(false); // first phase finished, don't confuse KonqView

    // Check if the main window wasn't deleted meanwhile
    if (!m_pMainWindow) {
        setError(true);
        setFinished(true);
        return;
    }

    // Grab the args back from BrowserRun
    m_req.args = arguments();
    m_req.browserArgs = browserArguments();

    bool tryEmbed = true;
    // One case where we shouldn't try to embed, is when the server asks us to save
    if (serverSuggestsSave())
        tryEmbed = false;

    const bool associatedAppIsKonqueror = KonqMainWindow::isMimeTypeAssociatedWithSelf(mimeType);

    if (tryEmbed && tryOpenView(mimeType, associatedAppIsKonqueror)) {
        return;
    }

    // If we were following another view, do nothing if opening didn't work.
    if (m_req.followMode) {
        setFinished(true);
    }

    if (!hasFinished()) {
        // If we couldn't embed the mimetype, call BrowserRun::handleNonEmbeddable()
        KService::Ptr selectedService;
        KParts::BrowserRun::NonEmbeddableResult res = handleNonEmbeddable(mimeType, &selectedService);
        if (res == KParts::BrowserRun::Delayed)
            return;
        setFinished(res == KParts::BrowserRun::Handled);
        if (hasFinished()) {
            // save or cancel -> nothing else will happen in m_pView, so clear statusbar (#163628)
            m_pView->frame()->statusbar()->slotClear();
        } else {
            if (!tryEmbed) {
                // "Open" selected for a serverSuggestsSave() file - let's open. #171869
                if (tryOpenView(mimeType, associatedAppIsKonqueror))
                    return;
            }
            // "Open" selected, possible with a specific application
            if (selectedService)
                KRun::setPreferredService(selectedService->desktopEntryName());
            else {
                KRun::displayOpenWithDialog(url(), m_pMainWindow, false /*tempfile*/, suggestedFileName());
                setFinished(true);
            }
        }
    }

    // make Konqueror think there was an error, in order to stop the spinning wheel
    // (we saved, canceled, or we're starting another app... in any case the current view should stop loading).
    setError(true);

    if (!hasFinished()) { // only if we're going to open
        if (associatedAppIsKonqueror && m_pMainWindow->refuseExecutingKonqueror(mimeType)) {
            setFinished(true);
        }
    }

    if (!hasFinished()) {
        kDebug() << "Nothing special to do in KonqRun, falling back to KRun";
        KRun::foundMimeType(mimeType);
    }
}
Ejemplo n.º 4
0
void SessionController::logout()
{
    userLogout();
    redirect(url("session", "form"));
}
bool Filters::BT_ThMLHTML::handleToken(sword::SWBuf &buf, const char *token, sword::BasicFilterUserData *userData) {
    if (!substituteToken(buf, token) && !substituteEscapeString(buf, token)) {
        sword::XMLTag tag(token);
        BT_UserData* myUserData = dynamic_cast<BT_UserData*>(userData);
        sword::SWModule* myModule = const_cast<sword::SWModule*>(myUserData->module); //hack to be able to call stuff like Lang()

        if ( tag.getName() && !sword::stricmp(tag.getName(), "foreign") ) { // a text part in another language, we have to set the right font

            if (tag.getAttribute("lang")) {
                const char* abbrev = tag.getAttribute("lang");
                //const CLanguageMgr::Language* const language = CPointers::languageMgr()->languageForAbbrev( QString::fromLatin1(abbrev) );

                buf.append("<span class=\"foreign\" lang=\"");
                buf.append(abbrev);
                buf.append("\">");
            }
        }
        else if (tag.getName() && !sword::stricmp(tag.getName(), "sync")) { //lemmas, morph codes or strongs

            if (tag.getAttribute("type") && (!sword::stricmp(tag.getAttribute("type"), "morph") || !sword::stricmp(tag.getAttribute("type"), "Strongs") || !sword::stricmp(tag.getAttribute("type"), "lemma"))) { // Morph or Strong
                buf.append('<');
                buf.append(token);
                buf.append('>');
            }
        }
        else if (tag.getName() && !sword::stricmp(tag.getName(), "note")) { // <note> tag

            if (!tag.isEndTag() && !tag.isEmpty()) {
                //appending is faster than appendFormatted
                buf.append(" <span class=\"footnote\" note=\"");
                buf.append(myModule->Name());
                buf.append('/');
                buf.append(myUserData->key->getShortText());
                buf.append('/');
                buf.append( QString::number(myUserData->swordFootnote++).toUtf8().constData() );
                buf.append("\">*</span> ");

                myUserData->suspendTextPassThru = true;
                myUserData->inFootnoteTag = true;
            }
            else if (tag.isEndTag() && !tag.isEmpty()) { //end tag
                //buf += ")</span>";
                myUserData->suspendTextPassThru = false;
                myUserData->inFootnoteTag = false;
            }
        }
        else if (tag.getName() && !sword::stricmp(tag.getName(), "scripRef")) { // a scripRef
            //scrip refs which are embeded in footnotes may not be displayed!

            if (!myUserData->inFootnoteTag) {
                if (tag.isEndTag()) {
                    if (myUserData->inscriptRef) { // like "<scripRef passage="John 3:16">See John 3:16</scripRef>"
                        buf.append("</a></span>");

                        myUserData->inscriptRef = false;
                        myUserData->suspendTextPassThru = false;
                    }
                    else { // like "<scripRef>John 3:16</scripRef>"

                        CSwordModuleInfo* mod = CBTConfig::get(CBTConfig::standardBible);
                        //Q_ASSERT(mod); tested later
                        if (mod) {
                            ReferenceManager::ParseOptions options;
                            options.refBase = QString::fromUtf8(myUserData->key->getText()); //current module key
                            options.refDestinationModule = QString(mod->name());
                            options.sourceLanguage = QString(myModule->Lang());
                            options.destinationLanguage = QString("en");

                            //it's ok to split the reference, because to descriptive text is given
                            bool insertSemicolon = false;
                            buf.append("<span class=\"crossreference\">");
                            QStringList refs = QString::fromUtf8(myUserData->lastTextNode.c_str()).split(";");
                            QString oldRef; //the previous reference to use as a base for the next refs
                            for (QStringList::iterator it(refs.begin()); it != refs.end(); ++it) {

                                if (! oldRef.isEmpty() ) {
                                    options.refBase = oldRef; //use the last ref as a base, e.g. Rom 1,2-3, when the next ref is only 3:3-10
                                }
                                const QString completeRef( ReferenceManager::parseVerseReference((*it), options) );

                                oldRef = completeRef; //use the parsed result as the base for the next ref.

                                if (insertSemicolon) { //prepend a ref divider if we're after the first one
                                    buf.append("; ");
                                }

                                buf.append("<a href=\"");
                                buf.append(
                                    ReferenceManager::encodeHyperlink(
                                        mod->name(),
                                        completeRef,
                                        ReferenceManager::typeFromModule(mod->type())
                                    ).toUtf8().constData()
                                );

                                buf.append("\" crossrefs=\"");
                                buf.append((const char*)completeRef.toUtf8());
                                buf.append("\">");

                                buf.append((const char*)(*it).toUtf8());

                                buf.append("</a>");

                                insertSemicolon = true;
                            }
                            buf.append("</span>"); //crossref end
                        }

                        myUserData->suspendTextPassThru = false;
                    }
                }
                else if (tag.getAttribute("passage") ) { //the passage was given as a parameter value
                    myUserData->inscriptRef = true;
                    myUserData->suspendTextPassThru = false;

                    const char* ref = tag.getAttribute("passage");
                    Q_ASSERT(ref);

                    CSwordModuleInfo* mod = CBTConfig::get(CBTConfig::standardBible);
                    //Q_ASSERT(mod); tested later

                    ReferenceManager::ParseOptions options;
                    options.refBase = QString::fromUtf8(myUserData->key->getText());

                    options.sourceLanguage = myModule->Lang();
                    options.destinationLanguage = QString("en");

                    const QString completeRef = ReferenceManager::parseVerseReference(QString::fromUtf8(ref), options);

                    if (mod) {
                        options.refDestinationModule = QString(mod->name());
                        buf.append("<span class=\"crossreference\">");
                        buf.append("<a href=\"");
                        buf.append(
                            ReferenceManager::encodeHyperlink(
                                mod->name(),
                                completeRef,
                                ReferenceManager::typeFromModule(mod->type())
                            ).toUtf8().constData()
                        );
                        buf.append("\" crossrefs=\"");
                        buf.append((const char*)completeRef.toUtf8());
                        buf.append("\">");
                    }
                    else {
                        buf.append("<span><a>");
                    }
                }
                else if ( !tag.getAttribute("passage") ) { // we're starting a scripRef like "<scripRef>John 3:16</scripRef>"
                    myUserData->inscriptRef = false;

                    // let's stop text from going to output, the text get's added in the -tag handler
                    myUserData->suspendTextPassThru = true;
                }
            }
        }
        else if (tag.getName() && !sword::stricmp(tag.getName(), "div")) {
            if (tag.isEndTag()) {
                buf.append("</div>");
            }
            else if ( tag.getAttribute("class") && !sword::stricmp(tag.getAttribute("class"), "sechead") ) {
                buf.append("<div class=\"sectiontitle\">");
            }
            else if (tag.getAttribute("class") && !sword::stricmp(tag.getAttribute("class"), "title")) {
                buf.append("<div class=\"booktitle\">");
            }
        }
        else if (tag.getName() && !sword::stricmp(tag.getName(), "img") && tag.getAttribute("src")) {
            const char* value = tag.getAttribute("src");

            if (value[0] == '/') {
                value++; //strip the first /
            }

            buf.append("<img src=\"");
            QString absPath(QTextCodec::codecForLocale()->toUnicode(myUserData->module->getConfigEntry("AbsoluteDataPath")));
            QString relPath(QString::fromUtf8(value));
            QString url(QUrl::fromLocalFile(absPath.append('/').append(relPath)).toString());
            buf.append(url.toUtf8().data());
            buf.append("\" />");
        }
        else { // let unknown token pass thru
            return sword::ThMLHTML::handleToken(buf, token, userData);
        }
    }

    return true;
}
Ejemplo n.º 6
0
php_http_url_t *php_http_url_mod(const php_http_url_t *old_url, const php_http_url_t *new_url, unsigned flags TSRMLS_DC)
{
	php_http_url_t *tmp_url = NULL;
	php_http_buffer_t buf;

	php_http_buffer_init_ex(&buf, MAX(PHP_HTTP_BUFFER_DEFAULT_SIZE, sizeof(php_http_url_t)<<2), PHP_HTTP_BUFFER_INIT_PREALLOC);
	php_http_buffer_account(&buf, sizeof(php_http_url_t));
	memset(buf.data, 0, buf.used);

	/* set from env if requested */
	if (flags & PHP_HTTP_URL_FROM_ENV) {
		php_http_url_t *env_url = php_http_url_from_env(TSRMLS_C);

		old_url = tmp_url = php_http_url_mod(env_url, old_url, flags ^ PHP_HTTP_URL_FROM_ENV TSRMLS_CC);
		php_http_url_free(&env_url);
	}

	url_copy(scheme);

	if (!(flags & PHP_HTTP_URL_STRIP_USER)) {
		url_copy(user);
	}

	if (!(flags & PHP_HTTP_URL_STRIP_PASS)) {
		url_copy(pass);
	}
	
	url_copy(host);
	
	if (!(flags & PHP_HTTP_URL_STRIP_PORT)) {
		url(buf)->port = url_isset(new_url, port) ? new_url->port : ((old_url) ? old_url->port : 0);
	}

	if (!(flags & PHP_HTTP_URL_STRIP_PATH)) {
		if ((flags & PHP_HTTP_URL_JOIN_PATH) && url_isset(old_url, path) && url_isset(new_url, path) && *new_url->path != '/') {
			size_t old_path_len = strlen(old_url->path), new_path_len = strlen(new_url->path);
			char *path = ecalloc(1, old_path_len + new_path_len + 1 + 1);
			
			strcat(path, old_url->path);
			if (path[old_path_len - 1] != '/') {
				php_dirname(path, old_path_len);
				strcat(path, "/");
			}
			strcat(path, new_url->path);
			
			url(buf)->path = &buf.data[buf.used];
			if (path[0] != '/') {
				url_append(&buf, php_http_buffer_append(&buf, "/", 1));
			}
			url_append(&buf, php_http_buffer_append(&buf, path, strlen(path) + 1));
			efree(path);
		} else {
			const char *path = NULL;

			if (url_isset(new_url, path)) {
				path = new_url->path;
			} else if (url_isset(old_url, path)) {
				path = old_url->path;
			}

			if (path) {
				url(buf)->path = &buf.data[buf.used];

				url_append(&buf, php_http_buffer_append(&buf, path, strlen(path) + 1));
			}


		}
	}

	if (!(flags & PHP_HTTP_URL_STRIP_QUERY)) {
		if ((flags & PHP_HTTP_URL_JOIN_QUERY) && url_isset(new_url, query) && url_isset(old_url, query)) {
			zval qarr, qstr;
			
			INIT_PZVAL(&qstr);
			INIT_PZVAL(&qarr);
			array_init(&qarr);
			
			ZVAL_STRING(&qstr, old_url->query, 0);
			php_http_querystring_update(&qarr, &qstr, NULL TSRMLS_CC);
			ZVAL_STRING(&qstr, new_url->query, 0);
			php_http_querystring_update(&qarr, &qstr, NULL TSRMLS_CC);
			
			ZVAL_NULL(&qstr);
			php_http_querystring_update(&qarr, NULL, &qstr TSRMLS_CC);

			url(buf)->query = &buf.data[buf.used];
			url_append(&buf, php_http_buffer_append(&buf, Z_STRVAL(qstr), Z_STRLEN(qstr) + 1));

			zval_dtor(&qstr);
			zval_dtor(&qarr);
		} else {
			url_copy(query);
		}
	}

	if (!(flags & PHP_HTTP_URL_STRIP_FRAGMENT)) {
		url_copy(fragment);
	}
	
	/* done with copy & combine & strip */

	if (flags & PHP_HTTP_URL_FROM_ENV) {
		/* free old_url we tainted above */
		php_http_url_free(&tmp_url);
	}

	/* replace directory references if path is not a single slash */
	if ((flags & PHP_HTTP_URL_SANITIZE_PATH)
	&&	url(buf)->path[0] && url(buf)->path[1]) {
		char *ptr, *end = url(buf)->path + strlen(url(buf)->path) + 1;
			
		for (ptr = strchr(url(buf)->path, '/'); ptr; ptr = strchr(ptr, '/')) {
			switch (ptr[1]) {
				case '/':
					memmove(&ptr[1], &ptr[2], end - &ptr[2]);
					break;
					
				case '.':
					switch (ptr[2]) {
						case '\0':
							ptr[1] = '\0';
							break;

						case '/':
							memmove(&ptr[1], &ptr[3], end - &ptr[3]);
							break;

						case '.':
							if (ptr[3] == '/') {
								char *pos = &ptr[4];
								while (ptr != url(buf)->path) {
									if (*--ptr == '/') {
										break;
									}
								}
								memmove(&ptr[1], pos, end - pos);
								break;
							} else if (!ptr[3]) {
								/* .. at the end */
								ptr[1] = '\0';
							}
							/* no break */

						default:
							/* something else */
							++ptr;
							break;
					}
					break;

				default:
					++ptr;
					break;
			}
		}
	}
	/* unset default ports */
	if (url(buf)->port) {
		if (	((url(buf)->port == 80) && url(buf)->scheme && !strcmp(url(buf)->scheme, "http"))
			||	((url(buf)->port ==443) && url(buf)->scheme && !strcmp(url(buf)->scheme, "https"))
		) {
			url(buf)->port = 0;
		}
	}
	
	return url(buf);
}
Ejemplo n.º 7
0
String Location::origin() const
{
    if (!m_frame)
        return String();
    return SecurityOrigin::create(url())->toString();
}
Ejemplo n.º 8
0
void KobeMenu::forumHelp()
{
    QUrl url(QString("http://www.ubuntukylin.com/ukylin/forum.php"));
    QDesktopServices::openUrl(url);
}
Ejemplo n.º 9
0
void ViewHistoryWindow::initViewHtml()
{
	static const QString HtmlTemplate = 
		"<html><body> \
			<div style=\"position:absolute; left:50%; top:50%; width:18px; height:18px; margin:-9px 0 0 -9px; background: transparent url('%6') no-repeat;\"></div> \
Ejemplo n.º 10
0
void QgsNewHttpConnection::accept()
{
  QSettings settings;
  QString key = mBaseKey + txtName->text();
  QString credentialsKey = "/Qgis/" + mCredentialsBaseKey + '/' + txtName->text();

  // warn if entry was renamed to an existing connection
  if (( mOriginalConnName.isNull() || mOriginalConnName.compare( txtName->text(), Qt::CaseInsensitive ) != 0 ) &&
      settings.contains( key + "/url" ) &&
      QMessageBox::question( this,
                             tr( "Save connection" ),
                             tr( "Should the existing connection %1 be overwritten?" ).arg( txtName->text() ),
                             QMessageBox::Ok | QMessageBox::Cancel ) == QMessageBox::Cancel )
  {
    return;
  }

  if ( !txtPassword->text().isEmpty() &&
       QMessageBox::question( this,
                              tr( "Saving passwords" ),
                              tr( "WARNING: You have entered a password. It will be stored in plain text in your project files and in your home directory on Unix-like systems, or in your user profile on Windows. If you do not want this to happen, please press the Cancel button.\nNote: giving the password is optional. It will be requested interactivly, when needed." ),
                              QMessageBox::Ok | QMessageBox::Cancel ) == QMessageBox::Cancel )
  {
    return;
  }

  // on rename delete original entry first
  if ( !mOriginalConnName.isNull() && mOriginalConnName != key )
  {
    settings.remove( mBaseKey + mOriginalConnName );
    settings.remove( "/Qgis/" + mCredentialsBaseKey + '/' + mOriginalConnName );
    settings.sync();
  }

  QUrl url( txtUrl->text().trimmed() );
  const QList< QPair<QByteArray, QByteArray> > &items = url.encodedQueryItems();
  QHash< QString, QPair<QByteArray, QByteArray> > params;
  for ( QList< QPair<QByteArray, QByteArray> >::const_iterator it = items.constBegin(); it != items.constEnd(); ++it )
  {
    params.insert( QString( it->first ).toUpper(), *it );
  }

  if ( params["SERVICE"].second.toUpper() == "WMS" ||
       params["SERVICE"].second.toUpper() == "WFS" ||
       params["SERVICE"].second.toUpper() == "WCS" )
  {
    url.removeEncodedQueryItem( params["SERVICE"].first );
    url.removeEncodedQueryItem( params["REQUEST"].first );
    url.removeEncodedQueryItem( params["FORMAT"].first );
  }

  if ( url.encodedPath().isEmpty() )
  {
    url.setEncodedPath( "/" );
  }

  settings.setValue( key + "/url", url.toString() );
  if ( mBaseKey == "/Qgis/connections-wms/" || mBaseKey == "/Qgis/connections-wcs/" )
  {
    settings.setValue( key + "/ignoreGetMapURI", cbxIgnoreGetMapURI->isChecked() );
    settings.setValue( key + "/ignoreAxisOrientation", cbxIgnoreAxisOrientation->isChecked() );
    settings.setValue( key + "/invertAxisOrientation", cbxInvertAxisOrientation->isChecked() );
    settings.setValue( key + "/smoothPixmapTransform", cbxSmoothPixmapTransform->isChecked() );

    int dpiMode = 0;
    switch ( cmbDpiMode->currentIndex() )
    {
      case 0: // all => QGIS|UMN|GeoServer
        dpiMode = 7;
        break;
      case 1: // off
        dpiMode = 0;
        break;
      case 2: // QGIS
        dpiMode = 1;
        break;
      case 3: // UMN
        dpiMode = 2;
        break;
      case 4: // GeoServer
        dpiMode = 4;
        break;
    }

    settings.setValue( key + "/dpiMode", dpiMode );
  }
  if ( mBaseKey == "/Qgis/connections-wms/" )
  {
    settings.setValue( key + "/ignoreGetFeatureInfoURI", cbxIgnoreGetFeatureInfoURI->isChecked() );
  }

  settings.setValue( key + "/referer", txtReferer->text() );

  settings.setValue( credentialsKey + "/username", txtUserName->text() );
  settings.setValue( credentialsKey + "/password", txtPassword->text() );

  settings.setValue( credentialsKey + "/authcfg", mAuthConfigSelect->configId() );

  settings.setValue( mBaseKey + "/selected", txtName->text() );

  QDialog::accept();
}
Ejemplo n.º 11
0
	void CustomWebView::handleLoadFinished ()
	{
		remakeURL (url ());
	}
Ejemplo n.º 12
0
 virtual void fire(Frame* frame)
 {
     UserGestureIndicator gestureIndicator(wasUserGesture() ? DefinitelyProcessingUserGesture : DefinitelyNotProcessingUserGesture);
     frame->loader()->changeLocation(securityOrigin(), KURL(ParsedURLString, url()), referrer(), lockHistory(), lockBackForwardList(), true);
 }
Ejemplo n.º 13
0
 virtual void fire(Frame* frame)
 {
     UserGestureIndicator gestureIndicator(wasUserGesture() ? DefinitelyProcessingUserGesture : DefinitelyNotProcessingUserGesture);
     bool refresh = equalIgnoringFragmentIdentifier(frame->document()->url(), KURL(ParsedURLString, url()));
     frame->loader()->changeLocation(securityOrigin(), KURL(ParsedURLString, url()), referrer(), lockHistory(), lockBackForwardList(), refresh);
 }
Ejemplo n.º 14
0
bool REventHandler::isUrl(const QString& urlString) {
    QUrl url(urlString);
    QString scheme = url.scheme();
    return scheme=="file" || scheme=="http" || scheme=="https" || scheme=="ftp";
}
Ejemplo n.º 15
0
bool Method::execute() {

    if (!prepare())
        return false;

    if (!validate())
        return false;


    // THese are always constant with API requests
    if (getMethodName().startsWith("fql.query",Qt::CaseInsensitive))
        m_argMap.insert("method","fql.query");
    else if (getMethodName().startsWith("fql.multiquery",Qt::CaseInsensitive))
        m_argMap.insert("method","fql.multiquery");
    else
        m_argMap.insert("method", getMethodName());

    m_argMap.insert("api_key", m_userInfo->getApiKey());
    m_argMap.insert("v","1.0");
    m_argMap.insert("session_key",m_userInfo->getSessionKey());

    // This is going to have to be changed to something with greater than
    // second resolution (miliseconds or microseconds). Is there anything portable across
    // Mac/Win/Linux? Doubtful, have to build compile options for it.
    time_t tm = time(0);
    //char callId[30];
    //sprintf(callId, "%lld", tm);
    m_argMap.insert("call_id",(qlonglong)tm);


    // pull all the key/value pairs from the QMap and do the magic Facebook requires to
    // make an API call

    /********** From the Facebook API docs ****************************************
    The signature can be generated by calling generate_sig in facebook.php.
    generate_sig takes two parameters: an array of arg=val pairs and your app secret.
    The signature can also be constructed using the following algorithm
    (after all the other arguments have been determined):

    args = array of args to the request, not counting sig, formatted in non-urlencoded arg=val pairs
    sorted_array = alphabetically_sort_array_by_keys(args);
    request_str = concatenate_in_order(sorted_array);
    signature = md5(concatenate(request_str, secret))
    ***********************************************************************************/

    // In a way, this is really retarded. Facebook wants an MD5 hash of the args with no
    // serparators. You also need a set of args with '&' separated url encoded
    // key/value pairs for the actual post

    QByteArray sigByteArray;
    QByteArray postArgs;

    // QMap is automatically sorted by keys
    QMapIterator<QString, QVariant> i(m_argMap);
    while (i.hasNext()) {
         i.next();
         sigByteArray.append(i.key() + "=" + i.value().toString() );
         postArgs.append(i.key() + "=" + i.value().toString() + "&");
    }

    sigByteArray.append(m_userInfo->getSecret());

    QByteArray sig = QCryptographicHash::hash(sigByteArray,QCryptographicHash::Md5 );

    postArgs.append("sig=");
    postArgs.append(sig.toHex());

    QByteArray exclude("&=");
    QByteArray include;
    postArgs = postArgs.toPercentEncoding(exclude,include,'%');

    // qDebug() << postArgs;

    QUrl url("http://api.facebook.com/restserver.php");

    QNetworkRequest nr;
    nr.setUrl(url);
    nr.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

    m_reply = m_manager->post(nr,postArgs);

    if (m_reply != 0) {
        connect(m_manager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(gotReply(QNetworkReply*)));
        return true;
    }
Ejemplo n.º 16
0
void CachedImage::checkShouldPaintBrokenImage()
{
    if (!m_loader || m_loader->reachedTerminalState())
        return;

    m_shouldPaintBrokenImage = m_loader->frameLoader()->client().shouldPaintBrokenImage(url());
}
Ejemplo n.º 17
0
int wmain(int argc, wchar_t* argv[])
{
	//::MessageBox(NULL, L"Stop here", L"STOP!", MB_ICONWARNING | MB_CANCELTRYCONTINUE | MB_DEFBUTTON3);

	std:cout << "Edge Diagnostics Adapter" << std::endl;

	po::options_description desc("Allowed options");
	desc.add_options()
		("help,h", "Prints this help text.")
		("launch,l", po::value<string>(), "Launches Edge. Optionally at the URL specified in the value")
		("killall,k", "Kills all running Edge processes.")
		("chrome,c", "Launches Crhome in the background to serve the Chrome Developer Tools frontend.")
		("port,p", po::value<string>(), "The port number to listen on. Default is 9222.");

	po::variables_map vm;
	try
	{
		po::store(po::parse_command_line(argc, argv, desc), vm);
	}
	catch (po::error& e)
	{
		std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
		std::cerr << desc << std::endl;
		return E_FAIL;
	}

	if (vm.count("help"))
	{
		std::cout << desc << std::endl;
		return S_OK;
	}


	// Initialize COM and deinitialize when we go out of scope
	HRESULT hrCoInit = ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);

	shared_ptr<HRESULT> spCoInit(&hrCoInit, [](const HRESULT* hrCom) -> void { if (SUCCEEDED(*hrCom)) { ::CoUninitialize(); } });
	{
		// Set a close handler to shutdown the chrome instance we launch
		::SetConsoleCtrlHandler(OnClose, TRUE);

		// Launch chrome
		if (vm.count("chrome"))
		{
			CString chromePath;

			// Find the chrome install location via the registry
			CString keyPath = L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe";

			CRegKey regKey;

			// First see if we can find where Chrome is installed from the registry. This will only succeed if Chrome is installed for all users
			if (regKey.Open(HKEY_LOCAL_MACHINE, keyPath, KEY_READ) == ERROR_SUCCESS)
			{
				ULONG bufferSize = MAX_PATH;
				CString path;
				LRESULT result = regKey.QueryStringValue(nullptr, path.GetBufferSetLength(bufferSize), &bufferSize);
				path.ReleaseBufferSetLength(bufferSize);
				if (result == ERROR_SUCCESS)
				{
					chromePath = path;
				}
			}

			if (chromePath.GetLength() == 0)
			{
				// If Chrome is only installed for the current user, look in \AppData\Local\Google\Chrome\Application\ for Chrome.exe
				CString appPath;
				::SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, appPath.GetBuffer(MAX_PATH + 1));
				appPath.ReleaseBuffer();
				chromePath = appPath + L"\\Google\\Chrome\\Application\\chrome.exe";
			}

			// Get a temp location
			CString temp;
			Helpers::ExpandEnvironmentString(L"%Temp%", temp);

			// Set arguments for the chrome that we launch
			CString arguments;
			arguments.Format(L"about:blank --remote-debugging-port=9223 --window-size=0,0 --silent-launch --no-first-run --no-default-browser-check --user-data-dir=\"%s\"", temp);

			// Launch the process
			STARTUPINFO si = { 0 };
			PROCESS_INFORMATION pi = { 0 };
			si.cb = sizeof(si);
			si.wShowWindow = SW_MINIMIZE;

			BOOL result = ::CreateProcess(
				chromePath,
				arguments.GetBuffer(),
				nullptr,
				nullptr,
				FALSE,
				0,
				nullptr,
				temp,
				&si,
				&pi);
			arguments.ReleaseBuffer();

			if (result)
			{
				// Store the handles
				CHandle hThread(pi.hThread);
				hChromeProcess.Attach(pi.hProcess);
				DWORD waitResult = ::WaitForInputIdle(hChromeProcess, 30000);
			}
			else
			{
				std::cerr << "Could not open Chrome. Please ensure that Chrome is installed." << std::endl;
				system("pause");
				return -1;
			}
		}

		// Kill all Edge instances if their is an aegument /killall
		if (vm.count("killall"))
		{
			//killAllProcessByExe(L"MicrosoftEdgeCP.exe");
			Helpers::KillAllProcessByExe(L"MicrosoftEdge.exe");
		}

		// Launch Edge if their is an argument set /launch:<url>
		if (vm.count("launch"))
		{
			CString url(vm["launch"].as<string>().c_str());
			if (url.GetLength() == 0)
			{
				url = L"https://www.bing.com";
			}

			HRESULT hr = Helpers::OpenUrlInMicrosoftEdge(url);

			if (FAILED(hr))
			{
				std::cout << L"Failed to launch Microsoft Edge";
			}
		}

		string port = EdgeDiagnosticsAdapter::s_Default_Port;
		if (vm.count("port"))
		{
			port = vm["port"].as<string>();
		}

		// We don't care if this fails as the developer can set it manually.
		setSecurityACLs();

		// We don't care if this fails or not as maybe the developer wants to do something that won't hit the PLM. In case errors went to the console.
		setEdgeForDebugging(true);

		// Load the proxy server
		EdgeDiagnosticsAdapter proxy(getPathToCurrentExeContainer(), port);

		if (proxy.IsServerRunning)
		{

			// Create a message pump
			MSG msg;
			::PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);

			// Thread message loop
			BOOL getMessageRet;
			while ((getMessageRet = ::GetMessage(&msg, NULL, 0, 0)) != 0)
			{
				if (getMessageRet != -1)
				{
					::TranslateMessage(&msg);
					::DispatchMessage(&msg);
				}
			}

			// Leave the window open so we can read the log file
			wcout << endl << L"Press [ENTER] to exit." << endl;
			cin.ignore();
		}
		else
		{
			wcout << L"Error starting. Quiting.";
			return E_FAIL;
		}
	}

	return S_OK;
}
Ejemplo n.º 18
0
int main()
{
  //string url("http://www.amazon.com/");
  std::string a("http://www.amazon.com/Turtle-Beach-Call-Duty-Playstation-3/");
  std::string b("dp/B005EEMYCO/ref=sr_1_7?ie=UTF8&qid=1329798456&sr=8-7");
  //std::string a("http://www.amazon.com/dp/B002GYWHSQ/?tag=googhydr-");
  //std::string b("20&hvadid=16413069595&ref=pd_sl_1gtlqzgaj7_b");
  std::string c = a.append(b);
  //std::string c("http://eng.utah.edu/~ccurtis/page1.html");
  std::string url(c);
            
  std::string filename ("words.txt");
  Dictionary dic(filename);

  RateLimiter limiter(8);

  /* DEBUG */
  printf("Calling Map!\n");

  Page *page =  Map(url, limiter, dic);
  //Page page = Map(url, dic);

  //printf("Page URL: %s\n", page.Url().c_str());
  printf("<<Map has Finished Running>>\n");


  std::vector<std::string> links = page->GetLinks();

  //std::vector<string>::iterator it;
  //cout << "Links: \n \n" << endl;
  //for (it = links.begin(); it < links.end(); ++it)
    //cout << "link ~ " <<  *it << "\n\n" << endl;


  /* Set up Page's Histogram */
  Word_Count *histogram = page->GetHistogram();
      // Print the Histogram
  printf("Page has %i total English words!\n", histogram->NumberOfWords());
  std::vector<std::string> words = histogram->GetWords();
  printf("There are %i misspellings!\n", 
	 page->GetMisspellings()->NumberOfWords());

 
  std::vector<AmazonCustomer> customers = page->GetReviewers();

  std::vector<AmazonCustomer>::iterator it;
  std::vector<std::pair <double, double> >::iterator it2;
  printf("\nPage has %i images\n\n", page->GetImageCount());
  printf("\nReviewers: \n\n");
  double x;
  std::vector <std::pair <double, double> > pairs;
  for (it = customers.begin(); it < customers.end(); ++it)
    {
      x = ((double)(*it).length_of_reviews/(*it).number_of_reviews);
      printf(" ~ %s\n", (*it).name.c_str());
      printf("Total Words = %i\n", (*it).length_of_reviews);
      printf("Has %i total reviews.\n", (*it).number_of_reviews);
      printf("With an average review length of %f words.\n", x);
      printf("And %i misspellings.\n\n", (*it).misspellings_count);

      printf("Max Review Length of %i\n", (*it).max_review_length);

      pairs = (*it).stars_cost;
      int j = 0;
      for (it2 = pairs.begin(); it2 < pairs.end(); ++it2)
	{
	  printf("(Stars, Cost) = (%f, %f)\n",
		 pairs.at(j).first, pairs.at(j).second);
	  j += 1;
	}
    }



  return 0;
}
Ejemplo n.º 19
0
static php_http_url_t *php_http_url_from_env(TSRMLS_D)
{
	zval *https, *zhost, *zport;
	long port;
	php_http_buffer_t buf;

	php_http_buffer_init_ex(&buf, MAX(PHP_HTTP_BUFFER_DEFAULT_SIZE, sizeof(php_http_url_t)<<2), PHP_HTTP_BUFFER_INIT_PREALLOC);
	php_http_buffer_account(&buf, sizeof(php_http_url_t));
	memset(buf.data, 0, buf.used);

	/* scheme */
	url(buf)->scheme = &buf.data[buf.used];
	https = php_http_env_get_server_var(ZEND_STRL("HTTPS"), 1 TSRMLS_CC);
	if (https && !strcasecmp(Z_STRVAL_P(https), "ON")) {
		php_http_buffer_append(&buf, "https", sizeof("https"));
	} else {
		php_http_buffer_append(&buf, "http", sizeof("http"));
	}

	/* host */
	url(buf)->host = &buf.data[buf.used];
	if ((((zhost = php_http_env_get_server_var(ZEND_STRL("HTTP_HOST"), 1 TSRMLS_CC)) ||
			(zhost = php_http_env_get_server_var(ZEND_STRL("SERVER_NAME"), 1 TSRMLS_CC)) ||
			(zhost = php_http_env_get_server_var(ZEND_STRL("SERVER_ADDR"), 1 TSRMLS_CC)))) && Z_STRLEN_P(zhost)) {
		size_t stop_at = strspn(Z_STRVAL_P(zhost), "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-.");

		php_http_buffer_append(&buf, Z_STRVAL_P(zhost), stop_at);
		php_http_buffer_append(&buf, "", 1);
	} else {
		char *host_str = localhostname();

		php_http_buffer_append(&buf, host_str, strlen(host_str) + 1);
		efree(host_str);
	}

	/* port */
	zport = php_http_env_get_server_var(ZEND_STRL("SERVER_PORT"), 1 TSRMLS_CC);
	if (zport && IS_LONG == is_numeric_string(Z_STRVAL_P(zport), Z_STRLEN_P(zport), &port, NULL, 0)) {
		url(buf)->port = port;
	}

	/* path */
	if (SG(request_info).request_uri && SG(request_info).request_uri[0]) {
		const char *q = strchr(SG(request_info).request_uri, '?');

		url(buf)->path = &buf.data[buf.used];

		if (q) {
			php_http_buffer_append(&buf, SG(request_info).request_uri, q - SG(request_info).request_uri);
			php_http_buffer_append(&buf, "", 1);
		} else {
			php_http_buffer_append(&buf, SG(request_info).request_uri, strlen(SG(request_info).request_uri) + 1);
		}
	}

	/* query */
	if (SG(request_info).query_string && SG(request_info).query_string[0]) {
		url(buf)->query = &buf.data[buf.used];
		php_http_buffer_append(&buf, SG(request_info).query_string, strlen(SG(request_info).query_string) + 1);
	}

	return url(buf);
}
Ejemplo n.º 20
0
    /**
     * @param s URL string to be parsed into its components.
     *
     * @param ec Error code set to indicate the reason for failure, if any.
     *
     * @returns A @c url object corresponding to the specified string.
     */
    static url from_string(const char* s, boost::system::error_code& ec)
    {
        url new_url;

        // Protocol.
        std::size_t length = std::strcspn(s, ":");
        new_url.protocol_.assign(s, s + length);
        for (std::size_t i = 0; i < new_url.protocol_.length(); ++i)
            new_url.protocol_[i] = std::tolower(new_url.protocol_[i]);
        s += length;

        // "://".
        if (*s++ != ':')
        {
            ec = make_error_code(boost::system::errc::invalid_argument);
            return url();
        }
        if (*s++ != '/')
        {
            ec = make_error_code(boost::system::errc::invalid_argument);
            return url();
        }
        if (*s++ != '/')
        {
            ec = make_error_code(boost::system::errc::invalid_argument);
            return url();
        }

        // UserInfo.
        length = std::strcspn(s, "@:[/?#");
        if (s[length] == '@')
        {
            new_url.user_info_.assign(s, s + length);
            s += length + 1;
        }
        else if (s[length] == ':')
        {
            std::size_t length2 = std::strcspn(s + length, "@/?#");
            if (s[length + length2] == '@')
            {
                new_url.user_info_.assign(s, s + length + length2);
                s += length + length2 + 1;
            }
        }

        // Host.
        if (*s == '[')
        {
            length = std::strcspn(++s, "]");
            if (s[length] != ']')
            {
                ec = make_error_code(boost::system::errc::invalid_argument);
                return url();
            }
            new_url.host_.assign(s, s + length);
            new_url.ipv6_host_ = true;
            s += length + 1;
            if (std::strcspn(s, ":/?#") != 0)
            {
                ec = make_error_code(boost::system::errc::invalid_argument);
                return url();
            }
        }
        else
        {
            length = std::strcspn(s, ":/?#");
            new_url.host_.assign(s, s + length);
            s += length;
        }

        // Port.
        if (*s == ':')
        {
            length = std::strcspn(++s, "/?#");
            if (length == 0)
            {
                ec = make_error_code(boost::system::errc::invalid_argument);
                return url();
            }
            new_url.port_.assign(s, s + length);
            for (std::size_t i = 0; i < new_url.port_.length(); ++i)
            {
                if (!std::isdigit(new_url.port_[i]))
                {
                    ec = make_error_code(boost::system::errc::invalid_argument);
                    return url();
                }
            }
            s += length;
        }

        // Path.
        if (*s == '/')
        {
            length = std::strcspn(s, "?#");
            new_url.path_.assign(s, s + length);
            std::string tmp_path;
            if (!detail::unescape_path(new_url.path_, tmp_path))
            {
                // ec = make_error_code(boost::system::errc::invalid_argument);
                // return url();
            }
            s += length;
        }
        else
            new_url.path_ = "/";

        // Query.
        if (*s == '?')
        {
            length = std::strcspn(++s, "#");
            new_url.query_.assign(s, s + length);
            s += length;
        }

        // Fragment.
        if (*s == '#')
            new_url.fragment_.assign(++s);

        ec = boost::system::error_code();
        return new_url;
    }
Ejemplo n.º 21
0
void CompilersDetectorManager::MSWSuggestToDownloadMinGW(bool prompt)
{
#ifdef __WXMSW__
    if(!prompt ||
       ::wxMessageBox(_("Could not locate any MinGW compiler installed on your machine, would you like to "
                        "install one now?"),
                      "CodeLite",
                      wxYES_NO | wxCANCEL | wxYES_DEFAULT | wxCENTER | wxICON_QUESTION) == wxYES) {
        // No MinGW compiler detected!, offer the user to download one
        wxStringMap_t mingwCompilers;
        wxArrayString options;

        // Load the compilers list from the website
        wxURL url("http://codelite.org/compilers.json");

        if(url.GetError() == wxURL_NOERR) {

            wxInputStream* in_stream = url.GetInputStream();
            if(!in_stream) {
                return;
            }
            unsigned char buffer[DLBUFSIZE + 1];
            wxString dataRead;
            do {
                in_stream->Read(buffer, DLBUFSIZE);
                size_t bytes_read = in_stream->LastRead();
                if(bytes_read > 0) {
                    buffer[bytes_read] = 0;
                    wxString buffRead((const char*)buffer, wxConvUTF8);
                    dataRead.Append(buffRead);
                }

            } while(!in_stream->Eof());

            JSONRoot root(dataRead);
            JSONElement compilers = root.toElement().namedObject("Compilers");
            JSONElement arr = compilers.namedObject("MinGW");
            int count = arr.arraySize();
            for(int i = 0; i < count; ++i) {
                JSONElement compiler = arr.arrayItem(i);
                mingwCompilers.insert(
                    std::make_pair(compiler.namedObject("Name").toString(), compiler.namedObject("URL").toString()));
                options.Add(compiler.namedObject("Name").toString());
            }

            if(options.IsEmpty()) {
                ::wxMessageBox(_("Unable to fetch compilers list from the website\nhttp://codelite.org/compilers.json"),
                               "CodeLite",
                               wxOK | wxCENTER | wxICON_WARNING);
                return;
            }
            int sel = 0;

            wxString selection =
                ::wxGetSingleChoice(_("Select a compiler to download"), _("Choose compiler"), options, sel);
            if(!selection.IsEmpty()) {
                // Reset the compiler detection flag so next time codelite is restarted, it will
                // rescan the machine
                clConfig::Get().Write(kConfigBootstrapCompleted, false);

                // Open the browser to start downloading the compiler
                ::wxLaunchDefaultBrowser(mingwCompilers.find(selection)->second);
                ::wxMessageBox(_("After install is completed, click the 'Scan' button"),
                               "CodeLite",
                               wxOK | wxCENTER | wxICON_INFORMATION);
            }
        }
    }

#endif // __WXMSW__
}
Ejemplo n.º 22
0
void RichTextHtmlEdit::insertFromMimeData(const QMimeData *source) {
	QString uri;
	QString title;
	QRegExp newline(QLatin1String("[\\r\\n]"));

#ifndef QT_NO_DEBUG
	qWarning() << "RichTextHtmlEdit::insertFromMimeData" << source->formats();
	foreach(const QString &format, source->formats())
		qWarning() << format << decodeMimeString(source->data(format));
#endif

	if (source->hasImage()) {
		QImage img = qvariant_cast<QImage>(source->imageData());
		QString html = Log::imageToImg(img);
		if (! html.isEmpty())
			insertHtml(html);
		return;
	}

	QString mozurl = decodeMimeString(source->data(QLatin1String("text/x-moz-url")));
	if (! mozurl.isEmpty()) {
		QStringList lines = mozurl.split(newline);
		qWarning() << mozurl << lines;
		if (lines.count() >= 2) {
			uri = lines.at(0);
			title = lines.at(1);
		}
	}

	if (uri.isEmpty())
		uri = decodeMimeString(source->data(QLatin1String("text/x-moz-url-data")));
	if (title.isEmpty())
		title = decodeMimeString(source->data(QLatin1String("text/x-moz-url-desc")));

	if (uri.isEmpty()) {
		QStringList urls;
#ifdef Q_OS_WIN
		urls = decodeMimeString(source->data(QLatin1String("application/x-qt-windows-mime;value=\"UniformResourceLocatorW\""))).split(newline);
		if (urls.isEmpty())
#endif
			urls = decodeMimeString(source->data(QLatin1String("text/uri-list"))).split(newline);
		if (! urls.isEmpty())
			uri = urls.at(0);
		uri = urls.at(0).trimmed();
	}

	if (uri.isEmpty()) {
		QUrl url(source->text(), QUrl::StrictMode);
		if (url.isValid() && ! url.isRelative()) {
			uri = url.toString();
		}
	}

#ifdef Q_OS_WIN
	if (title.isEmpty() && source->hasFormat(QLatin1String("application/x-qt-windows-mime;value=\"FileGroupDescriptorW\""))) {
		QByteArray qba = source->data(QLatin1String("application/x-qt-windows-mime;value=\"FileGroupDescriptorW\""));
		if (qba.length() == sizeof(FILEGROUPDESCRIPTORW)) {
			const FILEGROUPDESCRIPTORW *ptr = reinterpret_cast<const FILEGROUPDESCRIPTORW *>(qba.constData());
			title = QString::fromWCharArray(ptr->fgd[0].cFileName);
			if (title.endsWith(QLatin1String(".url"), Qt::CaseInsensitive))
				title = title.left(title.length() - 4);
		}
	}
#endif

	if (! uri.isEmpty()) {
		if (title.isEmpty())
			title = uri;
		uri = Qt::escape(uri);
		title = Qt::escape(title);

		insertHtml(QString::fromLatin1("<a href=\"%1\">%2</a>").arg(uri, title));
		return;
	}

	QString html = decodeMimeString(source->data(QLatin1String("text/html")));
	if (! html.isEmpty()) {
		insertHtml(html);
		return;
	}

	QTextEdit::insertFromMimeData(source);
}
Ejemplo n.º 23
0
int main(int argc, char **argv)
{
#if (QT_VERSION < 0x050200)
        #error("You need Qt 5.2.0 or later to compile Actiona Executer");
#endif

#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
    QtSingleApplication app("actiona-exec", argc, argv);
#else
    ActionTools::NativeEventFilteringApplication app("actiona-exec", argc, argv);
#endif
	app.setQuitOnLastWindowClosed(false);

	qAddPostRoutine(cleanup);

	qsrand(std::time(NULL));

#ifdef Q_OS_LINUX
    notify_init("Actiona executer");
#endif

#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
    QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
#endif

    QxtCommandOptions preOptions;

    preOptions.add("portable", QObject::tr("starts in portable mode, storing the settings in the executable folder"));
    preOptions.alias("portable", "p");
    preOptions.parse(QCoreApplication::arguments());

    if(preOptions.count("portable") > 0)
    {
        QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, QApplication::applicationDirPath() + "/userSettings");
        QSettings::setPath(QSettings::IniFormat, QSettings::SystemScope, QApplication::applicationDirPath() + "/systemSettings");
        QSettings::setDefaultFormat(QSettings::IniFormat);
    }

    QString locale = Tools::locale();

    Tools::installQtTranslator(locale);
    Tools::installTranslator("tools", locale);
    Tools::installTranslator("actiontools", locale);
    Tools::installTranslator("executer", locale);
    Tools::installTranslator("actexecuter", locale);

    const QStringList &arguments = QCoreApplication::arguments();

    QxtCommandOptions options;
    options.setFlagStyle(QxtCommandOptions::DoubleDash);
    options.setScreenWidth(0);
    options.add("code", QObject::tr("switch to code mode, may not be used with -s"));
    options.alias("code", "c");
    options.add("script", QObject::tr("switch to script mode, may not be used with -c"));
    options.alias("script", "s");
    options.add("nocodeqt", QObject::tr("do not include the Qt library into the code"));
    options.alias("nocodeqt", "Q");
    options.add("portable", QObject::tr("starts in portable mode, storing the settings in the executable folder"));
    options.alias("portable", "p");
    options.add("proxy-mode", QObject::tr("sets the proxy mode, values are \"none\", \"system\" (default) or \"custom\""));
    options.add("proxy-type", QObject::tr("sets the custom proxy type, values are \"http\" or \"socks\" (default)"));
    options.add("proxy-host", QObject::tr("sets the custom proxy host"));
    options.add("proxy-port", QObject::tr("sets the custom proxy port"));
    options.add("proxy-user", QObject::tr("sets the custom proxy user"));
    options.add("proxy-password", QObject::tr("sets the custom proxy password"));
#ifdef Q_OS_WIN
    options.add("console", QObject::tr("create a console to see debug output"));
    options.add("pause-at-end", QObject::tr("wait for user input at the end of the execution, used only with --console"));
#endif
    options.add("version", QObject::tr("show the program version"));
    options.alias("version", "v");
    options.add("help", QObject::tr("show this help text"));
    options.alias("help", "h");
    options.parse(arguments);

#ifdef Q_OS_WIN
    if(options.count("console"))
    {
        createConsole();

        if(options.count("pause-at-end"))
            qAddPostRoutine(pause);
    }
#endif

	qRegisterMetaType<ActionTools::ActionInstance>("ActionInstance");
	qRegisterMetaType<ActionTools::ActionException::Exception>("Exception");
	qRegisterMetaType<ActionTools::Parameter>("Parameter");
	qRegisterMetaType<ActionTools::SubParameter>("SubParameter");
	qRegisterMetaType<Tools::Version>("Version");

	qRegisterMetaTypeStreamOperators<ActionTools::ActionInstance>("ActionInstance");
	qRegisterMetaTypeStreamOperators<ActionTools::Parameter>("Parameter");
	qRegisterMetaTypeStreamOperators<ActionTools::SubParameter>("SubParameter");
	qRegisterMetaTypeStreamOperators<Tools::Version>("Version");

	if(options.count("version"))
	{
		QTextStream stream(stdout);
        stream << "Actiona Executer version " << Global::ACTIONA_VERSION.toString() << ", script version " << Global::SCRIPT_VERSION.toString() << "\n";
		stream.flush();
		return 0;
	}
	if(options.count("help") || options.showUnrecognizedWarning() || options.positional().count() < 1 || (options.count("code") && options.count("script")))
	{
		QTextStream stream(stdout);
		stream << QObject::tr("usage: ") << QCoreApplication::arguments().at(0) << " " << QObject::tr("[parameters]") << " " << QObject::tr("filename") << "\n";
		stream << QObject::tr("Parameters are:") << "\n";
		stream << options.getUsage();
		stream.flush();
		return -1;
	}

	app.addLibraryPath(QApplication::applicationDirPath() + "/actions");
	app.addLibraryPath(QApplication::applicationDirPath() + "/plugins");

	if(!options.count("nocodeqt"))
		app.addLibraryPath(QApplication::applicationDirPath() + "/code");

#ifdef Q_OS_LINUX
	{
#ifdef ACT_PROFILE
		Tools::HighResolutionTimer timer("Load key codes");
#endif
		ActionTools::KeySymHelper::loadKeyCodes();
	}
#endif

	// Proxy settings
	int proxyMode = ActionTools::Settings::PROXY_SYSTEM;
	if(options.value("proxy-mode").toString() == "none")
		proxyMode = ActionTools::Settings::PROXY_NONE;
	else if(options.value("proxy-mode").toString() == "custom")
		proxyMode = ActionTools::Settings::PROXY_CUSTOM;
	else if(options.value("proxy-mode").toString() == "system")
		proxyMode = ActionTools::Settings::PROXY_SYSTEM;
	else if(!options.value("proxy-mode").toString().isEmpty())
	{
		QTextStream stream(stdout);
		stream << QObject::tr("Unknown proxy mode, values are \"none\", \"system\" (default) or \"custom\"") << "\n";
		stream.flush();
		return -1;
	}

	QNetworkProxy proxy;

	switch(proxyMode)
	{
	case ActionTools::Settings::PROXY_NONE:
		proxy.setType(QNetworkProxy::NoProxy);
		break;
	case ActionTools::Settings::PROXY_SYSTEM:
		{
			QUrl url(Global::CONNECTIVITY_URL);
			QNetworkProxyQuery networkProxyQuery(url);
			QList<QNetworkProxy> listOfProxies = QNetworkProxyFactory::systemProxyForQuery(networkProxyQuery);
			if(!listOfProxies.isEmpty())
				proxy = listOfProxies.first();
			else
				proxy.setType(QNetworkProxy::NoProxy);
		}
		break;
	case ActionTools::Settings::PROXY_CUSTOM:
		{
			int type = ActionTools::Settings::PROXY_TYPE_SOCKS5;
			if(options.value("proxy-type").toString() == "http")
				type = ActionTools::Settings::PROXY_TYPE_HTTP;
			else if(options.value("proxy-type").toString() == "socks")
				type = ActionTools::Settings::PROXY_TYPE_SOCKS5;
			else if(!options.value("proxy-type").toString().isEmpty())
			{
				QTextStream stream(stdout);
				stream << QObject::tr("Unknown proxy type, values are \"http\" or \"socks\" (default)") << "\n";
				stream.flush();
				return -1;
			}

			QNetworkProxy proxy;

			if(type == ActionTools::Settings::PROXY_TYPE_HTTP)
				proxy.setType(QNetworkProxy::HttpProxy);
			else
				proxy.setType(QNetworkProxy::Socks5Proxy);

			proxy.setHostName(options.value("proxy-host").toString());
			proxy.setPort(options.value("proxy-port").toInt());
			proxy.setUser(options.value("proxy-user").toString());
			proxy.setPassword(options.value("proxy-password").toString());
		}
		break;
	}

	QNetworkProxy::setApplicationProxy(proxy);

	QUrl protocolUrl = QUrl::fromEncoded(arguments.at(1).toUtf8());
    if(protocolUrl.isValid() && protocolUrl.scheme() != "actiona")
		protocolUrl = QUrl();

	MainClass::ExecutionMode executionMode = MainClass::Unknown;
	MainClass mainClass;

	if(protocolUrl.isValid())
	{
		QString mode;
        using QStringPair = QPair<QString, QString>;
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
        for(const QStringPair &queryItem: QUrlQuery(protocolUrl.query()).queryItems())
#else
        for(const QStringPair &queryItem: protocolUrl.queryItems())
#endif
		{
			if(queryItem.first == "mode")
			{
				mode = queryItem.second;
				break;
			}
		}

		if(mode == "code")
			executionMode = MainClass::Code;
		else if(mode == "script")
			executionMode = MainClass::Script;
		else
		{
			if(protocolUrl.path().endsWith(".ascr"))
				executionMode = MainClass::Script;
			else if(protocolUrl.path().endsWith(".acod"))
				executionMode = MainClass::Code;
			else
			{
				QTextStream stream(stdout);
				stream << QObject::tr("Unknown execution mode, please specify mode=script or mode=code") << "\n";
				stream.flush();
				return -1;
			}
		}

		if(!mainClass.start(executionMode, protocolUrl))
			return -1;
	}
	else
	{
		QString filename = options.positional().at(0);

		if(options.count("code"))
			executionMode = MainClass::Code;
		else if(options.count("script"))
			executionMode = MainClass::Script;
		else
		{
			if(filename.endsWith(".ascr"))
				executionMode = MainClass::Script;
			else if(filename.endsWith(".acod"))
				executionMode = MainClass::Code;
			else
			{
				QTextStream stream(stdout);
				stream << QObject::tr("Unknown execution mode, please specify -s (script) or -c (code)") << "\n";
				stream.flush();
				return -1;
			}
		}

		QFile file(filename);
		if(!file.open(QIODevice::ReadOnly))
		{
			QTextStream stream(stdout);
			stream << QObject::tr("Unable to read input file") << "\n";
			stream.flush();
			return -1;
		}

		if(!mainClass.start(executionMode, &file, file.fileName()))
		{
			file.close();

			return -1;
		}
	}

	return app.exec();
}
Ejemplo n.º 24
0
Load::Load(QObject *parent) : QObject(parent), d_ptr(new LoadPrivate(this))
{
	Q_D(Load);
	ins = this;
	setObjectName("Load");

	auto avProcess = [this](QNetworkReply *reply){
		Q_D(Load);
		Task &task = d->queue.head();
		int sharp = task.code.indexOf(QRegularExpression("[#_]"));
		switch (task.state){
		case None:
		{
			QString i = task.code.mid(2, sharp - 2);
			QString p = sharp == -1 ? QString() : task.code.mid(sharp + 1);
			QString url("http://www.%1/video/av%2/");
			url = url.arg(Utils::customUrl(Utils::Bilibili)).arg(i);
			if (!p.isEmpty()){
				url += QString("index_%1.html").arg(p);
			}
			forward(QNetworkRequest(url), Page);
			break;
		}
		case Page:
		{
			d->model->clear();
			QString api, id, video(reply->readAll());
			int part = video.indexOf("<select");
			if (part != -1 && sharp == -1){
				QRegularExpression r("(?<=>).*?(?=</option>)");
				QStringRef list(&video, part, video.indexOf("</select>", part) - part);
				QRegularExpressionMatchIterator i = r.globalMatch(list);
				api = "http://www.%1/video/%2/index_%3.html";
				api = api.arg(Utils::customUrl(Utils::Bilibili));
				while (i.hasNext()){
					int index = d->model->rowCount() + 1;
					QStandardItem *item = new QStandardItem;
					item->setData(QUrl(api.arg(task.code).arg(index)), UrlRole);
					item->setData((task.code + "#%1").arg(index), StrRole);
					item->setData(Page, NxtRole);
					item->setData(Utils::decodeXml(i.next().captured()), Qt::EditRole);
					d->model->appendRow(item);
				}
			}
			if (d->model->rowCount() > 0){
				emit stateChanged(task.state = Part);
			}
			else{
				QRegularExpression r = QRegularExpression("cid[=\":]*\\d+", QRegularExpression::CaseInsensitiveOption);
				QRegularExpressionMatchIterator i = r.globalMatch(video);
				while (i.hasNext()){
					QString m = i.next().captured();
					m = QRegularExpression("\\d+").match(m).captured();
					if (id.isEmpty()){
						id = m;
					}
					else if (id != m){
						id.clear();
						break;
					}
				}
				if (!id.isEmpty()){
					api = "http://comment.%1/%2.xml";
					api = api.arg(Utils::customUrl(Utils::Bilibili));
					forward(QNetworkRequest(api.arg(id)), File);
				}
                else{
                    emit stateChanged(203);
                    qDebug() << "Fail to load danmaku, try biliApi";
                    dequeue();
                }
            }
			break;
		}
		case File:
		{
			dumpDanmaku(reply->readAll(), Utils::Bilibili, false);
			emit stateChanged(task.state = None);
			dequeue();
			break;
		}
		}
	};
	auto avRegular = [](QString &code){
		code.remove(QRegularExpression("/index(?=_\\d+\\.html)"));
		QRegularExpression r("a(v(\\d+([#_])?(\\d+)?)?)?");
		r.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
		return getRegular(r)(code);
	};
	d->pool.append({ avRegular, 0, avProcess });

	auto bbProcess = [this, avProcess](QNetworkReply *reply) {
		Q_D(Load);
		Task &task = d->queue.head();
		switch (task.state) {
		case None:
		{
			QString i = task.code.mid(2);
			QString u = "http://www.%1/bangumi/i/%2/";
			u = u.arg(Utils::customUrl(Utils::Bilibili)).arg(i);
			forward(QNetworkRequest(u), Page);
			break;
		}
		case Page:
		{
			d->model->clear();
			QString page(reply->readAll());
			QStringList list = page.split("<li data-index");

			if (list.size() < 2) {
				emit stateChanged(task.state = None);
				dequeue();
				break;
			}

			list.removeFirst();
			QListIterator<QString> iter(list);
			iter.toBack();
			while (iter.hasPrevious()) {
				QRegularExpression r;
				const QString &i = iter.previous();
				r.setPattern("(?<=href=\")[^\"]+");
				QString c = r.match(i).captured();
				fixCode(c);
				r.setPattern("(?<=<span>).+(?=</span>)");
				QString t = Utils::decodeXml(r.match(i).captured());

				QStandardItem *item = new QStandardItem;
				item->setData(c, StrRole);
				item->setData(None, NxtRole);
				item->setData(t, Qt::EditRole);
				d->model->appendRow(item);
			}
			emit stateChanged(task.state = Part);
		}
		}
	};

	auto bbRegular = [](QString &code) {
		code.replace(QRegularExpression("bangumi/i/(?=\\d+)"), "bb");
		QRegularExpression r("b(b(\\d+)?)?");
		r.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
		return getRegular(r)(code);
	};
	d->pool.append({ bbRegular, 0, bbProcess });

	auto acProcess = [this](QNetworkReply *reply){
		Q_D(Load);
		Task &task = d->queue.head();
		int sharp = task.code.indexOf(QRegularExpression("[#_]"));
		switch (task.state){
		case None:
		{
			QString i = task.code.mid(2, sharp - 2);
			QString p = sharp == -1 ? QString() : task.code.mid(sharp + 1);
			QString url("http://www.%1/v/ac%2");
			url = url.arg(Utils::customUrl(Utils::AcFun)).arg(i);
			if (!p.isEmpty()){
				url += QString("_%1").arg(p);
			}
			forward(QNetworkRequest(url), Page);
			break;;
		}
		case Page:
		{
			d->model->clear();
			QRegularExpressionMatchIterator match = QRegularExpression("data-vid.*?</a>").globalMatch(reply->readAll());
			while (match.hasNext()){
				QStandardItem *item = new QStandardItem;
				QString part = match.next().captured();
				QRegularExpression r;
				r.setPattern("(?<=>)[^>]+?(?=</a>)");
				item->setData(Utils::decodeXml(r.match(part).captured()), Qt::EditRole);
				r.setPattern("(?<=data-vid=\").+?(?=\")");
				QString next("http://static.comment.%1/V2/%2?pageSize=1000&pageNo=1");
				next = next.arg(Utils::customUrl(Utils::AcFun)).arg(r.match(part).captured());
				item->setData(next, UrlRole);
				item->setData((task.code + "#%1").arg(d->model->rowCount() + 1), StrRole);
				item->setData(File, NxtRole);
				d->model->appendRow(item);
			}
			if (sharp == -1 && d->model->rowCount() >= 2){
				emit stateChanged(task.state = Part);
			}
			else{
				int i = sharp == -1 ? 0 : task.code.mid(sharp + 1).toInt() - 1;
				if (i >= 0 && i < d->model->rowCount()){
					forward(QNetworkRequest(d->model->item(i)->data(UrlRole).toUrl()), File);
				}
				else{
					emit stateChanged(203);
					dequeue();
				}
			}
			break;
		}
		case File:
		{
			QByteArray data = reply->readAll();
			if (data != "[[],[],[]]"){
				QNetworkRequest &request = task.request;
				QUrl url = request.url();
				int page = QUrlQuery(url).queryItemValue("pageNo").toInt();
				url.setQuery(QString());
				request.setUrl(url);
				dumpDanmaku(data, Utils::AcFun, false);
				QUrlQuery query;
				query.addQueryItem("pageSize", "1000");
				query.addQueryItem("pageNo", QString::number(page + 1));
				url.setQuery(query);
				request.setUrl(url);
				forward(request, File);
			}
			else{
				emit stateChanged(task.state = None);
				dequeue();
			}
			break;
		}
		}
	};
	auto acRegular = getRegular(QRegularExpression("a(c(\\d+([#_])?(\\d+)?)?)?", QRegularExpression::CaseInsensitiveOption));
	d->pool.append({ acRegular, 0, acProcess });

	auto abProcess = [this, acProcess](QNetworkReply *reply){
		Q_D(Load);
		Task &task = d->queue.head();
		int sharp = task.code.indexOf(QRegularExpression("[#_]"));
		switch (task.state){
		case None:
		{
			QString url("http://www.%1/bangumi/video/page?bangumiId=%2&pageSize=30&pageNo=%3&order=2");
			url = url.arg(Utils::customUrl(Utils::AcFun)).arg(task.code.mid(2, sharp - 2));
			url = url.arg(sharp == -1 ? 1 : (task.code.mid(sharp + 1).toInt() - 1) / 30 + 1);
			forward(QNetworkRequest(url), Page);
			break;
		}
		case Page:
		{
			if (sharp != -1){
				QJsonObject data = QJsonDocument::fromJson(reply->readAll()).object()["data"].toObject();
				int i = task.code.mid(sharp + 1).toInt();
				if (i > 0){
					i = (i - 1) % 30;
				}
				else{
					i = data["totalCount"].toInt();
					if (i > 30){
						task.code = task.code.left(sharp) + QString("#%1").arg(i);
						task.state = None;
						task.processer->process(nullptr);
						break;
					}
				}
				QJsonArray list = data["list"].toArray();
				if (i < 0 || i >= list.size()){
					emit stateChanged(203);
					dequeue();
					break;
				}
				QString head("http://static.comment.%1/V2/%2?pageSize=1000&pageNo=1");
				head = head.arg(Utils::customUrl(Utils::AcFun));
				head = head.arg(list[i].toObject()["danmakuId"].toString());
				forward(QNetworkRequest(head), File);
				break;
			}
			else{
				d->model->clear();
			}
		}
		case Part:
		{
			QJsonObject info = QJsonDocument::fromJson(reply->readAll()).object();
			if (!info["success"].toBool() && d->model->rowCount() == 0){
				emit stateChanged(info["status"].toInt());
				dequeue();
			}
			QJsonObject data = info["data"].toObject();
			for (const QJsonValue &value : data["list"].toArray()){
				QStandardItem *item = new QStandardItem;
				QJsonObject data = value.toObject();
				item->setData(data["title"].toString(), Qt::EditRole);
				QString head("http://static.comment.%1/V2/%2?pageSize=1000&pageNo=1");
				head = head.arg(Utils::customUrl(Utils::AcFun)).arg(data["danmakuId"].toString());
				item->setData(head, UrlRole);
				item->setData((task.code + "#%1").arg(d->model->rowCount() + 1), StrRole);
				item->setData(File, NxtRole);
				d->model->appendRow(item);
			}
			if (task.state != Part){
				emit stateChanged(task.state = Part);
			}
			if (data["pageNo"].toInt() < data["totalPage"].toInt()){
				QUrl url = reply->request().url();
				auto arg = QUrlQuery(url).queryItems();
				for (auto &p : arg){
					if (p.first == "pageNo"){
						p.second = QString::number(p.second.toInt() + 1);
						break;
					}
				}
				QUrlQuery query;
				query.setQueryItems(arg);
				url.setQuery(query);
				d->remain.insert(d->manager.get(QNetworkRequest(url)));
			}
			break;
		}
		case File:
		{
			acProcess(reply);
			break;
		}
		}
	};
	auto abRegular = getRegular(QRegularExpression("a(b(\\d+([#_])?(\\d+)?)?)?", QRegularExpression::CaseInsensitiveOption));
	d->pool.append({ abRegular, 0, abProcess });

	auto ccProcess = [this](QNetworkReply *reply){
		Q_D(Load);
		Task &task = d->queue.head();
		int sharp = task.code.indexOf(QRegularExpression("[#_]"));
		switch (task.state){
		case None:
		{
			QString i = task.code.mid(2, sharp - 2);
			QString p = sharp == -1 ? QString() : task.code.mid(sharp + 1);
			QString url("http://www.%1/play/h%2/");
			url = url.arg(Utils::customUrl(Utils::TuCao)).arg(i);
			if (!p.isEmpty()){
				url += QString("#%1").arg(p);
			}
			forward(QNetworkRequest(url), Page);
			break;
		}
		case Page:
		{
			QString page = reply->readAll();
			d->model->clear();
			QRegularExpressionMatch m;
			QRegularExpression r("(?<=<li>)[^<]*(?=</li>)");
			m = r.match(page, page.indexOf("<ul id=\"player_code\""));
			QStringList list = m.captured().split("**");
			m = r.match(page, m.capturedEnd());
			QString code = m.captured();
			for (const QString &iter : list){
				QStandardItem *item = new QStandardItem;
				item->setData(iter.mid(iter.indexOf('|') + 1), Qt::EditRole);
				QString api("http://www.%1/index.php?m=mukio&c=index&a=init&playerID=%2");
				api = api.arg(Utils::customUrl(Utils::TuCao)).arg((code + "-%1").arg(d->model->rowCount()));
				item->setData(api, UrlRole);
				item->setData((task.code + "#%1").arg(d->model->rowCount() + 1), StrRole);
				item->setData(File, NxtRole);
				d->model->appendRow(item);
			}
			if (sharp == -1 && d->model->rowCount() >= 2){
				emit stateChanged(task.state = Part);
			}
			else{
				int i = sharp == -1 ? 0 : task.code.mid(sharp + 1).toInt() - 1;
				if (i >= 0 && i < d->model->rowCount()){
					forward(QNetworkRequest(d->model->item(i)->data(UrlRole).toUrl()), File);
				}
				else{
					emit stateChanged(203);
					dequeue();
				}
			}
			break;
		}
		case File:
		{
			dumpDanmaku(reply->readAll(), Utils::TuCao, false);
			emit stateChanged(task.state = None);
			dequeue();
			break;
		}
		}
	};
	auto ccRegular = [](QString &code){
		code.replace(QRegularExpression("[Hh](?=\\d)"), "cc");
		QRegularExpression r("c(c(\\d+([#_])?(\\d+)?)?)?");
		r.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
		return getRegular(r)(code);
	};
	d->pool.append({ ccRegular, 0, ccProcess });

	d->pool.append(Proc());
	Proc *directProc = &d->pool.last();
	directProc->process = [this](QNetworkReply *reply){
		Q_D(Load);
		Task &task = d->queue.head();
		switch (task.state){
		case None:
		{
			QUrl url = QUrl::fromUserInput(task.code);
			task.request.setUrl(url);
			task.state = File;
			forward();
			break;
		}
		case File:
		{
			Record load;
			QUrl url = reply->url();
			QByteArray data(reply->readAll());
			load.source = url.url();
			load.access = url.isLocalFile() ? url.toLocalFile() : load.source;
			load.string = QFileInfo(task.code).fileName();
			load.delay = task.delay;
			QString head = Utils::decodeTxt(data.left(512));
			if (head.startsWith("[Script Info]")){
				load.danmaku = Parse::parseComment(data, Utils::ASS);
			}
			else if (!head.startsWith("<?xml")){
				load.danmaku = Parse::parseComment(data, Utils::AcFun);
			}
			else if (head.indexOf("<packet>") != -1){
				load.danmaku = Parse::parseComment(data, Utils::Niconico);
			}
			else if (head.indexOf("<i>") != -1){
				load.danmaku = Parse::parseComment(data, Utils::Bilibili);
				QString i = QRegularExpression("(?<=<chatid>)\\d+(?=</chatid>)").match(head).captured();
				if (!i.isEmpty()){
					load.source = "http://comment.%1/%2.xml";
					load.source = load.source.arg(Utils::customUrl(Utils::Bilibili)).arg(i);
				}
			}
			else if (head.indexOf("<c>") != -1){
				load.danmaku = Parse::parseComment(data, Utils::AcfunLocalizer);
			}
			if (load.delay != 0){
				for (Comment &c : load.danmaku){
					c.time += load.delay;
				}
			}
			Danmaku::instance()->appendToPool(&load);
			emit stateChanged(task.state = None);
			dequeue();
			break;
		}
		}
	};
	directProc->priority = -100;
	directProc->regular = [this, directProc](QString &code){
		if (code.startsWith("full?") || code.startsWith("hist?")){
			code.clear();
			return false;
		}
		QUrl u = QUrl::fromUserInput(code);
		if (!u.host().isEmpty() && !u.path().isEmpty()){
			return true;
		}
		if (QFileInfo(code).exists()){
			return true;
		}
		code.clear();
		return false;
	};

	auto fullBiProcess = [this](QNetworkReply *reply){
		Q_D(Load);
		Task &task = d->queue.head();
		switch (task.state) {
		case None:
		{
			emit progressChanged(0);
			QString api("http://comment.%1/rolldate,%2");
			api = api.arg(Utils::customUrl(Utils::Bilibili));
			task.code = QUrlQuery(task.code.mid(5)).queryItemValue("source");
			forward(QNetworkRequest(api.arg(QFileInfo(task.code).baseName())), Page);
			break;
		}
		case Page:
		{
			QByteArray data = reply->readAll();
			QJsonArray date = QJsonDocument::fromJson(data).array();
			if (date.isEmpty()) {
				emit stateChanged(203);
				dequeue();
				break;
			}
			QJsonObject head = date.first().toObject();
			QString url("http://comment.%1/dmroll,%2,%3");
			url = url.arg(Utils::customUrl(Utils::Bilibili));
			url = url.arg(head["timestamp"].toVariant().toInt());
			url = url.arg(QFileInfo(task.code).baseName());
			QNetworkRequest request(url);
			request.setAttribute(QNetworkRequest::User, data);
			forward(request, Code);
			break;
		}
		case Code:
		{
			QByteArray data = task.request.attribute(QNetworkRequest::User).toByteArray();
			QJsonArray date = QJsonDocument::fromJson(data).array();
			QMap<int, int> count;
			for (auto iter : date) {
				QJsonObject item = iter.toObject();
				count[item["timestamp"].toVariant().toInt()] += item["new"].toVariant().toInt();
			}

			data = reply->readAll();
			if (count.size() >= 2) {
				int max = QRegularExpression("(?<=\\<max_count\\>).+(?=\\</max_count\\>)").match(data).captured().toInt();
				int now = 0;

				auto getHistory = [d, &count, &task](int date) {
					QString url("http://comment.%1/dmroll,%2,%3");
					url = url.arg(Utils::customUrl(Utils::Bilibili));
					url = url.arg(date);
					url = url.arg(QFileInfo(task.code).baseName());
					return d->manager.get(QNetworkRequest(url));
				};

				for (auto iter = count.begin() + 1;; ++iter) {
					now += iter.value();
					if (iter + 1 == count.end()) {
						d->remain += getHistory(iter.key());
						break;
					}
					else if (now + (iter + 1).value() > max) {
						d->remain += getHistory(iter.key());
						now = 0;
					}
				}

				auto pool = QSharedPointer<QVector<Parse::ResultDelegate>>::create();
				pool->append(Parse::parseComment(data, Utils::Bilibili));

				double total = d->remain.size() + 2;
				for (QNetworkReply *iter : d->remain) {
					connect(iter, &QNetworkReply::finished, [=, &task]() {
						QByteArray data = iter->readAll();
						pool->append(Parse::parseComment(data, Utils::Bilibili));
						switch (iter->error()) {
						case QNetworkReply::NoError:
							emit progressChanged((total - d->remain.size()) / total);
						case QNetworkReply::OperationCanceledError:
							if (d->remain.isEmpty() && !pool->empty()) {
								Record load;
								load.full = true;
								for (auto &iter : *pool) {
									load.danmaku.append(iter);
								}
								load.source = task.code;
								Danmaku::instance()->appendToPool(&load);
								emit stateChanged(task.state = None);
								dequeue();
							}
						default:
							break;
						}
					});
				}

				emit progressChanged(2 / total);
				emit stateChanged(task.state = File);
				break;
			}
			else {
				emit progressChanged(1);
				dumpDanmaku(data, Utils::Bilibili, true);
				emit stateChanged(task.state = None);
				dequeue();
				break;
			}
		}
		}
	};

	auto fullBiRegular = QRegularExpression("^full\\?source=http://comment\\.bilibili\\.com/\\d+\\.xml$");
	fullBiRegular.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
	d->pool.append({ getRegular(fullBiRegular), 100, fullBiProcess });

	auto histBiProcess = [this](QNetworkReply *reply){
		Q_D(Load);
		Task &task = d->queue.head();
		switch (task.state){
		case None:
		{
			QUrlQuery query(task.code.mid(5));
			task.code = query.queryItemValue("source");
			QString cid = QFileInfo(task.code).baseName();
			QString dat = query.queryItemValue("date");
			QString url;
			QNetworkRequest request;
			if (dat != "0" && dat.toUInt() != QDateTime(QDate::currentDate()).toTime_t()){
				url = QString("http://comment.%1/dmroll,%2,%3");
				url = url.arg(Utils::customUrl(Utils::Bilibili));
				url = url.arg(dat).arg(cid);
				int limit = QDateTime(QDateTime::fromTime_t(dat.toInt()).date().addDays(1)).toTime_t();
				request.setAttribute(QNetworkRequest::User, limit);
			}
			else{
				url = QString("http://comment.%1/%2.xml").arg(Utils::customUrl(Utils::Bilibili));
				url = url.arg(cid);
			}
			request.setUrl(url);
			forward(request, File);
			break;
		}
		case File:
		{
			Record load;
			load.danmaku = Parse::parseComment(reply->readAll(), Utils::Bilibili);
			load.source = task.code;
			for (Record &iter : Danmaku::instance()->getPool()){
				if (iter.source == load.source){
					iter.full = false;
					iter.danmaku.clear();
					iter.limit = 1;
					break;
				}
			}
			load.limit = task.request.attribute(QNetworkRequest::User).toInt();
			Danmaku::instance()->appendToPool(&load);
			emit stateChanged(task.state = None);
			dequeue();
			break;
		}
		}
	};
	auto histBiRegular = QRegularExpression("^hist\\?source=http://comment\\.bilibili\\.com/\\d+\\.xml&date=\\d+$");
	histBiRegular.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
	d->pool.append({ getRegular(histBiRegular), 100, histBiProcess });

	connect(this, &Load::stateChanged, [this](int code){
		switch (code){
		case None:
		case Page:
		case Part:
		case Code:
		case File:
			break;
		default:
		{
			Q_D(Load);
			if (!d->tryNext()){
				emit errorOccured(code);
			}
			break;
		}
		}
	});
}
Ejemplo n.º 25
0
Archivo: pihmgis.cpp Proyecto: mlt/PIHM
void PIHMgis::runHomePage(){
  QUrl url("http://www.pihm.psu.edu");
  QDesktopServices::openUrl( url);
}
Ejemplo n.º 26
0
int ComprDataIO::UnpRead(byte *Addr,uint Count)
{
  int RetCode=0,TotalRead=0;
  byte *ReadAddr;
  ReadAddr=Addr;
  while (Count > 0)
  {
    Archive *SrcArc=(Archive *)SrcFile;

    uint ReadSize=(Count>UnpPackedSize) ? int64to32(UnpPackedSize):Count;
    if (UnpackFromMemory)
    {
      memcpy(Addr,UnpackFromMemoryAddr,UnpackFromMemorySize);
      RetCode=UnpackFromMemorySize;
      UnpackFromMemorySize=0;
    }
    else
    {
      bool bRead = true;
      if (!SrcFile->IsOpened())
      {
        NextVolumeMissing = true;
        return(-1);
      }
      if (UnpackToMemory)
        if (WaitForSingleObject(hSeek,1) == WAIT_OBJECT_0) // we are seeking
        {
          if (m_iSeekTo > CurUnpStart+SrcArc->NewLhd.FullPackSize) // need to seek outside this block
          {
            TotalRead += (int)(SrcArc->NextBlockPos-SrcFile->Tell());
            CurUnpRead=CurUnpStart+SrcArc->NewLhd.FullPackSize;
            UnpPackedSize=0;
            RetCode = 0;
            bRead = false;
          }
          else
          {
            Int64 iStartOfFile = SrcArc->NextBlockPos-SrcArc->NewLhd.FullPackSize;
            m_iStartOfBuffer = CurUnpStart;
            Int64 iSeekTo=m_iSeekTo-CurUnpStart<MAXWINMEMSIZE/2?iStartOfFile:iStartOfFile+m_iSeekTo-CurUnpStart-MAXWINMEMSIZE/2;
            if (iSeekTo == iStartOfFile) // front
            {
              if (CurUnpStart+MAXWINMEMSIZE>SrcArc->NewLhd.FullUnpSize)
              {
                m_iSeekTo=SrcArc->NewLhd.FullUnpSize-iSeekTo+iStartOfFile; // back
                UnpPackedSize = SrcArc->NewLhd.FullPackSize;
              }
              else 
              {
                m_iSeekTo=MAXWINMEMSIZE-(m_iSeekTo-CurUnpStart);
                UnpPackedSize = SrcArc->NewLhd.FullPackSize - (m_iStartOfBuffer - CurUnpStart);
              }
            }
            else
            {
              m_iStartOfBuffer = m_iSeekTo-MAXWINMEMSIZE/2; // front
              if (m_iSeekTo+MAXWINMEMSIZE/2>SrcArc->NewLhd.FullUnpSize)
              {
                iSeekTo = iStartOfFile+SrcArc->NewLhd.FullPackSize-MAXWINMEMSIZE;
                m_iStartOfBuffer = CurUnpStart+SrcArc->NewLhd.FullPackSize-MAXWINMEMSIZE;
                m_iSeekTo = MAXWINMEMSIZE-(m_iSeekTo-m_iStartOfBuffer);
                UnpPackedSize = MAXWINMEMSIZE;
              }
              else 
              {
                m_iSeekTo=MAXWINMEMSIZE/2;
                UnpPackedSize = SrcArc->NewLhd.FullPackSize - (m_iStartOfBuffer - CurUnpStart);
              }  
            }

            SrcFile->Seek(iSeekTo,SEEK_SET);
            TotalRead = 0;
            CurUnpRead = CurUnpStart + iSeekTo - iStartOfFile;
            CurUnpWrite = SrcFile->Tell() - iStartOfFile + CurUnpStart;
            
            ResetEvent(hSeek);
            SetEvent(hSeekDone);
          }
        }
      if (bRead)
      {
        ReadSize=(Count>UnpPackedSize) ? int64to32(UnpPackedSize):Count;
        RetCode=SrcFile->Read(ReadAddr,ReadSize);
        FileHeader *hd=SubHead!=NULL ? SubHead:&SrcArc->NewLhd;
        if (hd->Flags & LHD_SPLIT_AFTER)
        {
          PackedCRC=CRC(PackedCRC,ReadAddr,ReadSize);
        }
      }
    }
    CurUnpRead+=RetCode;
    ReadAddr+=RetCode;
    TotalRead+=RetCode;
    Count-=RetCode;
    UnpPackedSize-=RetCode;
    if (UnpPackedSize == 0 && UnpVolume)
    {
#ifndef NOVOLUME
      if (!MergeArchive(*SrcArc,this,true,CurrentCommand))
#endif
      {
        NextVolumeMissing=true;
        return(-1);
      }
      CurUnpStart = CurUnpRead;
      if (m_pDlgProgress)
      {
        CURL url(SrcArc->FileName);
        CStdString strDisplay;
        url.GetURLWithoutUserDetails(strDisplay);
        m_pDlgProgress->SetLine(2,strDisplay); // update currently extracted rar file
        m_pDlgProgress->Progress();
      }
    }
    else
      break;
  }
  Archive *SrcArc=(Archive *)SrcFile;
  if (SrcArc!=NULL)
    ShowUnpRead(SrcArc->CurBlockPos+CurUnpRead,UnpArcSize);
  if (RetCode!=-1)
  {
    RetCode=TotalRead;
#ifndef NOCRYPT
    if (Decryption)
    {
#ifndef SFX_MODULE
      if (Decryption<20)
        Decrypt.Crypt(Addr,RetCode,(Decryption==15) ? NEW_CRYPT : OLD_DECODE);
      else if (Decryption==20)
        for (int I=0;I<RetCode;I+=16)
          Decrypt.DecryptBlock20(&Addr[I]);
      else
#endif
      {
        int CryptSize=(RetCode & 0xf)==0 ? RetCode:((RetCode & ~0xf)+16);
        Decrypt.DecryptBlock(Addr,CryptSize);
      }
    }
#endif
  }
  Wait();
  return(RetCode);
}
Ejemplo n.º 27
0
 void Mpris2DBusHandler::OpenUri( const QString &uri )
 {
     KUrl url( uri );
     The::playlistController()->insertOptioned( KUrl::List() << url, Playlist::AppendAndPlayImmediately );
 }
Ejemplo n.º 28
0
/*!
 * \brief CrashReportDialog::sendReport
 * Slot activated when mpSendReportButton clicked signal is raised.\n
 * Sends the crash report alongwith selected log files.
 */
void CrashReportDialog::sendReport()
{
  // ask for e-mail address.
  if (mpEmailTextBox->text().isEmpty()) {
    QMessageBox *pMessageBox = new QMessageBox;
    pMessageBox->setWindowTitle(QString(Helper::applicationName).append(" - ").append(Helper::error));
    pMessageBox->setIcon(QMessageBox::Critical);
    pMessageBox->setAttribute(Qt::WA_DeleteOnClose);
    pMessageBox->setText(tr("We can't contact you with a possible solution if you don't provide a valid e-mail address."));
    pMessageBox->addButton(tr("Send without e-mail"), QMessageBox::AcceptRole);
    pMessageBox->addButton(tr("Let me enter e-mail"), QMessageBox::RejectRole);
    int answer = pMessageBox->exec();
    switch (answer) {
      case QMessageBox::RejectRole:
        mpEmailTextBox->setFocus();
        return;
      case QMessageBox::AcceptRole:
      default:
        break;
    }
  }
  // create the report.
  QHttpMultiPart *pHttpMultiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
  // email
  QHttpPart emailHttpPart;
  emailHttpPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"email\""));
  emailHttpPart.setBody(mpEmailTextBox->text().toUtf8());
  pHttpMultiPart->append(emailHttpPart);
  // bug description
  QHttpPart bugDescriptionHttpPart;
  bugDescriptionHttpPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"bugdescription\""));
  bugDescriptionHttpPart.setBody(mpBugDescriptionTextBox->toPlainText().toUtf8());
  pHttpMultiPart->append(bugDescriptionHttpPart);
  // OMEditCommunicationLogFile
  if (mpOMEditCommunicationLogFileCheckBox->isChecked()) {
    QHttpPart OMEditCommunicationLogFileHttpPart;
    OMEditCommunicationLogFileHttpPart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/plain"));
    OMEditCommunicationLogFileHttpPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"omeditcommunication.log\"; filename=\"omeditcommunication.log\""));
    QFile *pOMEditCommunicationLogFileFile = new QFile(mpOMEditCommunicationLogFileCheckBox->text());
    pOMEditCommunicationLogFileFile->open(QIODevice::ReadOnly);
    OMEditCommunicationLogFileHttpPart.setBodyDevice(pOMEditCommunicationLogFileFile);
    pOMEditCommunicationLogFileFile->setParent(pHttpMultiPart); // file will be deleted when we delete pHttpMultiPart
    pHttpMultiPart->append(OMEditCommunicationLogFileHttpPart);
  }
  // OMEditCommandsMosFile
  if (mpOMEditCommandsMosFileCheckBox->isChecked()) {
    QHttpPart OMEditCommandsMosFileHttpPart;
    OMEditCommandsMosFileHttpPart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/plain"));
    OMEditCommandsMosFileHttpPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"omeditcommands.mos\"; filename=\"omeditcommands.mos\""));
    QFile *pOMEditCommandsMosFile = new QFile(mpOMEditCommandsMosFileCheckBox->text());
    pOMEditCommandsMosFile->open(QIODevice::ReadOnly);
    OMEditCommandsMosFileHttpPart.setBodyDevice(pOMEditCommandsMosFile);
    pOMEditCommandsMosFile->setParent(pHttpMultiPart); // file will be deleted when we delete pHttpMultiPart
    pHttpMultiPart->append(OMEditCommandsMosFileHttpPart);
  }
  // OMStackTraceFile
  if (mpOMStackTraceFileCheckBox->isChecked()) {
    QHttpPart OMStackTraceFileCheckBoxHttpPart;
    OMStackTraceFileCheckBoxHttpPart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/plain"));
    OMStackTraceFileCheckBoxHttpPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"openmodelica.stacktrace.OMEdit\"; filename=\"openmodelica.stacktrace.OMEdit\""));
    QFile *pOMStackTraceFile = new QFile(mpOMStackTraceFileCheckBox->text());
    pOMStackTraceFile->open(QIODevice::ReadOnly);
    OMStackTraceFileCheckBoxHttpPart.setBodyDevice(pOMStackTraceFile);
    pOMStackTraceFile->setParent(pHttpMultiPart); // file will be deleted when we delete pHttpMultiPart
    pHttpMultiPart->append(OMStackTraceFileCheckBoxHttpPart);
  }
  // create the request
  QUrl url("https://dev.openmodelica.org/omeditcrashreports/cgi-bin/server.py");
  QNetworkRequest networkRequest(url);
  QNetworkAccessManager *pNetworkAccessManager = new QNetworkAccessManager;
  QNetworkReply *pNetworkReply = pNetworkAccessManager->post(networkRequest, pHttpMultiPart);
  pNetworkReply->ignoreSslErrors();
  pHttpMultiPart->setParent(pNetworkReply); // delete the pHttpMultiPart with the pNetworkReply
  connect(pNetworkAccessManager, SIGNAL(finished(QNetworkReply*)), SLOT(reportSent(QNetworkReply*)));
}
Ejemplo n.º 29
0
/**
 *  Starts geo searching
 *  @param latLong latitude and longitude
 *  @param query text to match against while executing a geo-based query,
 *               best suited for finding nearby locations by name
 *  @param ip ip address. Used when attempting to fix geolocation based off of the user's IP address.
 *  @param granularity this is the minimal granularity of place types to return
 *  @param accuracy hint on the "region" in which to search in meters
 *  @param maxResults hint as to the number of results to return
 *  @param containedWithin this is the placeID which you would like to restrict the search results to
 */
void QTweetGeoSearch::search(const QTweetGeoCoord &latLong,
                             const QString &query,
                             const QString &ip,
                             QTweetPlace::Type granularity,
                             int accuracy,
                             int maxResults,
                             const QString &containedWithin)
{
    QUrl url("http://api.twitter.com/1/geo/search.json");

    if (latLong.isValid()) {
        url.addQueryItem("lat", QString::number(latLong.latitude()));
        url.addQueryItem("long", QString::number(latLong.longitude()));
    }

    if (!query.isEmpty())
        url.addEncodedQueryItem("query", QUrl::toPercentEncoding(query));

    if (!ip.isEmpty())
        //doesn't do ip format address checking
        url.addQueryItem("ip", ip);

    switch (granularity) {
    case QTweetPlace::Poi:
        url.addQueryItem("granularity", "poi");
        break;
    case QTweetPlace::Neighborhood:
        url.addQueryItem("granularity", "neighborhood");
        break;
    case QTweetPlace::City:
        url.addQueryItem("granularity", "city");
        break;
    case QTweetPlace::Admin:
        url.addQueryItem("granularity", "admin");
        break;
    case QTweetPlace::Country:
        url.addQueryItem("granularity", "country");
        break;
    default:
        ;
    }

    if (accuracy != 0)
        url.addQueryItem("accuracy", QString::number(accuracy));

    if (maxResults != 0)
        url.addQueryItem("max_results", QString::number(maxResults));

    if (!containedWithin.isEmpty())
        url.addQueryItem("contained_within", containedWithin);

    QNetworkRequest req(url);

    if (isAuthenticationEnabled()) {
        QByteArray oauthHeader = oauthTwitter()->generateAuthorizationHeader(url, OAuth::GET);
        req.setRawHeader(AUTH_HEADER, oauthHeader);
    }

    QNetworkReply *reply = oauthTwitter()->networkAccessManager()->get(req);
    connect(reply, SIGNAL(finished()), this, SLOT(reply()));
}
Ejemplo n.º 30
0
void AddFeedWizard::finish()
{
  int parentId = 0;

  QSqlQuery q;
  q.exec(QString("SELECT htmlUrl FROM feeds WHERE id=='%1'").arg(feedId_));
  if (q.first())
    htmlUrlString_ = q.value(0).toString();

  if (foldersTree_->currentItem()->text(1) != "0")
    parentId = foldersTree_->currentItem()->text(1).toInt();

  // Correct rowToParent field
  QList<int> idList;
  q.exec("SELECT id FROM feeds WHERE parentId=0 ORDER BY rowToParent");
  while (q.next()) {
    if (feedId_ != q.value(0).toInt())
      idList << q.value(0).toInt();
  }
  for (int i = 0; i < idList.count(); i++) {
    q.exec(QString("UPDATE feeds SET rowToParent='%1' WHERE id=='%2'").
           arg(i).arg(idList.at(i)));
  }

  // Calculate row number to insert feed
  int rowToParent = 0;
  q.exec(QString("SELECT count(id) FROM feeds WHERE parentId='%1' AND id!='%2'").
         arg(parentId).arg(feedId_));
  if (q.next()) rowToParent = q.value(0).toInt();

  int auth = 0;
  if (authentication_->isChecked()) auth = 1;

  q.prepare("UPDATE feeds SET text = ?, parentId = ?, rowToParent = ?, authentication = ? WHERE id == ?");
  q.addBindValue(nameFeedEdit_->text());
  q.addBindValue(parentId);
  q.addBindValue(rowToParent);
  q.addBindValue(auth);
  q.addBindValue(feedId_);
  q.exec();

  if (auth) {
    QUrl url(feedUrlString_);
    QString server = url.host();

    q.prepare("SELECT * FROM passwords WHERE server=?");
    q.addBindValue(server);
    q.exec();
    if (!q.next()) {
      q.prepare("INSERT INTO passwords (server, username, password) "
                "VALUES (:server, :username, :password)");
      q.bindValue(":server", server);
      q.bindValue(":username", user_->text());
      q.bindValue(":password", pass_->text().toUtf8().toBase64());
      q.exec();
    }
  }

  feedParentId_ = parentId;

  accept();
}