Commit e054d008 authored by Floréal Cabanettes's avatar Floréal Cabanettes

Add retrieve of recipe from a pywebcooking website

parent 65f585d6
......@@ -68,6 +68,7 @@ public:
QStringList preparation, QStringList conseils, QString picture, QMap<QString, QString> liens,
QString filename, QString coupDeCoeur, int idRecipe);
static bool saveRecipeFromDist(QString title, QStringList categories, QString content, QString picture, QString coupDeCoeur, QFile *file, int idRecipe);
static bool saveRecipeFromPwcJson(QVariantMap recipe, int config, QFile *tmpFile);
static QMap<QString, QStringList> loadRecipe(QString fileName);
static QStringList loadCategories();
static QString generateHtmlCode(QString titre, QString mainPicture, int hPrep, int minPrep, int hCuis, int minCuis, int jRep,
......@@ -81,6 +82,7 @@ public:
static QString getNumberedList(QStringList items, int config);
static QStringList makeNumberedList(QString text);
static QString insertLinks(QString data);
static int restoreLinks(QString *data, QMap<QString, QString> *liens, int nbLien);
static QString insertPictures(QString data, int config);
static QString insertMovies(QString data);
static QStringList getSelectedCategories(QMap<QCheckBox*, QString> categories);
......
......@@ -15,10 +15,12 @@
#define OPENDISTANT_H
#include "filedownloader.h"
#include "httprequestworker.h"
#include "login.h"
#include <QCheckBox>
#include <QDialog>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QList>
......@@ -27,6 +29,8 @@
#include <QRegExp>
#include <QScrollArea>
#include <QVBoxLayout>
#include <QVariantMap>
#include <QVariantList>
namespace Ui {
class OpenDistant;
......@@ -42,6 +46,7 @@ public:
void init();
int idRecipeToOpen;
int config;
QString user, passwd;
private slots:
void on_search_textChanged(const QString &arg1);
......@@ -55,6 +60,8 @@ private slots:
void on_pushButton_clicked();
void handle_result(HttpRequestWorker* worker);
private:
Ui::OpenDistant *ui;
QWidget *parentWidget;
......@@ -63,6 +70,11 @@ private:
QMap<QString, QStringList > recipesByCats;
void updateNbRecipes(int nbRecipes);
QList<QCheckBox*> cboxes;
void openFromPwc(int config);
void openFromWp(int config);
void addRecipe(QVariantMap recipe);
void refreshRecipesList();
QDialog *openInProgress;
};
#endif // OPENDISTANT_H
......@@ -81,6 +81,7 @@ public:
bool isMax;
void setLogoWindow();
QString openStartupFile;
void setIdLink(int my_idLink);
private slots:
......@@ -218,6 +219,8 @@ private slots:
void received_categories(HttpRequestWorker *worker);
void received_recipe(HttpRequestWorker *worker);
public slots:
void init();
void config();
......@@ -251,6 +254,7 @@ private:
QString balise; //Stores the tag that will be deleted
QStringList balises; //Stores tags that will be deleted
int resetPosCaret; //Stores position of the cursot at which we must set cursor after deleting tags
int tmp_idconf;
int roundValueToFive(double value);
bool askSaveFile();
void toggleEditPict();
......@@ -308,6 +312,8 @@ private:
void loadRecipe(QString fileName, bool testReadyToSend);
void searchUpdate();
void startAbcCheck(bool silent);
void openDistRecipeWp(int idConf, int idRecipeToOpen);
void openDistRecipePwc(int idConf, int idRecipeToOpen, QString user, QString passwd);
};
#endif // CECWRITER_H
This diff is collapsed.
......@@ -35,7 +35,8 @@ void OpenDistant::init() {
Login *login = new Login((QWidget*)this->parent());
login->init(false);
if (login->getAccepted()) {
QString pseudoWp = login->getUsername();
user = login->getUsername();
passwd = login->getPassword();
config = login->getConfig();
ui->categoriesBox->setContentsMargins(0,10,0,0);
......@@ -52,47 +53,117 @@ void OpenDistant::init() {
cboxes.append(catI);
connect(catI, SIGNAL(stateChanged(int)), this, SLOT(stateChanged()));;
}
FileDownloader *fdower = new FileDownloader(serverConfs[config]["addrSite"] + "/requests/getPostsJson.php?user=" + \
pseudoWp, tr("Récupération de la liste des recettes..."), parentWidget);
QByteArray resData = fdower->downloadedData();
QJsonParseError ok;
QJsonDocument jsonDoc = QJsonDocument::fromJson(resData, &ok);
if (!jsonDoc.isNull() && ! jsonDoc.isEmpty()) {
QJsonObject json = jsonDoc.object();
QVariantMap result = json.toVariantMap();
if (result["success"].toString() == "true") {
QList<QVariant> recipesRaw = result["recettes"].toList();
foreach (QVariant recipeRaw, recipesRaw) {
QMap<QString, QVariant> recipe = recipeRaw.toMap();
QStringList catsOld = recipe["cats"].toStringList();
QStringList catsNew;
foreach (QString catO, catsOld) {
catsNew.append(catO.replace("&", ""));
}
recipe["cats"] = catsNew;
recipes[recipe["title"].toString()] = recipe;
foreach (QString cat, recipe["cats"].toStringList()) {
recipesByCats[cat].append(recipe["title"].toString());
}
items.append(recipe["title"].toString());
}
ui->listRecipes->addItems(items);
ui->listRecipes->sortItems();
updateNbRecipes(items.count());
}
else {
QMessageBox::critical(this, tr("Erreur !"), tr("Une erreur est survenue lors de la récupération de la liste des recettes\nVeuillez contacter le support."),
QMessageBox::Ok);
if (serverConfs[config]["typeServer"] == "wordpress") {
this->openFromWp(config);
}
else if (serverConfs[config]["typeServer"] == "pywebcooking") {
this->openFromPwc(config);
}
}
}
void OpenDistant::addRecipe(QVariantMap recipe) {
QStringList catsOld = recipe["categories"].toStringList();
QStringList catsNew;
foreach (QString catO, catsOld) {
catsNew.append(catO.replace("&", ""));
}
recipe["categories"] = catsNew;
recipes[recipe["title"].toString()] = recipe;
foreach (QString cat, recipe["categories"].toStringList()) {
recipesByCats[cat].append(recipe["title"].toString());
}
items.append(recipe["title"].toString());
}
void OpenDistant::refreshRecipesList() {
ui->listRecipes->clear();
ui->listRecipes->addItems(items);
ui->listRecipes->sortItems();
updateNbRecipes(items.count());
}
void OpenDistant::openFromWp(int config) {
FileDownloader *fdower = new FileDownloader(serverConfs[config]["addrSite"] + "/requests/getPostsJson.php?user=" + \
user, tr("Récupération de la liste des recettes..."), parentWidget);
QByteArray resData = fdower->downloadedData();
QJsonParseError ok;
QJsonDocument jsonDoc = QJsonDocument::fromJson(resData, &ok);
if (!jsonDoc.isNull() && ! jsonDoc.isEmpty()) {
QJsonObject json = jsonDoc.object();
QVariantMap result = json.toVariantMap();
if (result["success"].toString() == "true") {
QList<QVariant> recipesRaw = result["recettes"].toList();
foreach (QVariant recipeRaw, recipesRaw) {
QVariantMap recipe = recipeRaw.toMap();
recipe["categories"] = recipe["cats"];
this->addRecipe(recipe);
}
this->refreshRecipesList();
this->exec();
}
else {
QMessageBox::critical(this, tr("Erreur !"), tr("Une erreur est survenue lors de la récupération de la liste des recettes\nVeuillez contacter le support."),
QMessageBox::Ok);
qCritical() << "Error while parsing JSON: " + ok.errorString();
QMessageBox::Ok);
}
}
else {
QMessageBox::critical(this, tr("Erreur !"), tr("Une erreur est survenue lors de la récupération de la liste des recettes\nVeuillez contacter le support."),
QMessageBox::Ok);
qCritical() << "Error while parsing JSON: " + ok.errorString();
}
}
void OpenDistant::openFromPwc(int config) {
openInProgress = new QDialog((QWidget*)this->parent());
openInProgress->setModal(true);
QLabel *lab = new QLabel("<b>" + tr("Récupération des recettes...") + "</b>");
lab->setAlignment(Qt::AlignCenter);
openInProgress->setWindowTitle("QRecipeWriter");
QHBoxLayout *layEnvoiEnCours = new QHBoxLayout();
layEnvoiEnCours->addWidget(lab);
openInProgress->setLayout(layEnvoiEnCours);
openInProgress->setFixedSize(300,50);
openInProgress->setModal(false);
HttpRequestInput input(serverConfs[config]["addrSite"] + "/api/", "GET", user, passwd);
HttpRequestWorker *worker = new HttpRequestWorker(this);
connect(worker, SIGNAL(on_execution_finished(HttpRequestWorker*)), this, SLOT(handle_result(HttpRequestWorker*)));
worker->execute(&input);
openInProgress->exec();
}
this->exec();
void OpenDistant::handle_result(HttpRequestWorker *worker) {
openInProgress->close();
if (worker->error_type == QNetworkReply::NoError) {
// communication was successful
QJsonParseError *error = new QJsonParseError();
QJsonDocument jsondoc = QJsonDocument::fromJson(worker->response, error);
if (error->error == QJsonParseError::NoError) {
QJsonArray jsonobj = jsondoc.array();
QVariantList recipes_r = jsonobj.toVariantList();
foreach (QVariant recipe_raw, recipes_r) {
QVariantMap recipe = recipe_raw.toMap();
this->addRecipe(recipe);
}
this->refreshRecipesList();
this->exec();
}
else {
qDebug() << worker->response;
qCritical() << "Error while parsing JSON: " + error->errorString();
QMessageBox::critical((QWidget*)this->parent(), tr("Une erreur est survenue"), tr("Impossible de lire la réponse du serveur. Merci de rapporter le bug."));
}
}
else {
// an error occurred
if (worker->error_type == QNetworkReply::ContentOperationNotPermittedError) {
QMessageBox::critical((QWidget*)this->parent(), tr("Une erreur est survenue"), "Votre identificant ou vote mot de passe est incorrect");
}
else {
QMessageBox::critical((QWidget*)this->parent(), tr("Une erreur est survenue"), worker->error_str);
}
}
}
......
......@@ -1657,7 +1657,6 @@ void QRecipeWriter::on_envoyer_clicked()
}
void QRecipeWriter::received_categories(HttpRequestWorker *worker) {
qDebug() << "PASS HERE";
if (worker->error_type == QNetworkReply::NoError) {
QJsonParseError *error = new QJsonParseError();
QJsonDocument jsondoc = QJsonDocument::fromJson(worker->response, error);
......@@ -1686,9 +1685,7 @@ void QRecipeWriter::received_categories(HttpRequestWorker *worker) {
void QRecipeWriter::on_sync_cats_clicked()
{
qDebug() << "PASS";
QString api_url = addrSite + (addrSite.endsWith("/") ? "" : "/") + "api/categories/";
qDebug() << api_url;
HttpRequestInput input(api_url, "GET");
HttpRequestWorker *worker = new HttpRequestWorker(this);
connect(worker, SIGNAL(on_execution_finished(HttpRequestWorker*)), this, SLOT(received_categories(HttpRequestWorker*)));
......@@ -2360,42 +2357,93 @@ void QRecipeWriter::on_actionOuvrir_une_recette_en_ligne_triggered()
int idRecipeToOpen = openDistant->idRecipeToOpen;
int idConf = openDistant->config;
QString user = openDistant->user;
QString passwd = openDistant->passwd;
//Delete pointer after close event:
delete openDistant;
openDistant = NULL;
if (idRecipeToOpen > -1) {
FileDownloader *fdower = new FileDownloader(serverConfs[idConf]["addrSite"] + "/requests/getPost.php?p=" + QString::number(idRecipeToOpen), tr("Récupération de la recette..."), this);
QByteArray resData = fdower->downloadedData();
QJsonParseError ok;
QJsonDocument jsonDoc = QJsonDocument::fromJson(resData, &ok);
if (!jsonDoc.isNull() && ! jsonDoc.isEmpty()) {
QJsonObject json = jsonDoc.object();
QVariantMap result = json.toVariantMap();
if (result["success"].toString() == "true") {
QString imgFileDist = result["thumbnailFile"].toString();
QFile *tmpFile = new QFile(dirTmp + "/recipe" + QString::number(QDateTime::currentMSecsSinceEpoch()) + ".rct");
tmpFile->remove(".");
bool success = Functions::saveRecipeFromDist(result["title"].toString(), result["cats"].toStringList(), result["content"].toString(), imgFileDist, result["coupDeCoeur"].toString(), tmpFile, idRecipeToOpen);
if (success) {
loadRecipe(tmpFile->fileName(), true);
}
else {
QMessageBox::critical(this, tr("Erreur !"), tr("Une erreur est survenue lors de la récupération de la recette\nVeuillez contacter le support."),
QMessageBox::Ok);
}
}
else {
QMessageBox::critical(this, tr("Erreur !"), tr("Une erreur est survenue lors de la récupération de la recette\nVeuillez contacter le support."),
QMessageBox::Ok);
}
if (serverConfs[idConf]["typeServer"] == "wordpress") {
this->openDistRecipeWp(idConf, idRecipeToOpen);
}
else if (serverConfs[idConf]["typeServer"] == "pywebcooking") {
this->openDistRecipePwc(idConf, idRecipeToOpen, user, passwd);
}
}
}
}
void QRecipeWriter::openDistRecipeWp(int idConf, int idRecipeToOpen) {
FileDownloader *fdower = new FileDownloader(serverConfs[idConf]["addrSite"] + "/requests/getPost.php?p=" + QString::number(idRecipeToOpen), tr("Récupération de la recette..."), this);
QByteArray resData = fdower->downloadedData();
QJsonParseError ok;
QJsonDocument jsonDoc = QJsonDocument::fromJson(resData, &ok);
if (!jsonDoc.isNull() && ! jsonDoc.isEmpty()) {
QJsonObject json = jsonDoc.object();
QVariantMap result = json.toVariantMap();
if (result["success"].toString() == "true") {
QString imgFileDist = result["thumbnailFile"].toString();
QFile *tmpFile = new QFile(dirTmp + "/recipe" + QString::number(QDateTime::currentMSecsSinceEpoch()) + ".rct");
tmpFile->remove(".");
bool success = Functions::saveRecipeFromDist(result["title"].toString(), result["cats"].toStringList(), result["content"].toString(), imgFileDist, result["coupDeCoeur"].toString(), tmpFile, idRecipeToOpen);
if (success) {
loadRecipe(tmpFile->fileName(), true);
}
else {
QMessageBox::critical(this, tr("Erreur !"), tr("Une erreur est survenue lors de la récupération de la recette\nVeuillez contacter le support."),
QMessageBox::Ok);
qCritical() << "Error while parsing JSON: " + ok.errorString();
QMessageBox::critical(this, tr("Erreur !"), tr("Une erreur est survenue lors de la récupération de la recette\nVeuillez contacter le support."),
QMessageBox::Ok);
}
}
else {
QMessageBox::critical(this, tr("Erreur !"), tr("Une erreur est survenue lors de la récupération de la recette\nVeuillez contacter le support."),
QMessageBox::Ok);
}
}
else {
QMessageBox::critical(this, tr("Erreur !"), tr("Une erreur est survenue lors de la récupération de la recette\nVeuillez contacter le support."),
QMessageBox::Ok);
qCritical() << "Error while parsing JSON: " + ok.errorString();
}
}
void QRecipeWriter::openDistRecipePwc(int idConf, int idRecipeToOpen, QString user, QString passwd) {
HttpRequestInput input(serverConfs[idConf]["addrSite"] + "/api/recipe/by-id/" + QString::number(idRecipeToOpen), "GET", user, passwd);
HttpRequestWorker *worker = new HttpRequestWorker(this);
tmp_idconf = idConf;
connect(worker, SIGNAL(on_execution_finished(HttpRequestWorker*)), this, SLOT(received_recipe(HttpRequestWorker*)));
worker->execute(&input);
}
void QRecipeWriter::received_recipe(HttpRequestWorker *worker) {
if (worker->error_type == QNetworkReply::NoError) {
// communication was successful
QJsonParseError *error = new QJsonParseError();
QJsonDocument jsondoc = QJsonDocument::fromJson(worker->response, error);
if (error->error == QJsonParseError::NoError) {
QJsonObject jsonobj = jsondoc.object();
QVariantMap recipe_r = jsonobj.toVariantMap();
QFile *tmpFile = new QFile(dirTmp + "/recipe" + QString::number(QDateTime::currentMSecsSinceEpoch()) + ".rct");
tmpFile->remove(".");
bool success = Functions::saveRecipeFromPwcJson(recipe_r, tmp_idconf, tmpFile);
if (success) {
loadRecipe(tmpFile->fileName(), true);
}
}
else {
qDebug() << worker->response;
qCritical() << "Error while parsing JSON: " + error->errorString();
QMessageBox::critical((QWidget*)this->parent(), tr("Une erreur est survenue"), tr("Impossible de lire la réponse du serveur. Merci de rapporter le bug."));
}
}
else {
// an error occurred
if (worker->error_type == QNetworkReply::ContentOperationNotPermittedError) {
QMessageBox::critical((QWidget*)this->parent(), tr("Une erreur est survenue"), "Votre identificant ou vote mot de passe est incorrect");
}
else {
QMessageBox::critical((QWidget*)this->parent(), tr("Une erreur est survenue"), worker->error_str);
}
}
}
......@@ -5394,3 +5442,7 @@ void QRecipeWriter::on_tab_mats_currentChanged(int index)
ui->comment_mat->setFocus();
}
}
void QRecipeWriter::setIdLink(int my_IdLink) {
idLien = my_IdLink;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment