void PendingDisco::handleReleaseLookupFinished ()
	{
		auto reply = qobject_cast<QNetworkReply*> (sender ());
		reply->deleteLater ();

		std::shared_ptr<void> decrementGuard (nullptr, [this] (void*) { DecrementPending (); });

		const auto& data = reply->readAll ();
		QDomDocument doc;
		if (!doc.setContent (data))
		{
			qWarning () << Q_FUNC_INFO
					<< "unable to parse"
					<< data;
		}

		const auto& releaseElem = doc.documentElement ().firstChildElement ("release");
		const auto& id = releaseElem.attribute ("id");
		auto pos = std::find_if (Releases_.begin (), Releases_.end (),
				[id] (decltype (Releases_.at (0)) release)
					{ return release.ID_ == id; });
		if (pos == Releases_.end ())
		{
			qWarning () << Q_FUNC_INFO
					<< "release"
					<< id
					<< "not found";
			return;
		}

		auto& release = *pos;
		auto mediumElem = releaseElem.firstChildElement ("medium-list").firstChildElement ("medium");
		while (!mediumElem.isNull ())
		{
			auto trackElem = mediumElem.firstChildElement ("track-list").firstChildElement ("track");

			QList<Media::ReleaseTrackInfo> tracks;
			while (!trackElem.isNull ())
			{
				const int num = trackElem.firstChildElement ("number").text ().toInt ();

				const auto& recElem = trackElem.firstChildElement ("recording");
				const auto& title = recElem.firstChildElement ("title").text ();
				const int length = recElem.firstChildElement ("length").text ().toInt () / 1000;

				tracks.push_back ({ num, title, length });
				trackElem = trackElem.nextSiblingElement ("track");
			}

			release.TrackInfos_ << tracks;

			mediumElem = mediumElem.nextSiblingElement ("medium");
		}
	}
	void PendingRecommendedArtists::handleReplyFinished ()
	{
		auto reply = qobject_cast<QNetworkReply*> (sender ());
		reply->deleteLater ();

		QDomDocument doc;
		if (!doc.setContent (reply->readAll ()))
		{
			qWarning () << Q_FUNC_INFO
					<< "unable to parse reply";
			emit error ();
			return;
		}

		auto artistElem = doc.documentElement ()
				.firstChildElement ("recommendations")
				.firstChildElement ("artist");
		auto elemGuard = [&artistElem] (void*) { artistElem = artistElem.nextSiblingElement ("artist"); };
		while (!artistElem.isNull ())
		{
			std::shared_ptr<void> guard (static_cast<void*> (0), elemGuard);

			const auto& name = artistElem.firstChildElement ("name").text ();
			if (name.isEmpty ())
				continue;

			QStringList similarTo;
			auto similarElem = artistElem.firstChildElement ("context").firstChildElement ("artist");
			while (!similarElem.isNull ())
			{
				similarTo << similarElem.firstChildElement ("name").text ();
				similarElem = similarElem.nextSiblingElement ("artist");
			}

			++InfosWaiting_;

			QMap<QString, QString> params;
			params ["artist"] = name;
			AddLanguageParam (params);
			auto infoReply = Request ("artist.getInfo", NAM_, params);

			infoReply->setProperty ("SimilarTo", similarTo);
			connect (infoReply,
					SIGNAL (finished ()),
					this,
					SLOT (handleInfoReplyFinished ()));
			connect (infoReply,
					SIGNAL (error (QNetworkReply::NetworkError)),
					this,
					SLOT (handleInfoReplyError ()));
		}
	}
	void RecentReleasesFetcher::handleReplyFinished ()
	{
		auto reply = qobject_cast<QNetworkReply*> (sender ());
		reply->deleteLater ();

		const auto& data = reply->readAll ();
		qDebug () << data;
		QDomDocument doc;
		if (!doc.setContent (data))
		{
			qWarning () << Q_FUNC_INFO
					<< "error parsing reply";
			return;
		}

		const auto& docElem = doc.documentElement ();
		if (docElem.attribute ("status") != "ok")
		{
			qWarning () << Q_FUNC_INFO
					<< "reply is not ok:"
					<< docElem.attribute ("status");
			return;
		}

		QList<Media::AlbumRelease> releases;

		static auto months = { "Jan", "Feb", "Mar",
				"Apr", "May", "Jun",
				"Jul", "Aug", "Sep",
				"Oct", "Nov", "Dec" };
		const auto monthsBegin = months.begin ();
		const auto monthsEnd = months.end ();
		auto album = docElem.firstChildElement ("albums").firstChildElement ("album");
		while (!album.isNull ())
		{
			const auto& strs = album.attribute ("releasedate").split (' ', QString::SkipEmptyParts);
			const int day = strs.value (1).toInt ();
			const int month = std::distance (monthsBegin,
						std::find (monthsBegin, monthsEnd, strs.value (2))) + 1;
			const int year = strs.value (3).toInt ();

			const QUrl& thumb = GetImage (album, "large");
			const QUrl& full = GetImage (album, "extralarge");

			Media::AlbumRelease release =
			{
				album.firstChildElement ("name").text (),
				album.firstChildElement ("artist").firstChildElement ("name").text (),
				QDateTime (QDate (year, month, day)),
				thumb,
				full,
				QUrl (album.firstChildElement ("url").text ())
			};
			releases << release;

			album = album.nextSiblingElement ("album");
		}

		emit gotRecentReleases (releases);
	}
	void CurrenciesManager::gotRateReply ()
	{
		auto reply = qobject_cast<QNetworkReply*> (sender ());
		reply->deleteLater ();

		const auto& data = reply->readAll ();

		QDomDocument doc;
		if (!doc.setContent (data))
		{
			qWarning () << Q_FUNC_INFO
					<< "unable to parse"
					<< data;
			return;
		}

		const auto& now = QDateTime::currentDateTime ();

		bool changed = false;
		auto rateElem = doc.documentElement ()
				.firstChildElement ("results")
				.firstChildElement ("rate");
		while (!rateElem.isNull ())
		{
			std::shared_ptr<void> guard (nullptr,
					[&rateElem] (void*) { rateElem = rateElem.nextSiblingElement ("rate"); });

			const auto& toValue = rateElem.attribute ("id").mid (3);
			if (toValue.size () != 3)
			{
				qWarning () << "incorrect `to` value"
						<< toValue;
				continue;
			}

			const auto newRate = rateElem.firstChildElement ("Rate").text ().toDouble ();
			if (std::fabs (newRate - RatesFromUSD_ [toValue]) > std::numeric_limits<double>::epsilon ())
			{
				RatesFromUSD_ [toValue] = newRate;
				changed = true;
			}

			Rate rate { 0, toValue, now, newRate };
			Core::Instance ().GetStorage ()->AddRate (rate);
		}

		LastFetch_ = QDateTime::currentDateTime ();

		QSettings settings (QCoreApplication::organizationName (),
			QCoreApplication::applicationName () + "_Poleemery");
		settings.beginGroup ("Currencies");
		settings.setValue ("LastFetch", LastFetch_);
		if (changed)
		{
			emit currenciesUpdated ();
			for (auto i = RatesFromUSD_.constBegin (); i != RatesFromUSD_.constEnd (); ++i)
				settings.setValue (i.key (), *i);
		}
		settings.endGroup ();
	}
