Example #1
0
    bool mergeJsonArrays (const QJsonArray &arrayFrom, QJsonArray &arrayTo, CompareValuesJson &comparer) {
        LOG_DEBUG << "#";

        if (arrayTo.isEmpty()) {
            LOG_DEBUG << "ArrayTo is empty";
            arrayTo = arrayFrom;
            return true;
        }

        if (arrayFrom.isEmpty()) {
            LOG_DEBUG << "ArrayFrom is empty";
            return false;
        }

        if (arrayTo.first().type() != arrayFrom.first().type() ) {
            LOG_WARNING << "Type of arrays to be merged does not match!";
            return false;
        }

        bool mergeResult = false;
        int type = arrayTo.first().type();

        if (type == QJsonValue::Object) {
            mergeResult = mergeArraysOfObjects(arrayFrom, arrayTo, comparer);
        } else if (type == QJsonValue::String) {
            mergeResult = mergeArraysOfStrings(arrayFrom, arrayTo);
        } else {
            LOG_WARNING << "Unsupported type of QJsonArray:" << type;
        }

        return mergeResult;
    }
Example #2
0
void SnapshotShareDialog::postRequestFinished() {

    QNetworkReply* requestReply = reinterpret_cast<QNetworkReply*>(sender());
    QJsonDocument jsonResponse = QJsonDocument::fromJson(requestReply->readAll());
    const QJsonObject& responseObject = jsonResponse.object();

    if (responseObject.contains("id")) {
        _ui.textEdit->setHtml("");
        const QString urlTemplate = "%1/t/%2/%3/%4";
        QString link = urlTemplate.arg(FORUM_URL,
                                        responseObject["topic_slug"].toString(),
                                        QString::number(responseObject["topic_id"].toDouble()),
                                        QString::number(responseObject["post_number"].toDouble()));

        _ui.successLabel->setText(SUCCESS_LABEL_TEMPLATE.arg(link));
        _ui.successLabel->setFixedHeight(SUCCESS_LABEL_HEIGHT);

        // hide input widgets
        _ui.shareButton->hide();
        _ui.textEdit->hide();
        _ui.labelNotes->hide();

    } else {
        QString errorMessage(SHARE_DEFAULT_ERROR);
        if (responseObject.contains("errors")) {
            QJsonArray errorArray = responseObject["errors"].toArray();
            if (!errorArray.first().toString().isEmpty()) {
                errorMessage = errorArray.first().toString();
            }
        }
        QMessageBox::warning(this, "", errorMessage);
        _ui.shareButton->setEnabled(true);
        _ui.shareButton->setStyleSheet(SHARE_BUTTON_STYLE + SHARE_BUTTON_ENABLED_STYLE);
    }
}
Example #3
0
void Database::load(QString path){
    std::ifstream in(path.toStdString().c_str(), std::ifstream::in);
    QJsonDocument jdoc;
    QJsonObject root;
    QJsonObject table;
    QJsonObject values;
    QJsonArray keys;
    QJsonArray tables;
    std::string line;
    Kind *k;
    while(getline(in, line)){
        jdoc = QJsonDocument::fromJson(QString::fromStdString(line).toUtf8());
        root = jdoc.object();
        k = con->addChild(root[NAME].toString(),root[SURNAME].toString());
        k->setDate(QDate::fromString(root[DATE].toString(), DATESAVEFORMAT));
        k->setStreet(root[STREET].toString());
        k->setCity(root[CITY].toString());
        k->setGroup(root[GROUP].toString());
        k->setMail(root[MAIL].toString());
        k->setNumber(root[NUMBER].toString());
        tables = root[TABLE].toArray();
        table = tables.first().toObject();
        keys = table[KEY].toArray();
        values = table[VALUE].toObject();
        foreach(const QJsonValue & key, keys){
            QString ks = key.toString();
            k->addTableLine(ks, values[ks].toString());
        }
    }
Example #4
0
bool Client::processServerRequest(const BP::Packet &packet){
	setStatus(Client::NotActive);

	last_server_serial = packet.global_serial;

	BP::CommandType command = packet.getCommandType();
	QJsonValue msg = packet.getMessageBody();

	BP::Countdown countdown;
	countdown.current = 0;

	bool use_default = !msg.isArray();
	if(!use_default){
		QJsonArray arr = msg.toArray();
		if(arr.size() <= 1 || !countdown.tryParse(arr.first())){
			use_default = true;
		}
	}
	if(use_default){
		countdown.type = BP::Countdown::UseDefault;
		countdown.max = ServerInfo.getCommandTimeout(command, BP::ClientInstance);
	}

	setCountdown(countdown);

	Callback callback = interactions[command];
	if(!callback){
		return false;
	}
	(this->*callback)(msg);

	return true;
}
Example #5
0
void RPCWallet::transferResponse(const QJsonObject& pObjResponse, const QJsonObject& pObjOriginalParams)
{
    qDebug() << "Received transfer resposnse";
    qDebug() << pObjResponse;
    qDebug() << "With original params : ";
    qDebug() << pObjOriginalParams;

    /* Error */
    if ( pObjResponse["error"].isObject() ) {

        const QJsonObject lError = pObjResponse["error"].toObject();
        int lErrorCode = -1;
        QString lErrorMessage;

        if ( lError.contains("message") ) {
            lErrorMessage = lError["message"].toString();
        }

        if ( lError.contains("code") ) {
            lErrorCode = lError["code"].toInt();
        }

        this->onTransferError(lErrorCode, lErrorMessage);
        return;
    }


    if ( !pObjResponse["tx_hash"].isString() ) {
        qWarning() << "Bad JSON response for transfer : " << pObjResponse;
        return;
    }

    /* TOOD : Create a serialization:deserialization function for this stuff */

    if ( !pObjOriginalParams["destinations"].isArray() ) {
        qCritical() << "transferResponse brought bad original params : " << pObjOriginalParams;
        return;
    }


    QJsonArray lDsts = pObjOriginalParams["destinations"].toArray();
    const QJsonObject& lDestination = lDsts.first().toObject();
    if ( !lDestination["address"].isString() || !lDestination["amount"].isDouble() ) {
        qCritical() << "transferResponse brought bad original params : " << pObjOriginalParams;
        return;
    }

    unsigned long long lOriginalFee = 5000000000uLL;
    if ( pObjOriginalParams["fee"].isDouble() ) {
        lOriginalFee = pObjOriginalParams["fee"].toDouble();
    }

    /* OK */
    onTransferSuccessful(pObjResponse["tx_hash"].toString(), lDestination["amount"].toDouble(), lDestination["address"].toString(), lOriginalFee);

}
Example #6
0
QJsonObject _getArraySchema(const QString& name, const QJsonArray& array)
{
    if (array.isEmpty())
        return {};

    return QJsonObject{{"type", "array"},
                       {"title", name},
                       {"items",
                        _getPropertySchema(name + "_items", array.first())}};
}
Example #7
0
void designer::itunesSearchFinished(QNetworkReply* reply)
{
    QString answ = reply->readAll();

    QJsonDocument doc = QJsonDocument::fromJson(answ.toUtf8());
    QJsonObject jsonObj = doc.object();
    QJsonArray jsonArObj = jsonObj["results"].toArray();
    QJsonObject jsonFirObj = jsonArObj.first().toObject();

    gItL->findChild<QLineEdit*>("itLinkLine")->setText(jsonFirObj.value("collectionViewUrl").toString());
    gItL->findChild<QLineEdit*>("itPicLinkLine")->setText(jsonFirObj.value("artworkUrl100").toString().replace("100x100bb", "1400x1400bb"));

    reply->deleteLater();
}
Example #8
0
DocumentSymbolsResult::DocumentSymbolsResult(const QJsonValue &value)
{
    if (value.isArray()) {
        QJsonArray array = value.toArray();
        if (array.isEmpty()) {
            *this = QList<SymbolInformation>();
        } else {
            QJsonObject arrayObject = array.first().toObject();
            if (arrayObject.contains(rangeKey))
                *this = documentSymbolsResultArray<DocumentSymbol>(array);
            else
                *this = documentSymbolsResultArray<SymbolInformation>(array);
        }
    } else {
        *this = nullptr;
    }
}
void Configuration::read(const QJsonObject &json)
{
    QJsonValue positionValue = json[KEY_POSITION];
    Utils::checkValue(KEY_POSITION, positionValue);
    QJsonObject jsonPosition = positionValue.toObject();

    QJsonValue positionXValue = jsonPosition[KEY_X];
    Utils::checkValue(KEY_X, positionXValue);
    positionX = positionXValue.toInt();

    QJsonValue positionYValue = jsonPosition[KEY_Y];
    Utils::checkValue(KEY_Y, positionYValue);
    positionY = positionYValue.toInt();

    QJsonValue scaleValue = json[KEY_SCALE];
    Utils::checkValue(KEY_SCALE, scaleValue);
    scale = scaleValue.toInt();

    QJsonValue fillValue = json[KEY_FILL];
    Utils::checkValue(KEY_FILL, fillValue);
    fill = fillValue.toBool();

    QJsonValue outlineValue = json[KEY_OUTLINE];
    Utils::checkValue(KEY_OUTLINE, outlineValue);
    outline = outlineValue.toBool();

    QJsonValue glyphsValue = json[KEY_GLYPHS];
    Utils::checkValue(KEY_GLYPHS, glyphsValue);
    if (!glyphsValue.isArray())
    {
        throw JsonParserException("""glyphs"" should be array");
    }
    QJsonArray figuresArray = glyphsValue.toArray();

    figure = new Figure();
    figure->read(figuresArray.first().toObject());

    panel = new Panel();
    panel->read(json);

}
Example #10
0
/* json
HostInfoWidget::HostInfoWidget(QList<QStringList> listOfStringLists, QString TimeFormat,int TimeZone, QString ServiceURL,int uniqObjectID, QWidget * parent, Qt::WindowFlags f): QWidget( parent, f )
{
    uid=uniqObjectID;
    SURL=ServiceURL;

    Hostname=listOfStringLists.at(0).at(0);
    NotesUrl=listOfStringLists.at(0).at(11);
    ActionUrl=listOfStringLists.at(0).at(12);


     resize(800,640);
     setWindowTitle("HostInfo for " + Hostname);
     QGridLayout* mainGrid = new QGridLayout(this);

     //Lets get the info, request was:
     //GET hosts\nColumns:host_name alias display_name address state last_time_down comments_with_info services_with_info contacts downtimes_with_info last_hard_state_change notes_url_expanded action_url_expanded plugin_output contact_groups parents childs  host_groups worst_service_state perf_data\n
     //                     0       1       2           3       4           5           6                   7                   8       9                   10                      11                  12              13              14              15  16      17          18                  19
     //Filter: host_name = " + host +" \nLimit: 1\n";

    int k = 0;
    int r=0;
    mainGrid->addWidget(new QLabel("Hostname:",this),r,0);
    QLabel* L_Hostname = new QLabel(Hostname,this);
            L_Hostname->setTextInteractionFlags(Qt::TextSelectableByMouse);
    mainGrid->addWidget(L_Hostname,r,1,1,2);

    r=1;
    qDebug() <<r;
    mainGrid->addWidget(new QLabel("Address:",this),r,0);
    QLabel* L_Address = new QLabel(listOfStringLists.at(k).at(3),this);
            L_Address->setTextInteractionFlags(Qt::TextSelectableByMouse);
    mainGrid->addWidget(L_Address,r,1,1,2);

    r=2;
    qDebug() <<r;
    mainGrid->addWidget(new QLabel("State:",this),r,0);
    QLabel* stateLabel = new QLabel(this);
    if (listOfStringLists.at(k).at(4) == "0")
    {
        stateLabel->setPixmap(QPixmap(ok_xpm));
    }
    else if (listOfStringLists.at(k).at(4) == "1")
    {
        stateLabel->setPixmap(QPixmap(warning_xpm));

    }
    else if (listOfStringLists.at(k).at(4).toInt() >= 2)
    {
        stateLabel->setPixmap(QPixmap(critical_xpm));
    }
    mainGrid->addWidget(stateLabel,r,1);

    // Plugin OUtput

    QLabel* L_Output = new QLabel(listOfStringLists.at(k).at(13),this);
            L_Output->setTextInteractionFlags(Qt::TextSelectableByMouse);
    mainGrid->addWidget(L_Output,r,2);
    mainGrid->addItem(new QSpacerItem ( 10, 10, QSizePolicy::Expanding, QSizePolicy::Fixed ),r,3);


    //last_hard_state_change

//Item->setText(3,dt.toString("HH:mm dd-MM-yy"));
    r=3;
    //inputTimezone->value()
    QDateTime lcdt = QDateTime::fromString("01-01-70 00:00:00", "dd-MM-yy HH:mm:ss").addSecs(QString(listOfStringLists.at(k).at(10)).toInt()+(3600*TimeZone));
    mainGrid->addWidget(new QLabel("Last Change:",this),r,0);
    QLabel* L_LastChange = new QLabel(lcdt.toString(TimeFormat),this);
            L_LastChange->setTextInteractionFlags(Qt::TextSelectableByMouse);
    mainGrid->addWidget(L_LastChange,r,1,1,2);



    //contacts (8) & contact_groups (14)
    r=4;
    mainGrid->addWidget(new QLabel("Contacts:",this),r,0);
    QComboBox* contactBox = new QComboBox(this);
        contactBox->addItems(listOfStringLists.at(k).at(8).split(","));
    mainGrid->addWidget(contactBox,r,1,1,2);

    r=5;
    mainGrid->addWidget(new QLabel("Groups:",this),r,0);
    QComboBox* contactGroupBox = new QComboBox(this);
        contactGroupBox->addItems(listOfStringLists.at(k).at(14).split(","));
        mainGrid->addWidget(contactGroupBox,r,1,1,2);


    // Hostgroups (17)
    r=6;
    mainGrid->addWidget(new QLabel("Hostgroups:",this),r,0);
    QComboBox* hostGroupBox = new QComboBox(this);
        hostGroupBox->addItems(listOfStringLists.at(k).at(17).split(","));
        mainGrid->addWidget(hostGroupBox,r,1,1,2);

    r=7;
    mainGrid->addWidget(new QLabel(" ",this),r,0);

    r=8;
    mainGrid->addWidget(new QLabel("Services:",this),r,0);
    r=9;
    //services_with_state (7)
    QTreeWidget* serviceTree = new QTreeWidget(this);
        serviceTree->setSelectionMode(QAbstractItemView::SingleSelection);
        serviceTree->setColumnCount(2);
        serviceTree->setMaximumWidth(600);
        serviceTree->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
        QStringList headerLabelsService;
        headerLabelsService << "Service" << "Output";
        serviceTree->setHeaderLabels(headerLabelsService);
        serviceTree->setSortingEnabled (false);
     mainGrid->addWidget(serviceTree,r,0,1,5);



     //QStringList listServices = QString(listOfStringLists.at(k).at(7)).contains();


    QStringList ServiceList;
    QStringList StateList;
    QStringList OutputList;

     // lets get the services (ugly format)
     QString state_with_info="," + QString(listOfStringLists.at(k).at(7));
     QRegularExpression re("(,(\\w|\\d|/|:| )+\\|)");
     QRegularExpressionMatchIterator i = re.globalMatch(state_with_info);
     while (i.hasNext())
     {
         QRegularExpressionMatch match = i.next();

         // Lets create a String List with Service name
         ServiceList << match.captured(0).remove(",").remove("|");

         //Here comes the trick, just remove what we just found, we need it nomore, but don't removw the seperating pipe
         state_with_info.remove(match.captured(0).remove("|"));
         qDebug()<< "use match" << match.captured(0);
     }
     qDebug() << "state_with_info" << state_with_info;

     //Lets find the State
     QRegularExpression re2("\\|\\d+\\|\\d+\\|");
     QRegularExpressionMatchIterator i2 = re2.globalMatch(state_with_info);
     while (i2.hasNext())
     {
            QRegularExpressionMatch match = i2.next();
            qDebug()<< "use match 2" << match.captured(0);
            qDebug() << "state" << match.captured(0).split("|")[1];

            StateList << match.captured(0).split("|")[1];
            state_with_info.replace(match.captured(0),"|");
     }
     qDebug() << "state_with_info" << state_with_info;

     // and last the output (remove first pipe
     state_with_info.remove(0,1);
     OutputList=state_with_info.split("|");

     for (int i=0;i<ServiceList.size();i++)
     {
         qDebug() << "ServicesList" << i << ServiceList.at(i) << StateList.at(i) << OutputList.at(i);
         QStringList tmp;
         tmp << ServiceList.at(i) <<  OutputList.at(i);
            QTreeWidgetItem* Item = new QTreeWidgetItem(tmp,QTreeWidgetItem::Type);
            if (StateList.at(i) == "0")
            {
                Item->setIcon(0, QIcon(QPixmap(ok_xpm)) );
            }
            else if (StateList.at(i) == "1")
            {
                Item->setIcon(0, QIcon(QPixmap(warning_xpm)) );
            }
            else
            {
                Item->setIcon(0, QIcon(QPixmap(critical_xpm)) );
            }
            serviceTree->insertTopLevelItem(0,Item);

     }

     r=1;
     QPushButton* browserUrlButton = new QPushButton("Open in Browser", this);
        connect( browserUrlButton, SIGNAL( pressed()) , this, SLOT( browserUrlButtonPressed() ) );
     mainGrid->addWidget(browserUrlButton,r,4);

     r=2;
     QPushButton* actionUrlButton = new QPushButton("Open Action URL", this);
        connect( actionUrlButton, SIGNAL( pressed()) , this, SLOT( actionUrlButtonPressed() ) );
     mainGrid->addWidget(actionUrlButton,r,4);

     r=3;
     QPushButton* notesUrlButton = new QPushButton("Open Notes URL", this);
        connect( notesUrlButton, SIGNAL( pressed()) , this, SLOT( notesUrlButtonPressed() ) );
     mainGrid->addWidget(notesUrlButton,r,4);

     r=4;
     QPushButton* logButton = new QPushButton("Open Log", this);
        connect( logButton, SIGNAL( pressed()) , this, SLOT( logButtonPressed() ) );
     mainGrid->addWidget(logButton,r,4);


     //Get overallstate
     //worst_service_state (18) + state (4)
     int overallState=listOfStringLists.at(k).at(18).toInt()+listOfStringLists.at(k).at(4).toInt();
     qDebug() << "overallState" << overallState;
     r=1;
     pcDialog = new PCDialog(Hostname, overallState, this);
     connect( pcDialog, SIGNAL(doubleClickedHost(QString)) , this, SLOT( slotDoubleClickedHost(QString) ) );
       mainGrid->addWidget(pcDialog,r,5,9,3);

     //Parents (15)
      parentList=listOfStringLists.at(k).at(15).split(",");
      parentList.sort();
      //pcDialog->setGeneration();
      for (int i=0;i<parentList.size();i++)
      {
          if (!parentList.at(i).trimmed().isEmpty())
          {
            pcDialog->addParent(parentList.at(i));
            //pcDialog->addNode(parentList.at(i),Hostname,127,"parent");
          }
      }

      //Childs (16)
       QStringList childList=listOfStringLists.at(k).at(16).split(",");
       childList.sort();
       for (int i=0;i<childList.size();i++)
       {

           if (!childList.at(i).trimmed().isEmpty())
           {
                pcDialog->addChild(childList.at(i));
                //pcDialog->addNode(childList.at(i),Hostname,127,"child");
           }
       }

       r=0;
       QPushButton* getParentsButton = new QPushButton("Get Parents", this);
          connect( getParentsButton, SIGNAL( pressed()) , this, SLOT( requestParents() ) );
       mainGrid->addWidget(getParentsButton,r,5);

       QPushButton* forceButton = new QPushButton("Force", this);
          connect( forceButton, SIGNAL( pressed()) , pcDialog, SLOT( force() ) );
       mainGrid->addWidget(forceButton,r,6);

       mainGrid->addItem(new QSpacerItem ( 10, 10, QSizePolicy::Expanding, QSizePolicy::Fixed ),r,7);
      //last spacer
        //mainGrid->addItem(new QSpacerItem ( 300, 0, QSizePolicy::Maximum, QSizePolicy::Fixed ),10,1,1,5);
        mainGrid->addItem(new QSpacerItem ( 500, 0, QSizePolicy::Expanding, QSizePolicy::Fixed ),10,5);


}
*/
HostInfoWidget::HostInfoWidget(QJsonArray jsonArray, QString TimeFormat,int TimeZone, QString ServiceURL,int uniqObjectID, QWidget * parent, Qt::WindowFlags f): QWidget( parent, f )
{
    uid=uniqObjectID;
    SURL=ServiceURL;

    Hostname=jsonArray.at(0).toString();
    NotesUrl=jsonArray.at(11).toString();
    ActionUrl=jsonArray.at(12).toString();

    qDebug()<<"hsotname" << Hostname<<NotesUrl<<ActionUrl;

    resize(800,640);
    setWindowTitle("HostInfo for " + Hostname);
    QGridLayout* mainGrid = new QGridLayout(this);

    //Lets get the info, request was:
    //GET hosts\nColumns:host_name alias display_name address state last_time_down comments_with_info services_with_info contacts downtimes_with_info last_hard_state_change notes_url_expanded action_url_expanded plugin_output contact_groups parents childs  host_groups worst_service_state perf_data\n
    //                     0       1       2           3       4           5           6                   7                   8       9                   10                      11                  12              13              14              15  16      17          18                  19
    //Filter: host_name = " + host +" \nLimit: 1\n";

   int k = 0;
   int r=0;
   mainGrid->addWidget(new QLabel("Hostname:",this),r,0);
   QLabel* L_Hostname = new QLabel(Hostname,this);
           L_Hostname->setTextInteractionFlags(Qt::TextSelectableByMouse);
   mainGrid->addWidget(L_Hostname,r,1,1,2);

   r=1;
   qDebug() <<r;
   mainGrid->addWidget(new QLabel("Address:",this),r,0);
   QLabel* L_Address = new QLabel(jsonArray.at(3).toString(),this);
           L_Address->setTextInteractionFlags(Qt::TextSelectableByMouse);
   mainGrid->addWidget(L_Address,r,1,1,2);

   r=2;
   qDebug() <<r;
   mainGrid->addWidget(new QLabel("State:",this),r,0);
   QLabel* stateLabel = new QLabel(this);
   if (jsonArray.at(4).toDouble() == 0)
   {
       stateLabel->setPixmap(QPixmap(ok_xpm));
   }
   else if (jsonArray.at(4).toDouble() == 1)
   {
       stateLabel->setPixmap(QPixmap(warning_xpm));

   }
   else if (jsonArray.at(4).toDouble() >= 2)
   {
       stateLabel->setPixmap(QPixmap(critical_xpm));
   }
   mainGrid->addWidget(stateLabel,r,1);

   // Plugin OUtput

   QLabel* L_Output = new QLabel(jsonArray.at(13).toString(),this);
           L_Output->setTextInteractionFlags(Qt::TextSelectableByMouse);
   mainGrid->addWidget(L_Output,r,2);
   mainGrid->addItem(new QSpacerItem ( 10, 10, QSizePolicy::Expanding, QSizePolicy::Fixed ),r,3);


   //last_hard_state_change

//Item->setText(3,dt.toString("HH:mm dd-MM-yy"));
   r=3;
   //inputTimezone->value()
   QDateTime lcdt = QDateTime::fromString("01-01-70 00:00:00", "dd-MM-yy HH:mm:ss").addSecs(jsonArray.at(10).toDouble()+(3600*TimeZone));
   mainGrid->addWidget(new QLabel("Last Change:",this),r,0);
   QLabel* L_LastChange = new QLabel(lcdt.toString(TimeFormat),this);
           L_LastChange->setTextInteractionFlags(Qt::TextSelectableByMouse);
   mainGrid->addWidget(L_LastChange,r,1,1,2);



   //contacts (8) & contact_groups (14)
   r=4;
   mainGrid->addWidget(new QLabel("Contacts:",this),r,0);
   QComboBox* contactBox = new QComboBox(this);
       QJsonArray jsonContactArray=jsonArray.at(8).toArray();
       for (int i=0;i<jsonContactArray.size();i++)
       {
           contactBox->addItem(jsonContactArray.at(i).toString());
       }
   mainGrid->addWidget(contactBox,r,1,1,2);

   r=5;
   mainGrid->addWidget(new QLabel("Groups:",this),r,0);
   QComboBox* contactGroupBox = new QComboBox(this);
       QJsonArray jsonGroupArray=jsonArray.at(14).toArray();
       for (int i=0;i<jsonGroupArray.size();i++)
       {
           contactGroupBox->addItem(jsonGroupArray.at(i).toString());
       }
    mainGrid->addWidget(contactGroupBox,r,1,1,2);


   // Hostgroups (17)
   r=6;
   mainGrid->addWidget(new QLabel("Hostgroups:",this),r,0);
   QComboBox* hostGroupBox = new QComboBox(this);
       QJsonArray jsonHostGroupArray=jsonArray.at(17).toArray();
       for (int i=0;i<jsonHostGroupArray.size();i++)
       {
           hostGroupBox->addItem(jsonHostGroupArray.at(i).toString());
       }
    mainGrid->addWidget(hostGroupBox,r,1,1,2);

   r=7;
   mainGrid->addWidget(new QLabel(" ",this),r,0);

   r=8;
   mainGrid->addWidget(new QLabel("Services:",this),r,0);

   r=9;
   //services_with_state (7)
   QTreeWidget* serviceTree = new QTreeWidget(this);
       serviceTree->setSelectionMode(QAbstractItemView::SingleSelection);
       serviceTree->setColumnCount(2);
       serviceTree->setMaximumWidth(600);
       serviceTree->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
       QStringList headerLabelsService;
       headerLabelsService << "Service" << "Output";
       serviceTree->setHeaderLabels(headerLabelsService);
       serviceTree->setSortingEnabled (false);
    mainGrid->addWidget(serviceTree,r,0,1,5);


    QJsonArray serviceJsonArray = jsonArray.at(7).toArray();
    qDebug() << "json service size" << serviceJsonArray.size();
    qDebug() << "json service " << serviceJsonArray.first();

    for (int i=0;i<serviceJsonArray.size();i++)
    {
        QJsonArray singleServiceJsonArray = serviceJsonArray.at(i).toArray();
        QStringList tmp;
        tmp << singleServiceJsonArray.at(0).toString() <<  singleServiceJsonArray.at(3).toString();
        qDebug() << "json service list" << singleServiceJsonArray.at(i).toString();
           QTreeWidgetItem* Item = new QTreeWidgetItem(tmp,QTreeWidgetItem::Type);

           if (singleServiceJsonArray.at(1).toDouble() == 0)
           {
               Item->setIcon(0, QIcon(QPixmap(ok_xpm)) );
           }
           else if (singleServiceJsonArray.at(1).toDouble() == 1)
           {
               Item->setIcon(0, QIcon(QPixmap(warning_xpm)) );
           }
           else
           {
               Item->setIcon(0, QIcon(QPixmap(critical_xpm)) );
           }
           serviceTree->insertTopLevelItem(0,Item);

    }

    r=1;
    QPushButton* browserUrlButton = new QPushButton("Open in Browser", this);
       connect( browserUrlButton, SIGNAL( pressed()) , this, SLOT( browserUrlButtonPressed() ) );
    mainGrid->addWidget(browserUrlButton,r,4);

    r=2;
    QPushButton* actionUrlButton = new QPushButton("Open Action URL", this);
       connect( actionUrlButton, SIGNAL( pressed()) , this, SLOT( actionUrlButtonPressed() ) );
    mainGrid->addWidget(actionUrlButton,r,4);

    r=3;
    QPushButton* notesUrlButton = new QPushButton("Open Notes URL", this);
       connect( notesUrlButton, SIGNAL( pressed()) , this, SLOT( notesUrlButtonPressed() ) );
    mainGrid->addWidget(notesUrlButton,r,4);

    r=4;
    QPushButton* logButton = new QPushButton("Open Log", this);
       connect( logButton, SIGNAL( pressed()) , this, SLOT( logButtonPressed() ) );
    mainGrid->addWidget(logButton,r,4);


    //Get overallstate
    //worst_service_state (18) + state (4)
    int overallState=jsonArray.at(18).toDouble()+jsonArray.at(4).toDouble();
    qDebug() << "overallState" << overallState;
    r=1;
    pcDialog = new PCDialog(Hostname, overallState, this);
    connect( pcDialog, SIGNAL(doubleClickedHost(QString)) , this, SLOT( slotDoubleClickedHost(QString) ) );
      mainGrid->addWidget(pcDialog,r,5,9,3);

      QJsonArray parentJsonArray=jsonArray.at(15).toArray();
     //pcDialog->setGeneration();
     for (int i=0;i<parentJsonArray.size();i++)
     {
         if (!parentJsonArray.at(i).toString().trimmed().isEmpty())
         {
           pcDialog->addParent(parentJsonArray.at(i).toString());
         }
     }

     //Childs (16)
     QJsonArray childJsonArray=jsonArray.at(16).toArray();
    //pcDialog->setGeneration();
    for (int i=0;i<childJsonArray.size();i++)
    {
        if (!childJsonArray.at(i).toString().trimmed().isEmpty())
        {
          pcDialog->addChild(childJsonArray.at(i).toString());
        }
    }

      r=0;
      QPushButton* getParentsButton = new QPushButton("Get Parents", this);
         connect( getParentsButton, SIGNAL( pressed()) , this, SLOT( requestParents() ) );
      mainGrid->addWidget(getParentsButton,r,5);

      QPushButton* forceButton = new QPushButton("Force", this);
         connect( forceButton, SIGNAL( pressed()) , pcDialog, SLOT( force() ) );
      mainGrid->addWidget(forceButton,r,6);

      mainGrid->addItem(new QSpacerItem ( 10, 10, QSizePolicy::Expanding, QSizePolicy::Fixed ),r,7);
     //last spacer
       //mainGrid->addItem(new QSpacerItem ( 300, 0, QSizePolicy::Maximum, QSizePolicy::Fixed ),10,1,1,5);
       mainGrid->addItem(new QSpacerItem ( 500, 0, QSizePolicy::Expanding, QSizePolicy::Fixed ),10,5);



}
void FayeConnector::message(QString text)
{
  QJsonParseError err;
  QJsonDocument message = QJsonDocument::fromJson(text.toUtf8(), &err);

  if (err.error != QJsonParseError::NoError)
  {
    qDebug() << "Error parsing JSon " << err.error;
    emit error(err.error);
    return;
  }

  QJsonObject obj;
  if (message.isArray())
  {
    QJsonArray array = message.array();
    QJsonValue val = array.first();
    obj = val.toObject();
  }
  else
    obj = message.object();

  switch(status)
  {
     case CONNECTING:
     {
          QJsonValue successful = obj.value("successful");
          if (successful.toBool())
          {
            clientId = obj.value("clientId").toString();
            status = CONNECTED;
            emit statusChanged(CONNECTED);
          }
          else
            qDebug() << "Something is wrong: " << text;
     }
     break;
     case SUBSCRIBING:
     {
          QJsonValue successful = obj.value("successful");
          if (successful.toBool())
          {
            status = SUBSCRIBED;
            emit statusChanged(SUBSCRIBED);
            this->keepAlive();
          }
          else
            qDebug() << "Something is wrong: " << text;
     }
     break;
     case SUBSCRIBED:
     {
        if (obj.value("channel").toString().contains("/meta/connect", Qt::CaseInsensitive))
        {
            QJsonValue successful = obj.value("successful");
            if (successful.toBool())
              this->keepAlive();
            else
              qDebug() << "Something is wrong: " << text;
        }
        else
        {
            //qDebug() << text;
            emit messageReceived(text);
        }
     }
     break;
     default:
        //do nothing
     break;
   }
}
Example #12
0
/**
 * DBInterface::jsonToDataBufferVector
 * @brief iterate through JSON and return data inside json_ as vector of DataBuffer
 * @param json_ JSON string to convert
 * @return returns a vector of DataBuffer which contains the data inside json_
 *
 * This function can convert a json received from either InfluxDB or TODO
 * to a vector of DataBuffers.
 * If the JSONs origin was InfluxDB, the return values contains a DataBuffer for
 * every DateTime which was requested from InfluxDB.
 */
vector<DataBuffer> DBInterface::jsonToDataBufferVector(const string &json_, const string& dataSource_) {
    vector<DataBuffer> result;
    QString jsonQString(json_.c_str());
    QJsonDocument jsonDocument = QJsonDocument::fromJson(jsonQString.toUtf8());
    QJsonObject jsonObject = jsonDocument.object();

    // parse json from influxdb
    if (jsonObject.contains(QString("results"))) {
        QJsonArray tempArray = jsonObject["results"].toArray();
        QJsonObject tempObject = tempArray.first().toObject();
        if (tempObject.contains(QString("series"))) {
            tempArray = tempObject["series"].toArray();
            tempObject = tempArray.first().toObject();
            if (tempObject.contains(QString("columns")) &&
                tempObject.contains(QString("values" )) ){
                QJsonArray names  = tempObject["columns"].toArray();
                QJsonArray values = tempObject["values" ].toArray();

                // iterate through all datasets
                typedef QJsonArray::iterator it_type;
                for(it_type iterator = values.begin(); iterator != values.end(); iterator++) {
                    QJsonArray dataSet = values.at(iterator.i).toArray();
                    DataBuffer tempDataBuffer;
                    // iterate to all names/values in a dataset
                    for(it_type iterator2 = dataSet.begin(); iterator2 != dataSet.end(); iterator2++) {

                        // get name
                        string name = names.at(iterator2.i).toString().toStdString();
                        // get value
                        QJsonValue valueJSON = dataSet.at(iterator2.i);

                        // set time
                        if (name == "time") {
                            struct tm time = stringToCTime(valueJSON.toString().toStdString());
                            tempDataBuffer.useDateTimes = true;
                            tempDataBuffer.startDateTime = time;
                            tempDataBuffer.endDateTime   = time;
                        } else {
                            // set values
                            double valueDouble = valueJSON.toDouble();
                            tempDataBuffer.data[name] = cutValueToInfluxDBRange(valueDouble);
                        }
                    }
                    // add DataSource;
                    tempDataBuffer.useDataSource = true;
                    tempDataBuffer.dataSource = cleanString(dataSource_);

                    // add data buffer to vector
                    result.push_back(tempDataBuffer);

                }
            } else {
                log << SLevel(ERROR) << "Aborted parsing InfluxDB-Json to databuffer. Unable to find 'columns and/or 'values' in JSON" << endl;
            }
        } else {
            log << SLevel(ERROR) << "Aborted parsing InfluxDB-Json to databuffer. Unable to find 'series' in JSON" << endl;
        }
    }


    return result;
}
Example #13
0
QString Analyzer::funTvAnalyze(QString url)//http://www.sufeinet.com/thread-8196-1-1.html
{
    //qDebug()<<url;
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    QString realUrl;
    QString mediaid;
    QString serial;
    QStringList urlParts = url.split("/");
    QString mediaidPart;
    foreach (QString part, urlParts) {
        if(part.contains("m-"))
        {
            mediaidPart = part;
            break;
        }
    }
    //qDebug()<<mediaidPart;
    QRegExp rx_mediaid("m-\\d{1,10}");//
    QRegExp rx_serial("e-\\d{1,10}");//集数
    //rx_mediaid.setMinimal(true);
    //rx_serial.setMinimal(true);
    int pos_mediaid = rx_mediaid.indexIn(mediaidPart);
    if (pos_mediaid > -1) {
        mediaid = rx_mediaid.cap(0);
    }
    int pos_serial = rx_serial.indexIn(mediaidPart);
    if (pos_serial > -1) {
        serial = rx_serial.cap(0);
    }
    mediaid.replace("m-","");
    serial.replace("e-","");
    //qDebug()<<mediaid<<serial;

    QString hashid;
    QString apiUrl1 = QString("http://api.funshion.com/ajax/vod_panel/%1/w-1").arg(mediaid);
    QNetworkReply *reply = manager->get(QNetworkRequest(QUrl(apiUrl1)));
    QEventLoop loop;
    QTimer::singleShot(8000,&loop,SLOT(quit()));//
    QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();
    QByteArray data = reply->readAll();
    QRegExp rx_hashid("hashid\":\".*\"");
    rx_hashid.setMinimal(true);
    int pos_hashid = rx_hashid.indexIn(data);
    if (pos_hashid > -1) {
        hashid = rx_hashid.cap(0);
    }
    hashid.replace(QRegExp("hashid\":\"|\""),"");
    //qDebug()<<hashid;

    if(serial == "")
    {
        serial = "1";
    }
    //get token
    QString apiUrl2 = QString("http://api.funshion.com/ajax/get_webplayinfo/%1/%2/mp4?user=funshion").arg(mediaid).arg(serial);
    QNetworkReply *reply2 = manager->get(QNetworkRequest(QUrl(apiUrl2)));
    QTimer::singleShot(8000,&loop,SLOT(quit()));//
    QObject::connect(reply2, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();
    data = reply2->readAll();

    QString token;
    QJsonParseError *error=new QJsonParseError;
    QJsonDocument doc =QJsonDocument::fromJson(data,error);
    if(error->error==QJsonParseError::NoError)
    {
        QJsonObject rootObj = doc.object();
        token = rootObj["token"].toString();
    }

    //get realUrl
    QString apiUrl3 = QString("http://jobsfe.funshion.com/query/v1/mp4/%1.json?clifz=fun&mac=&tm=1395365896&token=%2").arg(hashid).arg(token);
    QNetworkReply *reply3 = manager->get(QNetworkRequest(QUrl(apiUrl3)));
    QTimer::singleShot(8000,&loop,SLOT(quit()));//
    QObject::connect(reply3, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();
    data = reply3->readAll();

    QJsonDocument realUrlDoc =QJsonDocument::fromJson(data,error);
    if(error->error==QJsonParseError::NoError)
    {
        QJsonObject rootObj = realUrlDoc.object();
        QJsonArray playlistArray = rootObj["playlist"].toArray();
        QJsonObject obj = playlistArray.first().toObject();
        realUrl = obj["urls"].toArray().first().toString();
    }


    return realUrl;
}
Example #14
0
void MessageTest::toJson()
{
  // Misc objects used in testing:
  QJsonObject testObject;
  testObject.insert("test", QLatin1String("value"));

  QJsonArray testArray;
  testArray.append(QString("Test"));

  QJsonArray testCompositeArray;
  testCompositeArray.append(MoleQueue::idTypeToJson(MoleQueue::InvalidId));
  testCompositeArray.append(testObject);
  testCompositeArray.append(testArray);
  testCompositeArray.append(true);
  testCompositeArray.append(5);
  testCompositeArray.append(5.36893473232); // This will be truncated to %.5f!
  testCompositeArray.append(QString("Abrakadabra"));

  // Test that the idtypeutils is working as expected.
  QVERIFY(testCompositeArray.first().isNull());
  QCOMPARE(MoleQueue::toIdType(testCompositeArray.first()),
           MoleQueue::InvalidId);

  // Invalid message
  Message invalid;
  QCOMPARE(QString(invalid.toJson()),
           QString(ReferenceString("message-ref/invalidJson.json")));

  // Request -- no params
  Message request(Message::Request);
  request.setMethod("testMethod");
  request.setId(MoleQueue::MessageIdType(1));
  QCOMPARE(QString(request.toJson()),
           QString(ReferenceString("message-ref/requestJson-noParams.json")));

  // Request -- object params
  request.setParams(testObject);
  QCOMPARE(QString(request.toJson()),
           QString(ReferenceString("message-ref/requestJson-objectParams.json")));

  // Request -- array params
  request.setParams(testArray);
  QCOMPARE(QString(request.toJson()),
           QString(ReferenceString("message-ref/requestJson-arrayParams.json")));

  // Notification -- no params
  Message notification(Message::Notification);
  notification.setMethod("poke");
  QCOMPARE(QString(notification.toJson()),
           QString(ReferenceString("message-ref/notificationJson-noParams.json")));

  // Notification -- object params
  notification.setParams(testObject);
  QCOMPARE(QString(notification.toJson()),
           QString(ReferenceString("message-ref/notificationJson-objectParams.json")));

  // Notification -- array params
  notification.setParams(testArray);
  QCOMPARE(QString(notification.toJson()),
           QString(ReferenceString("message-ref/notificationJson-arrayParams.json")));

  // Response
  Message response(Message::Response);
  response.setId(MoleQueue::MessageIdType(42));
  response.setMethod("Won't be in JSON string for response.");
  response.setResult(testCompositeArray);
  QCOMPARE(QString(response.toJson()),
           QString(ReferenceString("message-ref/responseJson.json")));

  // Error -- no data
  Message error(Message::Error);
  error.setId(MoleQueue::MessageIdType(13));
  error.setMethod("Won't be in JSON string for error.");
  error.setErrorCode(666);
  error.setErrorMessage("Server is possessed.");
  QCOMPARE(QString(error.toJson()),
           QString(ReferenceString("message-ref/errorJson-noData.json")));

  // Error -- primitive data
  error.setErrorData(55);
  QCOMPARE(QString(error.toJson()),
           QString(ReferenceString("message-ref/errorJson-primData.json")));

  // Error -- object data
  error.setErrorData(testObject);
  QCOMPARE(QString(error.toJson()),
           QString(ReferenceString("message-ref/errorJson-objectData.json")));

  // Error -- array data
  error.setErrorData(testArray);
  QCOMPARE(QString(error.toJson()),
           QString(ReferenceString("message-ref/errorJson-arrayData.json")));
}
Example #15
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;
		}
		}
	});
}