videodownloader/application/utils.cpp

74 lines
2.0 KiB
C++
Raw Normal View History

2015-09-08 17:05:59 +02:00
#include "./utils.h"
2015-04-22 19:32:04 +02:00
2017-05-01 03:22:50 +02:00
#include <QFile>
2015-04-22 19:32:04 +02:00
#include <QJsonDocument>
2017-05-01 03:22:50 +02:00
#include <QJsonObject>
2015-04-22 19:32:04 +02:00
#include <QJsonParseError>
2017-05-01 03:22:50 +02:00
#include <QString>
#include <QTextDocument>
2015-04-22 19:32:04 +02:00
namespace Application {
int substring(const QString &source, QString &target, int startIndex, const QString &startStr, const QString &endStr)
{
int beg = source.indexOf(startStr, startIndex);
2017-05-01 03:22:50 +02:00
if (beg > -1) {
2015-04-22 19:32:04 +02:00
beg += startStr.length();
int end = source.indexOf(endStr, beg);
2017-05-01 03:22:50 +02:00
if (end > -1) {
2015-04-22 19:32:04 +02:00
int len = end - beg;
2017-05-01 03:22:50 +02:00
if (len > 0) {
2015-04-22 19:32:04 +02:00
target = source.mid(beg, len);
return beg;
2017-05-01 03:22:50 +02:00
} else if (len == 0) {
2015-04-22 19:32:04 +02:00
target.clear();
return beg;
}
}
}
return -1;
}
void replaceHtmlEntities(QString &text)
{
//text = text.replace("&amp;", "&").replace("&gt;", ">").replace("&lt;" ,"<").replace("&#39;", "'");
QTextDocument textDocument;
textDocument.setHtml(text);
text = textDocument.toPlainText();
2017-05-01 03:22:50 +02:00
foreach (const QChar &c, text) {
if (!c.isSpace()) {
2015-04-22 19:32:04 +02:00
return;
}
}
text.clear(); // clear text if it contains white spaces only
}
QJsonObject loadJsonObjectFromResource(const QString &resource, QString *error)
{
QFile file(resource);
2017-05-01 03:22:50 +02:00
if (file.open(QFile::ReadOnly)) {
2015-04-22 19:32:04 +02:00
QJsonParseError parseError;
QJsonDocument doc = QJsonDocument::fromJson(file.readAll(), &parseError);
2017-05-01 03:22:50 +02:00
if (parseError.error == QJsonParseError::NoError) {
if (doc.isObject())
2015-04-22 19:32:04 +02:00
return doc.object();
else {
2017-05-01 03:22:50 +02:00
if (error) {
2015-09-16 17:32:47 +02:00
*error = QStringLiteral("JSON doesn't contain a main object.");
2015-04-22 19:32:04 +02:00
}
}
} else {
2017-05-01 03:22:50 +02:00
if (error) {
2015-04-22 19:32:04 +02:00
*error = parseError.errorString();
}
}
} else {
2017-05-01 03:22:50 +02:00
if (error) {
2015-04-22 19:32:04 +02:00
*error = QStringLiteral("Unable to open file.");
}
}
return QJsonObject();
}
2019-07-20 20:20:58 +02:00
} // namespace Application