Exemple #5
0
QStringList Read (const QString& path)
{
    QFile file (path);
    if (!file.open (QIODevice::ReadOnly))
    {
        qWarning () << Q_FUNC_INFO
                    << "unable to open"
                    << path
                    << file.errorString ();
        return QStringList ();
    }

    QDomDocument doc;
    if (!doc.setContent (file.readAll ()))
    {
        qWarning () << Q_FUNC_INFO
                    << "unable to parse"
                    << path;
        return QStringList ();
    }

    QStringList result;
    auto track = doc.documentElement ()
                 .firstChildElement ("trackList")
                 .firstChildElement ("track");
    while (!track.isNull ())
    {
        const auto& loc = track.firstChildElement ("location").text ();
        if (!loc.isEmpty ())
            result << loc;

        track = track.nextSiblingElement ("track");
    }
    return result;
}
	void ReportTypePage::ParseCategories (const QByteArray& data)
	{
		QDomDocument doc;
		if (!doc.setContent (data))
		{
			qWarning () << Q_FUNC_INFO
					<< "invalid data"
					<< data;
			return;
		}

		auto category = doc.documentElement ()
				.firstChildElement ("issue_categories")
				.firstChildElement ("issue_category");
		while (!category.isNull ())
		{
			std::shared_ptr<void> guard (static_cast<void*> (0),
					[&category] (void*) { category = category.nextSiblingElement ("issue_category"); });
			const auto& idText = category.attribute ("id");
			bool ok = false;
			const int id = idText.toInt (&ok);
			if (!ok)
			{
				qWarning () << Q_FUNC_INFO
						<< "invalid category id"
						<< idText;
				continue;
			}

			const auto& name = category.attribute ("name");

			Ui_.CatCombo_->addItem (name, id);
		}
	}
Exemple #7
0
	ConcreteSiteDesc::ConcreteSiteDesc (const QDomElement& elem)
	: Name_ (elem.attribute ("name"))
	, Charset_ (elem.attribute ("charset", "utf-8"))
	, URLTemplate_ (elem.attribute ("url"))
	{
		auto urlFormat = elem.firstChildElement ("urlFormat");
		while (!urlFormat.isNull ())
		{
			const auto& replace = urlFormat.attribute ("replace");
			const auto& with = urlFormat.attribute ("with");
			for (const auto c : replace)
				Replacements_ [c] = with;

			urlFormat = urlFormat.nextSiblingElement ("urlFormat");
		}

		auto fillMatchers = [&elem] (const QString& name, MatcherBase::Mode mode) -> QList<MatcherBase_ptr>
		{
			QList<MatcherBase_ptr> result;

			auto extract = elem.firstChildElement (name);
			while (!extract.isNull ())
			{
				auto item = extract.firstChildElement ("item");
				while (!item.isNull ())
				{
					result << MatcherBase::MakeMatcher (mode, item);
					item = item.nextSiblingElement ("item");
				}

				extract = extract.nextSiblingElement (name);
			}
			result.removeAll (MatcherBase_ptr ());
			return result;
		};

		Matchers_ += fillMatchers ("extract", MatcherBase::Mode::Return);
		Matchers_ += fillMatchers ("exclude", MatcherBase::Mode::Exclude);

		auto invalidElem = elem.firstChildElement ("invalidIndicator");
		while (!invalidElem.isNull ())
		{
			InvalidIndicators_ << invalidElem.attribute ("value");
			invalidElem = invalidElem.nextSiblingElement ("invalidIndicator");
		}
	}
