Commit 65cc308a authored by Floréal Cabanettes's avatar Floréal Cabanettes

Wordpress: Use new Wordpress REST API to load/receive recipe (using our...

Wordpress: Use new Wordpress REST API to load/receive recipe (using our Wordpress plugin) instead of XML-RPC + ! DROP JAVA REQUIREMENT !
parent 1cf3fbec
......@@ -104,6 +104,7 @@ public:
static void write_categories_file(QStringList new_cats);
static QString get_ingredient_type(QString ingr);
static bool validate_quantity(QString qte);
static QStringList get_wp_tags(QVariantList tags);
};
#endif // FUNCTIONS_H
......@@ -70,8 +70,7 @@ private:
QMap<QString, QStringList > recipesByCats;
void updateNbRecipes(int nbRecipes);
QList<QCheckBox*> cboxes;
void openFromPwc(int config);
void openFromWp(int config);
void open(int config, QString typeServer);
void addRecipe(QVariantMap recipe);
void refreshRecipesList();
QDialog *openInProgress;
......
......@@ -53,6 +53,7 @@
#include <qmath.h>
#include <QMessageBox>
#include <QPainter>
#include <QPlainTextEdit>
#include <QPixmap>
#include <QRegExp>
#include <QStandardItem>
......@@ -221,6 +222,8 @@ private slots:
void received_recipe(HttpRequestWorker *worker);
void received_recipe_wp(HttpRequestWorker *worker);
public slots:
void init();
void config();
......
/*
* © 2013-2016 Flo-Art.fr
*
* QRecipeWriter et l'ensemble de ses putils est fournit sous la licence Creative Common BY-NC-SA.
* Toutes les modifications et la redistribution sont autorisés pour une utilisation NON COMMERCIALE.
* Par ailleurs, les modifications et la reproduction doivent respecter les règles ci-dessous :
* - Cette en-tête doit être maintenue.
* - Vous devez redistribuer la version modifiée ou non sous licence Creative Common au moins autant
* restrictive.
* - Flo-Art.fr ne peut être tenu pour responsable des versions modifiées et/ou redistribuées.
* - Toute utilisation commerciale partielle ou complète est interdite.
*/
#ifndef SENDWORDPRESS_H
#define SENDWORDPRESS_H
#ifndef SENDAUTOMATIC_H
#define SENDAUTOMATIC_H
#include "functions.h"
#include "login.h"
#include <QCoreApplication>
#include <QDataStream>
#include <QDialog>
#include <QKeyEvent>
#include <QPlainTextEdit>
#include <QDebug>
#include <QHash>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QMessageBox>
#include <QNetworkReply>
#include <QProcess>
#include <QRegExp>
#include <QWidget>
#include "filenotfoundexception.h"
#include "functions.h"
#include "globalexception.h"
#include "httprequestworker.h"
class SendWordpress : public QDialog
{
......@@ -30,37 +24,26 @@ class SendWordpress : public QDialog
public:
explicit SendWordpress(QWidget *parent = 0);
~SendWordpress();
void init(QString htmlCode_lu, QString titre_lu, QStringList categories_lu, QList<int> tpsPrep, QList<int> tpsCuis,
QList<int> tpsRep, QString mainPicture_lu, QString excerpt_lu, QString coupDeCoeur_lu,
QString user_lu, QString passwd_lu, int config_lu, bool publier_lu, QDialog *envoiEnCours_lu);
private slots:
void errorDetails_clicked();
void errorOk_clicked();
void init(QString htmlCode_lu, QString title_lu, QString mainPicture_lu, QString mainPictureName_lu,
QString excerpt_lu, QString coupDeCoeur_lu,
QList<int> tpsPrep_lu, QList<int> tpsCuis_lu, QList<int> tpsRep_lu, QStringList categories_lu,
bool publish_lu, QString user_lu, QString password_lu, int config_lu, QDialog *envoiEnCours_lu);
private:
QString htmlCode, excerpt, titre, mainPicture, tags;
QString htmlCode, title, mainPicture, mainPictureName, precision, description, excerpt, coupDeCoeur, tags;
int tpsPrep, tpsCuis, tpsRep;
QStringList categories;
QString user, passwd;
int config;
bool publier;
QString resultSend;
bool publish;
QDialog *envoiEnCours;
QDialog *errorShow;
QVBoxLayout *verrorShowContent;
QPlainTextEdit *showError;
bool isErrorDetailsOpened;
QLabel *mainError;
QSize errorSize;
QPushButton *details;
bool isSending;
private slots:
void handle_result(HttpRequestWorker *worker);
private:
QString makeExcerpt (QStringList descWords, QString tpsPrep, QString tpsCuis, QString tpsRep);
QString makeTags(QList<int> tpsPrep, QList<int> tpsCuis, QList<int> tpsRep);
void sendRecipe();
QString makeTags(QList<int> tpsPrep, QList<int> tpsCuis, QList<int> tpsRep);
};
#endif // SENDAUTOMATIC_H
#endif // SENDWORDPRESS_H
......@@ -1716,3 +1716,13 @@ bool Functions::validate_quantity(QString qte) {
QRegExp expQte("\\d+([/.,]\\d+)?");
return qte.isEmpty() || expQte.exactMatch(qte);
}
QStringList Functions::get_wp_tags(QVariantList tags) {
QStringList tags_list;
foreach (QVariant tag_v, tags) {
QVariantMap tag = tag_v.toMap();
tags_list.append(tag["name"].toString());
}
return tags_list;
}
......@@ -54,12 +54,7 @@ void OpenDistant::init() {
connect(catI, SIGNAL(stateChanged(int)), this, SLOT(stateChanged()));;
}
if (serverConfs[config]["typeServer"] == "wordpress") {
this->openFromWp(config);
}
else if (serverConfs[config]["typeServer"] == "pywebcooking") {
this->openFromPwc(config);
}
this->open(config, serverConfs[config]["typeServer"]);
}
}
......@@ -84,39 +79,7 @@ void OpenDistant::refreshRecipesList() {
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);
}
}
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) {
void OpenDistant::open(int config, QString typeServer) {
openInProgress = new QDialog((QWidget*)this->parent());
openInProgress->setModal(true);
QLabel *lab = new QLabel("<b>" + tr("Récupération des recettes...") + "</b>");
......@@ -127,7 +90,13 @@ void OpenDistant::openFromPwc(int config) {
openInProgress->setLayout(layEnvoiEnCours);
openInProgress->setFixedSize(300,50);
openInProgress->setModal(false);
HttpRequestInput input(serverConfs[config]["addrSite"] + "/api/", "GET", user, passwd);
HttpRequestInput input;
if (typeServer == "pywebcooking") {
input = HttpRequestInput(serverConfs[config]["addrSite"] + "/api/", "GET", user, passwd);
}
else { // IS wordpress
input = HttpRequestInput(serverConfs[config]["addrSite"] + "/wp-json/qrecipewriter/v1/posts/" + user, "GET");
}
HttpRequestWorker *worker = new HttpRequestWorker(this);
connect(worker, SIGNAL(on_execution_finished(HttpRequestWorker*)), this, SLOT(handle_result(HttpRequestWorker*)));
worker->execute(&input);
......
......@@ -1702,16 +1702,14 @@ void QRecipeWriter::on_sync_cats_clicked()
void QRecipeWriter::sendWordpress(QString user, QString password, int config, bool publier, QDialog *envoiEnCours)
{
makeHtmlCode(config);
SendWordpress *sendWp = new SendWordpress(this);
QStringList cats = Functions::getSelectedCategories(categories);
QList<int> tpsPrep, tpsCuis, tpsRep;
tpsPrep << ui->hPrep->value() << ui->minPrep->value();
tpsCuis << ui->hCuis->value() << ui->minCuis->value();
tpsRep << ui->jRep->value() << ui->hRep->value() << ui->minRep->value();
sendWp->init(htmlCode, ui->titre->text(), cats, tpsPrep, tpsCuis, tpsRep, imgFile, excerpt, coupDeCoeur,
user, password, config, publier, envoiEnCours);
delete sendWp;
sendWp = NULL;
SendWordpress *sendWp = new SendWordpress(this);
sendWp->init(htmlCode, ui->titre->text(), imgFile, imgFileName, excerpt, coupDeCoeur, tpsPrep, tpsCuis,
tpsRep, cats, publier, user, password, config, envoiEnCours);
}
void QRecipeWriter::sendPyWebCooking(QString user, QString password, int config, bool publier, QDialog *envoiEnCours) {
......@@ -2377,38 +2375,15 @@ void QRecipeWriter::on_actionOuvrir_une_recette_en_ligne_triggered()
}
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);
}
}
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();
}
HttpRequestInput input(serverConfs[idConf]["addrSite"] + "/wp-json/qrecipewriter/v1/post/" + QString::number(idRecipeToOpen), "GET");
HttpRequestWorker *worker = new HttpRequestWorker(this);
tmp_idconf = idConf;
connect(worker, SIGNAL(on_execution_finished(HttpRequestWorker*)), this, SLOT(received_recipe_wp(HttpRequestWorker*)));
worker->execute(&input);
}
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);
......@@ -2417,6 +2392,43 @@ void QRecipeWriter::openDistRecipePwc(int idConf, int idRecipeToOpen, QString us
worker->execute(&input);
}
void QRecipeWriter::received_recipe_wp(HttpRequestWorker *worker) {
if (worker->error_type == QNetworkReply::NoError) {
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();
QString imgFileDist = recipe_r["thumbnailFile"].toString();
QFile *tmpFile = new QFile(dirTmp + "/recipe" + QString::number(QDateTime::currentMSecsSinceEpoch()) + ".rct");
tmpFile->remove(".");
QString cdc_lu = "no_coup_de_coeur";
QStringList tags = Functions::get_wp_tags(recipe_r["tags"].toList());
if (tags.contains("coup_de_coeur_1")) {
cdc_lu = "coup_de_coeur_1";
}
else if (tags.contains("coup_de_coeur_2")) {
cdc_lu = "coup_de_coeur_2";
}
else if (tags.contains("coup_de_coeur_3")) {
cdc_lu = "coup_de_coeur_3";
}
bool success = Functions::saveRecipeFromDist(recipe_r["title"].toString(), recipe_r["categories"].toStringList(), recipe_r["content"].toString(), imgFileDist, cdc_lu, tmpFile, recipe_r["id"].toInt());
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 {
QMessageBox::critical((QWidget*)this->parent(), tr("Une erreur est survenue"), worker->error_str);
}
}
void QRecipeWriter::received_recipe(HttpRequestWorker *worker) {
if (worker->error_type == QNetworkReply::NoError) {
// communication was successful
......
......@@ -3,6 +3,7 @@
extern QHash<int,QHash<QString, QString>> serverConfs;
extern QString cmdNav; //Command to launch navigator
extern int idRecipe;
extern QStringList otherPicts;
SendPyWebCooking::SendPyWebCooking(QWidget *parent) :
QDialog(parent)
......
This diff is collapsed.
Manifest-Version: 1.0
Class-Path: SendToWordpress_lib/xmlrpc-1.1.1.jar SendToWordpress_lib/jwordpress-0.5.1-cec3.jar
Main-Class: sendtowordpress.SendToWordpress
../wordpress/SendToWordpress_lib
\ No newline at end of file
package sendtowordpress;
import java.awt.HeadlessException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.Reader;
import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.bican.wordpress.MediaObject;
import net.bican.wordpress.Page;
import net.bican.wordpress.Wordpress;
import redstone.xmlrpc.XmlRpcArray;
import redstone.xmlrpc.XmlRpcException;
import redstone.xmlrpc.XmlRpcFault;
public class SendToWordpress {
static String user;
static String password;
static String xmlRpcUrl;
static String titre;
static String categories;
static String tags;
static String mainPict;
static String otherPicts;
static String htmlCode;
static String excerpt;
static String idRecipe;
static boolean publier;
public static void main(String[] args)
throws IOException {
if (args.length != 8) {
System.out.println("ERREUR : nombre d'arguments incorrect (" + args.length + "). Veuillez rapporter le bug.");
System.out.println("\"" + String.join("\", \"", args) + "\"");
} else {
xmlRpcUrl = args[0];
categories = args[1];
tags = args[2];
mainPict = args[3];
File htmlFile = new File(args[4]);
String contentFile = loadFile(htmlFile);
String[] parts = contentFile.split("\n");
user = parts[0].replace("\r", "");
password = parts[1].replace("\r", "");
titre = parts[2].replace("\r", "");
excerpt = parts[3].replace("\r", "");
int i = 4;
while (!parts[i].replace("\r", "").equals("<htmlCode>")) {
excerpt = excerpt + "\n" + parts[i].replace("\r", "");
i++;
}
htmlCode = parts[(i + 1)];
for (int j = i + 2; j < parts.length; j++) {
htmlCode = htmlCode + "\n" + parts[j];
}
otherPicts = args[5];
publier = "true".equals(args[6]);
idRecipe = args[7];
if ((xmlRpcUrl != null) && (categories != null) && (mainPict != null) && (user != null) && (password != null) && (titre != null) && (excerpt != null) && (htmlCode != null) && (idRecipe != null)) {
sendRecipe();
} else {
System.out.println("ERREUR : Le fichier envoyé est incorrect. Veuillez rapporter le bug.");
}
}
}
private static void sendRecipe() {
try {
Wordpress wp = new Wordpress(user, password, xmlRpcUrl);
Page post = new Page();
post.setTitle(titre);
XmlRpcArray cats = new XmlRpcArray();
if (!"null".equals(tags)) {
post.setMt_keywords(tags);
}
List<String> catsRead = Arrays.asList(categories.split("\\|"));
cats.addAll(catsRead);
post.setCategories(cats);
post.setDescription(htmlCode);
post.setExcerpt(excerpt);
String post_id;
if (idRecipe.equals("-1")) {
post_id = wp.newPost(post, publier);
} else {
post_id = idRecipe;
}
if (!mainPict.startsWith("http")) {
MediaObject mediaImg = wp.newMediaObject("image/jpg", new File(mainPict), Boolean.FALSE, post_id);
post.setThumbnail(mediaImg.getId());
}
String publish_statut = publier ? "1" : "0";
wp.editPost(Integer.valueOf(post_id), post, publish_statut);
if (!"null".equals(otherPicts)) {
String[] oPicts = otherPicts.split("\\|");
int j = oPicts.length;
for (String otherImage : oPicts) {
String ext = otherImage.substring(otherImage.lastIndexOf(".")).toLowerCase();
if (!ext.equals(".png")) {
wp.newMediaObject("image/jpg", new File(otherImage), Boolean.FALSE, post_id);
} else {
wp.newMediaObject("image/png", new File(otherImage), Boolean.FALSE, post_id);
}
}
}
System.out.println("!!!Send recipe SUCCEEDED!!!");
System.out.println(post_id);
} catch (MalformedURLException | XmlRpcFault | XmlRpcException | NumberFormatException | HeadlessException ex) {
System.out.println("ERROR : send recipe failed.");
Logger.getLogger(SendToWordpress.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static void testVariables() {
System.out.println("USER :");
System.out.println(user);
System.out.println("PASSWD :");
System.out.println(password);
System.out.println("PUBLISH ADRESS :");
System.out.println(xmlRpcUrl);
System.out.println("TITRE :");
System.out.println(titre);
System.out.println("CATEGORIES :");
System.out.println(categories);
System.out.println("TAGS :");
System.out.println(tags);
System.out.println("IMAGE PRINCIPALE :");
System.out.println(mainPict);
System.out.println("HTML CODE :");
System.out.println(htmlCode);
System.out.println("AUTRES IMAGES :");
System.out.println(otherPicts);
System.out.println("PUBLIER :");
System.out.println(publier);
System.out.println("EXCERPT :");
System.out.println(excerpt);
}
public static String loadFile(File file)
throws IOException {
InputStream fileReader = new FileInputStream(file);
Reader utfReader = new InputStreamReader(fileReader, "utf-8");
BufferedReader input = new BufferedReader(utfReader);
String separator = System.getProperty("line.separator");
StringBuilder builder = new StringBuilder();
String line;
while ((line = input.readLine()) != null) {
builder.append(line);
builder.append(separator);
}
input.close();
return builder.toString();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="SendToWordpress_lib" level="project" />
</component>
</module>
\ No newline at end of file
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