Exemple #8
0
void LoaderXml::layers(const QDomElement& node)
{
    for ( auto lay = node.firstChildElement("layer"); !lay.isNull();
            lay = lay.nextSiblingElement("layer") )
    {
        layer(lay);
    }
}
Exemple #9
0
void LoaderXml::metadata(const QDomElement& node)
{
    if ( node.isNull() ) return;

    auto& meta = builder.currentElement()->metadata();
    for ( auto data = node.firstChildElement("entry"); !data.isNull();
            data = data.nextSiblingElement("entry") )
    {
        if ( data.hasAttribute("name") )
            meta[data.attribute("name")] = data.text();
    }
}
Exemple #10
0
	QList<QImage> XmlSettingsDialog::GetImages (const QDomElement& item) const
	{
		QList<QImage> result;
		auto binary = item.firstChildElement ("binary");
		while (!binary.isNull ())
		{
			QByteArray data;
			if (binary.attribute ("place") == "rcc")
			{
				QFile file (binary.text ());
				if (!file.open (QIODevice::ReadOnly))
				{
					qWarning () << Q_FUNC_INFO
						<< "could not open file"
						<< binary.text ()
						<< ", because"
						<< file.errorString ();

					binary = binary.nextSiblingElement ("binary");

					continue;
				}
				data = file.readAll ();
			}
			else
			{
				const auto& base64 = binary.text ().toLatin1 ();
				data = QByteArray::fromBase64 (base64);
			}
			if (binary.attribute ("type") == "image")
			{
				const auto& image = QImage::fromData (data);
				if (!image.isNull ())
					result << image;
			}
			binary = binary.nextSiblingElement ("binary");
		}
		return result;
	}
	void HypedTracksFetcher::handleFinished ()
	{
		auto reply = qobject_cast<QNetworkReply*> (sender ());
		deleteLater ();

		const auto& data = reply->readAll ();
		QDomDocument doc;
		if (!doc.setContent (data))
		{
			qWarning () << Q_FUNC_INFO
					<< "error parsing reply"
					<< data;
			return;
		}

		QList<Media::HypedTrackInfo> tracks;

		auto trackElem = doc
				.documentElement ()
				.firstChildElement ("tracks")
				.firstChildElement ("track");
		while (!trackElem.isNull ())
		{
			auto getText = [&trackElem] (const QString& name)
			{
				return trackElem.firstChildElement (name).text ();
			};

			const auto& artistElem = trackElem.firstChildElement ("artist");

			tracks << Media::HypedTrackInfo
			{
				getText ("name"),
				getText ("url"),
				getText ("percentagechange").toInt (),
				getText ("playcount").toInt (),
				getText ("listeners").toInt (),
				getText ("duration").toInt (),
				GetImage (trackElem, "medium"),
				GetImage (trackElem, "extralarge"),
				artistElem.firstChildElement ("name").text (),
				artistElem.firstChildElement ("url").text ()
			};

			trackElem = trackElem.nextSiblingElement ("track");
		}

		emit gotHypedTracks (tracks, Type_);
	}
	void ReportTypePage::handleCategoriesFinished ()
	{
		auto reply = qobject_cast<QNetworkReply*> (sender ());
		if (!reply)
		{
			qWarning () << Q_FUNC_INFO
					<< "invalid reply"
					<< sender ();
			return;
		}

		reply->deleteLater ();

		const auto& data = reply->readAll ();
		QDomDocument doc;
		if (!doc.setContent (data))
		{
			qWarning () << Q_FUNC_INFO
					<< "invalid data"
					<< data;
			return;
		}

		auto category = doc.documentElement ()
				.firstChildElement ("issue_categories")
				.firstChildElement ("issue_category");
		while (!category.isNull ())
		{
			std::shared_ptr<void> guard (static_cast<void*> (0),
					[&category] (void*) { category = category.nextSiblingElement ("issue_category"); });
			const auto& idText = category.attribute ("id");
			bool ok = false;
			const int id = idText.toInt (&ok);
			if (!ok)
			{
				qWarning () << Q_FUNC_INFO
						<< "invalid category id"
						<< idText;
				continue;
			}

			const auto& name = category.attribute ("name");

			Ui_.CatCombo_->addItem (name, id);
		}
	}
void AutomationPathSerializer::read_automation_path(const QDomNode &node, AutomationPath &path)
{
	auto point = node.firstChildElement();
	while (! point.isNull()) {
		if (point.tagName() == "point") {
			bool hasX = false;
			bool hasY = false;
			float x = point.attribute("x").toFloat(&hasX);
			float y = point.attribute("y").toFloat(&hasY);

			if (hasX && hasY) {
				path.add_point(x, y);
			}

		}
		point = point.nextSiblingElement();
	}
}
Exemple #14
0
	DescParser::DescParser ()
	{
		QFile file { ":/azoth/mucommands/resources/data/descriptions.xml" };
		if (!file.open (QIODevice::ReadOnly))
		{
			qWarning () << Q_FUNC_INFO
					<< "unable to open descriptions file"
					<< file.errorString ();
			return;
		}

		QDomDocument doc;
		QString msg;
		int line = 0;
		int column = 0;
		if (!doc.setContent (&file, &msg, &line, &column))
		{
			qWarning () << Q_FUNC_INFO
					<< "cannot parse descriptions file"
					<< msg
					<< line
					<< column;
			return;
		}

		auto cmdElem = doc.documentElement ().firstChildElement ("command");
		while (!cmdElem.isNull ())
		{
			const auto& name = cmdElem.attribute ("name");

			const auto& descr = cmdElem.firstChildElement ("desc").text ();
			const auto& help = cmdElem.firstChildElement ("help").text ();

			const auto& descrTr = qApp->translate ("descriptions", descr.toUtf8 ().constData ());

			Cmd2Desc_ [name] = Desc { descrTr, help };

			cmdElem = cmdElem.nextSiblingElement ("command");
		}
	}
Exemple #15
0
void LoaderXml::layer(const QDomElement& node)
{
    document::Layer* layer = builder.beginLayer();
    id(node);
    layer->setName(node.attribute("name", tr("Layer")));
    layer->setOpacity(node.attribute("opacity", "1").toDouble());
    layer->setVisible(node.attribute("visible", "1").toInt());
    layer->setLocked(node.attribute("locked", "0").toInt());
    layer->setBlendMode(misc::composition_from_string(node.attribute("blend")));
    layer->setBackgroundColor(color_widgets::colorFromString(node.attribute("background")));

    metadata(node);

    for ( auto img = node.firstChildElement("image"); !img.isNull();
            img = img.nextSiblingElement("image") )
    {
        image(img);
    }

    layers(node);
    builder.endLayer();
}
Exemple #16
0
	void Plugin::handleReply ()
	{
		auto reply = qobject_cast<QNetworkReply*> (sender ());
		reply->deleteLater ();

		if (!Reply2Model_.contains (reply))
		{
			qWarning () << Q_FUNC_INFO
					<< "stall reply detected";
			return;
		}

		const auto& data = reply->readAll ();

		auto model = Reply2Model_.take (reply);
		Model2Reply_.remove (model);

		QDomDocument doc;
		if (!doc.setContent (data))
		{
			qWarning () << Q_FUNC_INFO
					<< "unable to read reply";
			return;
		}

		auto iURLCompleter = qobject_cast<IURLCompletionModel*> (model);

		auto suggestion = doc.documentElement ().firstChildElement ("CompleteSuggestion");
		auto pos = 5;
		while (!suggestion.isNull ())
		{
			const auto& str = suggestion.firstChildElement ("suggestion").attribute ("data");

			iURLCompleter->AddItem (str, str, pos++);

			suggestion = suggestion.nextSiblingElement ("CompleteSuggestion");
		}
	}
Exemple #17
0
	void XmlSettingsDialog::ParsePage (const QDomElement& page)
	{
		Titles_ << GetLabel (page);

		QStringList icons;
		if (page.hasAttribute ("icon"))
			icons << page.attribute ("icon");
		auto iconElem = page
				.firstChildElement ("icons")
				.firstChildElement ("icon");
		while (!iconElem.isNull ())
		{
			icons << iconElem.text ();
			iconElem = iconElem.nextSiblingElement ("icon");
		}
		IconNames_ << icons;

		const auto baseWidget = new QWidget;
		Pages_->addWidget (baseWidget);
		const auto lay = new QGridLayout;
		lay->setContentsMargins (0, 0, 0, 0);
		baseWidget->setLayout (lay);

		ParseEntity (page, baseWidget);

		bool foundExpanding = false;

		for (const auto w : baseWidget->findChildren<QWidget*> ())
			if (w->sizePolicy ().verticalPolicy () & QSizePolicy::ExpandFlag)
			{
				foundExpanding = true;
				break;
			}

		if (!foundExpanding)
			lay->addItem (new QSpacerItem (0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding),
					lay->rowCount (), 0, 1, 2);
	}
	PsiPlusImportPage::PsiPlusImportPage (QWidget *parent)
	: Common::IMImportPage (parent)
	{
		auto tfd = [] (const QDomElement& account, const QString& field)
			{ return account.firstChildElement (field).text (); };

		auto adapter = Common::XMLIMAccount::ConfigAdapter
		{
			AccountsModel_,
			QStringList (".config") << "Psi+" << "profiles",
			"accounts.xml",
			[] (const QDomElement&) { return "xmpp"; },
			[=] (const QDomElement& acc) { return tfd (acc, "name"); },
			[=] (const QDomElement& acc) { return tfd (acc, "enabled") == "true"; },
			[=] (const QDomElement& acc) { return tfd (acc, "jid"); },
			[=] (const QDomElement& acc, QVariantMap& accountData)
			{
				accountData ["Port"] = tfd (acc, "port").toInt ();
				accountData ["Host"] = tfd (acc, "use-host") == "true" ?
						tfd (acc, "host") :
						QString ();

				QStringList jids;

				auto rosterItem = acc.firstChildElement ("roster-cache").firstChildElement ();
				while (!rosterItem.isNull ())
				{
					const QString& jid = rosterItem.firstChildElement ("jid").text ();
					if (!jid.isEmpty ())
						jids << jid;
					rosterItem = rosterItem.nextSiblingElement ();
				}
				accountData ["Contacts"] = jids;
			}
		};
		XIA_.reset (new Common::XMLIMAccount (adapter));
	}
	void PListParser::Parse (const QString& filename)
	{
		QFile file (filename);
		if (!file.open (QIODevice::ReadOnly))
			throw PListParseError (QObject::tr ("Unable to open file: %2.")
					.arg (file.errorString ()));

		QDomDocument doc;

		QString error;
		int line = 0;
		int col = 0;
		if (!doc.setContent (&file, &error, &line, &col))
			throw PListParseError (QObject::tr ("Parse error: %1 (%2:%3).")
					.arg (error)
					.arg (line)
					.arg (col));

		const auto& dict = doc.documentElement ().firstChildElement ("dict");
		auto elem = dict.firstChildElement ();
		QString currentKey;
		while (!elem.isNull ())
		{
			if (elem.tagName ().toLower () == "key")
				currentKey = elem.text ();
			else if (currentKey.isEmpty ())
				throw PListParseError (QObject::tr ("State mismatch: expected key tag."));
			else
			{
				KeyVals_ [currentKey] = elem.text ();
				currentKey.clear ();
			}

			elem = elem.nextSiblingElement ();
		}
	}
Exemple #20
0
	IAdvancedHTMLEditor::CustomTags_t LJBloggingPlatform::GetCustomTags () const
	{
		IAdvancedHTMLEditor::CustomTags_t tags;

		IAdvancedHTMLEditor::CustomTag ljUserTag;
		ljUserTag.TagName_ = "lj";
		ljUserTag.ToKnown_ = [] (QDomElement& elem) -> void
		{
			const auto& user = elem.attribute ("user");
			elem.setTagName ("span");
			elem.setAttribute ("contenteditable", "false");

			QDomElement linkElem = elem.ownerDocument ().createElement ("a");
			linkElem.setAttribute ("href", QString ("http://%1.livejournal.com/profile").arg (user));
			linkElem.setAttribute ("target", "_blank");

			QDomElement imgElem = elem.ownerDocument ().createElement ("img");
			imgElem.setAttribute ("src", "http://l-stat.livejournal.com/img/userinfo.gif?v=17080");
			linkElem.appendChild (imgElem);

			QDomElement nameElem = elem.ownerDocument ().createElement ("a");
			nameElem.setAttribute ("href", QString ("http://%1.livejournal.com/profile").arg (user));
			nameElem.setAttribute ("target", "_blank");
			nameElem.setAttribute ("id", "nameLink");
			nameElem.setAttribute ("contenteditable", "true");
			nameElem.appendChild (elem.ownerDocument ().createTextNode (user));

			elem.appendChild (linkElem);
			elem.appendChild (nameElem);

			elem.removeAttribute ("user");
		};
		ljUserTag.FromKnown_ = [] (QDomElement& elem) -> bool
		{
			auto aElem = elem.firstChildElement ("a");
			while (!aElem.isNull ())
			{
				if (aElem.attribute ("id") == "nameLink")
					break;

				aElem = aElem.nextSiblingElement ("a");
			}
			if (aElem.isNull ())
				return false;
			const auto& username = aElem.text ();

			const auto& children = elem.childNodes ();
			while (!children.isEmpty ())
				elem.removeChild (children.at (0));

			elem.setTagName ("lj");
			elem.setAttribute ("user", username);

			return true;
		};
		tags << ljUserTag;

		IAdvancedHTMLEditor::CustomTag ljCutTag;
		ljCutTag.TagName_ = "lj-cut";
		ljCutTag.ToKnown_ = [] (QDomElement& elem) -> void
		{
			elem.setTagName ("div");
			const auto& text = elem.attribute ("text");
			elem.removeAttribute ("text");
			elem.setAttribute ("id", "cutTag");
			elem.setAttribute ("style", "overflow:auto;border-width:3px;border-style:dotted;margin-left:3em;padding:2em 2em;");
			elem.setAttribute ("text", text);
		};
		ljCutTag.FromKnown_ = [] (QDomElement& elem) -> bool
		{
			if (!elem.hasAttribute ("id") ||
					elem.attribute ("id") != "cutTag")
				return false;

			elem.removeAttribute ("id");
			elem.removeAttribute ("style");
			const auto& text = elem.attribute ("text");
			elem.removeAttribute ("text");
			elem.setTagName ("lj-cut");
			if (!text.isEmpty ())
				elem.setAttribute ("text", text);

			return true;
		};

		tags << ljCutTag;

		IAdvancedHTMLEditor::CustomTag ljPollTag;
		ljPollTag.TagName_ = "lj-poll";
		ljPollTag.ToKnown_ = [this] (QDomElement& elem) -> void
		{
			const auto& whoView = elem.attribute ("whoview");
			const auto& whoVote = elem.attribute ("whovote");
			const auto& name = elem.attribute ("name");

			auto children = elem.childNodes ();

			elem.setTagName ("div");
			elem.setAttribute ("style", "overflow:auto;border-width:2px;border-style:solid;border-radius:5px;margin-left:3em;padding:2em 2em;");
			elem.setAttribute ("id", "pollDiv");
			elem.setAttribute ("ljPollWhoview", whoView);
			elem.setAttribute ("ljPollWhovote", whoVote);
			elem.setAttribute ("ljPollName", name);
			QString questions;
			for (int i = 0, size = children.size (); i < size; ++i)
			{
				const auto& child = children.at (i);
				QString question;
				QTextStream str (&question);
				child.save (str, 0);

				questions.append (question);
			}
			elem.setAttribute ("ljPollQuestions", QString (questions.toUtf8 ().toBase64 ()));
			while (!children.isEmpty ())
				elem.removeChild (children.at (0));
			auto textElem = elem.ownerDocument ().createTextNode (tr ("Poll: %1").arg (name));
			elem.appendChild (textElem);

		};
		ljPollTag.FromKnown_ = [] (QDomElement& elem) -> bool
		{
			if (!elem.hasAttribute ("id") ||
					elem.attribute ("id") != "pollDiv")
				return false;

			auto whoView = elem.attribute ("ljPollWhoview");
			auto whoVote = elem.attribute ("ljPollWhovote");
			auto name = elem.attribute ("ljPollName");
			auto questions = QByteArray::fromBase64 (elem.attribute ("ljPollQuestions").toUtf8 ());

			elem.removeAttribute ("style");
			elem.removeAttribute ("ljPollWhoview");
			elem.removeAttribute ("ljPollWhovot");
			elem.removeAttribute ("ljPollName");
			elem.removeAttribute ("ljPollQuestions");
			elem.removeAttribute ("id");
			elem.removeChild (elem.firstChild ());

			elem.setTagName ("lj-poll");
			elem.setAttribute ("whoview", whoView);
			elem.setAttribute ("whovote", whoVote);
			elem.setAttribute ("name", name);
			QDomDocument doc;
			doc.setContent (questions);
			elem.appendChild (doc.documentElement ());

			return true;
		};

		tags << ljPollTag;

		IAdvancedHTMLEditor::CustomTag ljEmbedTag;
		ljEmbedTag.TagName_ = "lj-embed";
		ljEmbedTag.ToKnown_ = [this] (QDomElement& elem) -> void
		{
			const auto& id = elem.attribute ("id");
			elem.removeAttribute ("id");

			elem.setTagName ("div");
			elem.setAttribute ("style", "overflow:auto;border-width:2px;border-style:solid;border-radius:5px;margin-left:3em;padding:2em 2em;");
			elem.setAttribute ("id", "embedTag");
			elem.setAttribute ("name", id);
			auto textElem = elem.ownerDocument ().createTextNode (tr ("Embedded: %1")
					.arg (id));
			elem.appendChild (textElem);
		};
		ljEmbedTag.FromKnown_ = [] (QDomElement& elem) -> bool
		{
			if (!elem.hasAttribute ("id") ||
					elem.attribute ("id") != "embedTag")
				return false;

			elem.removeAttribute ("style");
			elem.removeChild (elem.firstChild ());
			const auto& id = elem.attribute ("name");
			elem.removeAttribute ("id");
			elem.setTagName ("lj-embed");
			elem.setAttribute ("id", id);
			return true;
		};

		tags << ljEmbedTag;

		IAdvancedHTMLEditor::CustomTag ljLikeTag;
		ljLikeTag.TagName_ = "lj-like";
		ljLikeTag.ToKnown_ = [this] (QDomElement& elem) -> void
		{
			const auto& buttons = elem.attribute ("buttons");
			elem.removeAttribute ("buttons");

			elem.setTagName ("div");
			elem.setAttribute ("style", "overflow:auto;border-width:2px;border-style:solid;border-radius:5px;margin-left:3em;padding:2em 2em;");
			elem.setAttribute ("likes", buttons);
			auto textElem = elem.ownerDocument ().createTextNode (tr ("Likes: %1")
					.arg (!buttons.isEmpty () ?
						buttons :
						"repost,facebook,twitter,google,vkontakte,surfingbird,tumblr,livejournal"));
			elem.appendChild (textElem);
		};
		ljLikeTag.FromKnown_ = [] (QDomElement& elem) -> bool
		{
			const auto& likes = elem.attribute ("likes");
			if (likes.isEmpty ())
				return false;

			elem.removeAttribute ("likes");
			elem.removeAttribute ("style");
			elem.setTagName ("lj-like");
			elem.setAttribute ("buttons", likes);
			elem.removeChild (elem.firstChild ());
			return true;
		};

		tags << ljLikeTag;

		return tags;
	}
Exemple #21
0
	void XmlSettingsDialog::ParseEntity (const QDomElement& entity, QWidget *baseWidget)
	{
		QDomElement item = entity.firstChildElement ("item");
		while (!item.isNull ())
		{
			ParseItem (item, baseWidget);
			item = item.nextSiblingElement ("item");
		}

		auto gbox = entity.firstChildElement ("groupbox");
		while (!gbox.isNull ())
		{
			const auto box = new QGroupBox (GetLabel (gbox));
			box->setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Preferred);
			const auto groupLayout = new QGridLayout ();
			groupLayout->setContentsMargins (2, 2, 2, 2);
			box->setLayout (groupLayout);

			ParseEntity (gbox, box);

			const auto lay = qobject_cast<QGridLayout*> (baseWidget->layout ());
			lay->addWidget (box, lay->rowCount (), 0, 1, 2);

			gbox = gbox.nextSiblingElement ("groupbox");
		}

		auto scroll = entity.firstChildElement ("scrollarea");
		while (!scroll.isNull ())
		{
			const auto area = new QScrollArea ();
			if (scroll.hasAttribute ("horizontalScroll"))
			{
				const auto& attr = scroll.attribute ("horizontalScroll");
				if (attr == "on")
					area->setHorizontalScrollBarPolicy (Qt::ScrollBarAlwaysOn);
				else if (attr == "off")
					area->setHorizontalScrollBarPolicy (Qt::ScrollBarAlwaysOff);
			}
			if (scroll.hasAttribute ("verticalScroll"))
			{
				const auto& attr = scroll.attribute ("verticalScroll");
				if (attr == "on")
					area->setVerticalScrollBarPolicy (Qt::ScrollBarAlwaysOn);
				else if (attr == "off")
					area->setVerticalScrollBarPolicy (Qt::ScrollBarAlwaysOff);
			}

			area->setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Expanding);

			const auto areaWidget = new QFrame;
			areaWidget->setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Expanding);
			const auto areaLayout = new QGridLayout;
			areaWidget->setLayout (areaLayout);
			ParseEntity (scroll, areaWidget);
			area->setWidget (areaWidget);
			area->setWidgetResizable (true);
			areaWidget->show ();

			const auto lay = qobject_cast<QGridLayout*> (baseWidget->layout ());
			const auto thisRow = lay->rowCount ();
			lay->addWidget (area, thisRow, 0, 1, 2);
			lay->setRowStretch (thisRow, 1);

			scroll = scroll.nextSiblingElement ("scrollarea");
		}

		auto tab = entity.firstChildElement ("tab");
		if (!tab.isNull ())
		{
			const auto tabs = new QTabWidget;
			const auto lay = qobject_cast<QGridLayout*> (baseWidget->layout ());
			lay->addWidget (tabs, lay->rowCount (), 0, 1, 2);
			while (!tab.isNull ())
			{
				const auto page = new QWidget;
				const auto widgetLay = new QGridLayout;
				widgetLay->setContentsMargins (0, 0, 0, 0);
				page->setLayout (widgetLay);
				tabs->addTab (page, GetLabel (tab));
				ParseEntity (tab, page);
				tab = tab.nextSiblingElement ("tab");

				widgetLay->addItem (new QSpacerItem (0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding),
						widgetLay->rowCount (), 0, 1, 1);
			}
		}
	}
Exemple #22
0
	void KopeteImportThread::ParseFile (const QString& filename)
	{
		QFile file (filename);
		if (!file.open (QIODevice::ReadOnly))
		{
			qWarning () << Q_FUNC_INFO
					<< "unable to open file"
					<< file.fileName ()
					<< file.errorString ();
			return;
		}

		QDomDocument doc;
		if (!doc.setContent (&file))
		{
			qWarning () << Q_FUNC_INFO
					<< "error parsing file"
					<< file.fileName ();
			return;
		}

		int month = 0, year = 0;
		QString contact;
		QString ourContact;
		ParseHead (doc.documentElement (), month, year, contact, ourContact);
		if (contact.isEmpty ())
		{
			qWarning () << Q_FUNC_INFO
					<< "got empty contact for"
					<< file.fileName ();
			return;
		}

		QVariantList list;

		auto msg = doc.documentElement ().firstChildElement ("msg");
		while (!msg.isNull ())
		{
			const auto& rawTime = msg.attribute ("time").split (' ', QString::SkipEmptyParts);

			QVariantMap result;
			result ["EntryID"] = contact;
			result ["DateTime"] = QDateTime (QDate (year, month, rawTime.value (0).toInt ()),
						QTime::fromString (rawTime.value (1), "h:m:s"));
			result ["Direction"] = msg.attribute ("in") == "0" ? "in" : "out";
			result ["Body"] = msg.text ();
			result ["MessageType"] = "chat";

			list << result;

			msg = msg.nextSiblingElement ("msg");
		}

		if (list.isEmpty ())
			return;

		Entity e;
		e.Additional_ ["History"] = list;
		e.Mime_ = "x-leechcraft/im-history-import";
		e.Additional_ ["AccountName"] = ourContact;
		e.Additional_ ["AccountID"] = ourContact;
		e.Parameters_ = OnlyHandle | FromUserInitiated;
		Proxy_->GetEntityManager ()->HandleEntity (e);
	}
Exemple #23
0
	void VkAccount::handleGotPhotos ()
	{
		auto reply = qobject_cast<QNetworkReply*> (sender ());
		reply->deleteLater ();

		const auto& data = reply->readAll ();
		QDomDocument doc;
		if (!doc.setContent (data))
		{
			qWarning () << Q_FUNC_INFO
					<< "cannot parse reply"
					<< data;
			return;
		}

		bool finishReached = false;

		auto photoElem = doc
				.documentElement ()
				.firstChildElement ("photo");
		while (!photoElem.isNull ())
		{
			auto mkItem = [&photoElem] () -> QStandardItem*
			{
				const auto& idText = photoElem.firstChildElement ("pid").text ();

				auto item = new QStandardItem (idText);
				item->setData (ItemType::Image, CollectionRole::Type);
				item->setData (idText, CollectionRole::ID);
				item->setData (QString (), CollectionRole::Name);

				const auto& sizesElem = photoElem.firstChildElement ("sizes");
				auto getType = [&sizesElem] (const QString& type) -> QPair<QUrl, QSize>
				{
					auto sizeElem = sizesElem.firstChildElement ("size");
					while (!sizeElem.isNull ())
					{
						if (sizeElem.firstChildElement ("type").text () != type)
						{
							sizeElem = sizeElem.nextSiblingElement ("size");
							continue;
						}

						const auto& src = sizeElem.firstChildElement ("src").text ();
						const auto width = sizeElem.firstChildElement ("width").text ().toInt ();
						const auto height = sizeElem.firstChildElement ("height").text ().toInt ();

						return { src, { width, height } };
					}

					return {};
				};

				const auto& small = getType ("m");
				const auto& mid = getType ("x");
				auto orig = getType ("w");
				QStringList sizeCandidates { "z", "y", "x", "r" };
				while (orig.second.width () <= 0)
				{
					if (sizeCandidates.isEmpty ())
						return nullptr;

					orig = getType (sizeCandidates.takeFirst ());
				}

				item->setData (small.first, CollectionRole::SmallThumb);
				item->setData (small.second, CollectionRole::SmallThumbSize);

				item->setData (mid.first, CollectionRole::MediumThumb);
				item->setData (mid.second, CollectionRole::MediumThumbSize);

				item->setData (orig.first, CollectionRole::Original);
				item->setData (orig.second, CollectionRole::OriginalSize);

				return item;
			};

			auto allItem = mkItem ();
			if (!allItem)
			{
				finishReached = true;
				break;
			}

			AllPhotosItem_->appendRow (allItem);

			const auto aid = photoElem.firstChildElement ("aid").text ().toInt ();
			if (Albums_.contains (aid))
				Albums_ [aid]->appendRow (mkItem ());

			photoElem = photoElem.nextSiblingElement ("photo");
		}

		if (finishReached)
			return;

		const auto count = doc.documentElement ().firstChildElement ("count").text ().toInt ();
		if (count == AllPhotosItem_->rowCount ())
			return;

		const auto offset = AllPhotosItem_->rowCount ();

		CallQueue_.append ([this, offset] (const QString& authKey) -> void
			{
				QUrl photosUrl ("https://api.vk.com/method/photos.getAll.xml");
				photosUrl.addQueryItem ("access_token", authKey);
				photosUrl.addQueryItem ("count", "100");
				photosUrl.addQueryItem ("offset", QString::number (offset));
				photosUrl.addQueryItem ("photo_sizes", "1");
				RequestQueue_->Schedule ([this, photosUrl]
					{
						connect (Proxy_->GetNetworkAccessManager ()->get (QNetworkRequest (photosUrl)),
								SIGNAL (finished ()),
								this,
								SLOT (handleGotPhotos ()));
					}, this);
			});

		AuthMgr_->GetAuthKey ();

	}
	void PendingDisco::handleLookupFinished ()
	{
		auto reply = qobject_cast<QNetworkReply*> (sender ());
		reply->deleteLater ();

		const auto& data = reply->readAll ();
		QDomDocument doc;
		if (!doc.setContent (data))
		{
			qWarning () << Q_FUNC_INFO
					<< "unable to parse"
					<< data;
			emit error (tr ("Unable to parse MusicBrainz reply."));
			deleteLater ();
		}

		QMap<QString, QMap<QString, Media::ReleaseInfo>> infos;

		auto releaseElem = doc
				.documentElement ()
				.firstChildElement ("artist")
				.firstChildElement ("release-list")
				.firstChildElement ("release");
		while (!releaseElem.isNull ())
		{
			std::shared_ptr<void> guard (nullptr,
					[&releaseElem] (void*)
						{ releaseElem = releaseElem.nextSiblingElement ("release"); });

			auto elemText = [&releaseElem] (const QString& sub)
			{
				return releaseElem.firstChildElement (sub).text ();
			};

			if (elemText ("status") != "Official")
				continue;

			const auto& dateStr = elemText ("date");
			const int dashPos = dateStr.indexOf ('-');
			const int date = (dashPos > 0 ? dateStr.left (dashPos) : dateStr).toInt ();
			if (date < 1000)
				continue;

			const auto& title = elemText ("title");
			if (!ReleaseName_.isEmpty () && title.toLower () != ReleaseName_)
				continue;

			infos [title] [elemText ("country")] =
			{
				releaseElem.attribute ("id"),
				title,
				date,
				Media::ReleaseInfo::Type::Standard,
				QList<QList<Media::ReleaseTrackInfo>> ()
			};
		}

		for (const auto& key : infos.keys ())
		{
			const auto& countries = infos [key];
			const auto& release = countries.contains ("US") ?
					countries ["US"] :
					countries.values ().first ();
			Releases_ << release;

			++PendingReleases_;

			const auto urlStr = "http://musicbrainz.org/ws/2/release/" + release.ID_ + "?inc=recordings";

			Queue_->Schedule ([this, urlStr] () -> void
				{
					auto reply = NAM_->get (QNetworkRequest (QUrl (urlStr)));
					connect (reply,
							SIGNAL (finished ()),
							this,
							SLOT (handleReleaseLookupFinished ()));
					connect (reply,
							SIGNAL (error (QNetworkReply::NetworkError)),
							this,
							SLOT (handleReleaseLookupError ()));
				}, this);
		}

		std::sort (Releases_.begin (), Releases_.end (),
				[] (decltype (Releases_.at (0)) left, decltype (Releases_.at (0)) right)
					{ return left.Year_ < right.Year_; });
	}
	void HypedArtistsFetcher::handleFinished ()
	{
		auto reply = qobject_cast<QNetworkReply*> (sender ());
		reply->deleteLater ();

		const auto& data = reply->readAll ();
		QDomDocument doc;
		if (!doc.setContent (data))
		{
			qWarning () << Q_FUNC_INFO
					<< "error parsing reply"
					<< data;
			return;
		}

		auto artistElem = doc
				.documentElement ()
				.firstChildElement ("artists")
				.firstChildElement ("artist");
		while (!artistElem.isNull ())
		{
			auto getText = [&artistElem] (const QString& name)
			{
				return artistElem.firstChildElement (name).text ();
			};

			const auto& name = getText ("name");

			Infos_ << Media::HypedArtistInfo
			{
				Media::ArtistInfo
				{
					name,
					QString (),
					QString (),
					GetImage (artistElem, "medium"),
					GetImage (artistElem, "extralarge"),
					getText ("url"),
					Media::TagInfos_t ()
				},
				getText ("percentagechange").toInt (),
				getText ("playcount").toInt (),
				getText ("listeners").toInt ()
			};

			auto pendingBio = new PendingArtistBio (name, NAM_, this);
			connect (pendingBio,
					SIGNAL (ready ()),
					this,
					SLOT (pendingBioReady ()));
			connect (pendingBio,
					SIGNAL (error ()),
					this,
					SLOT (pendingBioError ()));

			artistElem = artistElem.nextSiblingElement ("artist");
		}

		InfoCount_ = Infos_.size ();
		if (!InfoCount_)
			deleteLater ();
	}
Exemple #26
0
bool Prototype::readXml(const QString &i_fileName)
{
  QFile file(i_fileName);
  if (!file.open(QIODevice::ReadOnly))
  {
    return false;
  }
  QDomDocument document;
  if (!document.setContent(file.readAll()))
  {
    return false;
  }
  auto commonElement = document.documentElement().firstChildElement("Common");
  auto backgroundFileName = commonElement.firstChildElement("Background").text();
  backgroundImage = QImage(backgroundFileName);
  firstSlide = commonElement.firstChildElement("FirstSlide").text();
  auto slidesElement = document.documentElement().firstChildElement("Slides");
  if (slidesElement.isNull())
  {
    return false;
  }
  slides.clear();
  for (auto slideElement = slidesElement.firstChildElement("Slide"); !slideElement.isNull(); slideElement = slideElement.nextSiblingElement("Slide"))
  {
    Slide slide;
    if (!slide.readXml(slideElement))
    {
      return false;
    }
    slides[slide.name] = slide;
  }
  return true;
}
	void RecEventsFetcher::handleFinished ()
	{
		auto reply = qobject_cast<QNetworkReply*> (sender ());
		if (!reply)
			return;

		reply->deleteLater ();
		deleteLater ();

		const auto& data = reply->readAll ();

		QDomDocument doc;
		if (!doc.setContent (data))
		{
			qWarning () << Q_FUNC_INFO
					<< "error parsing reply";
			return;
		}

		Media::EventInfos_t result;

		auto eventElem = doc
				.documentElement ()
				.firstChildElement ("events")
				.firstChildElement ("event");
		while (!eventElem.isNull ())
		{
			auto artistsElem = eventElem.firstChildElement ("artists");
			auto venueElem = eventElem.firstChildElement ("venue");
			auto locationElem = venueElem.firstChildElement ("location");
			auto pointElem = locationElem.firstChildElement ("point");

			Media::EventInfo info =
			{
				eventElem.firstChildElement ("id").text ().toInt (),
				eventElem.firstChildElement ("title").text (),
				QString (),
				QLocale ("en_US").toDateTime (eventElem.firstChildElement ("startDate").text (),
							"ddd, dd MMM yyyy hh:mm:ss"),
				eventElem.firstChildElement ("url").text (),
				GetImage (eventElem, "medium"),
				GetImage (eventElem, "extralarge"),
				GetElemsList (artistsElem, "artist"),
				artistsElem.firstChildElement ("headliner").text (),
				GetElemsList (eventElem.firstChildElement ("tags"), "tag"),
				eventElem.firstChildElement ("attendance").text ().toInt (),
				venueElem.firstChildElement ("name").text (),
				pointElem.firstChildElement ("lat").text ().toDouble (),
				pointElem.firstChildElement ("long").text ().toDouble (),
				locationElem.firstChildElement ("city").text (),
				locationElem.firstChildElement ("street").text (),
				true,
				Type_ == Type::Attending ?
						Media::EventAttendType::Surely :
						Media::EventAttendType::None
			};
			result << info;

			eventElem = eventElem.nextSiblingElement ("event");
		}

		emit gotRecommendedEvents (result);
	}