UBYouTubePublisher.cpp 12.9 KB
Newer Older
Claudio Valerio's avatar
Claudio Valerio committed
1
/*
2
 * Copyright (C) 2015-2018 Département de l'Instruction Publique (DIP-SEM)
Craig Watson's avatar
Craig Watson committed
3
 *
Claudio Valerio's avatar
Claudio Valerio committed
4
 * Copyright (C) 2013 Open Education Foundation
Claudio Valerio's avatar
Claudio Valerio committed
5
 *
Claudio Valerio's avatar
Claudio Valerio committed
6 7
 * Copyright (C) 2010-2013 Groupement d'Intérêt Public pour
 * l'Education Numérique en Afrique (GIP ENA)
8
 *
Claudio Valerio's avatar
Claudio Valerio committed
9 10 11
 * This file is part of OpenBoard.
 *
 * OpenBoard is free software: you can redistribute it and/or modify
Claudio Valerio's avatar
Claudio Valerio committed
12 13
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License,
14 15 16 17
 * with a specific linking exception for the OpenSSL project's
 * "OpenSSL" library (or with modified versions of it that use the
 * same license as the "OpenSSL" library).
 *
Claudio Valerio's avatar
Claudio Valerio committed
18
 * OpenBoard is distributed in the hope that it will be useful,
Claudio Valerio's avatar
Claudio Valerio committed
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
Claudio Valerio's avatar
Claudio Valerio committed
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Claudio Valerio's avatar
Claudio Valerio committed
21
 * GNU General Public License for more details.
Claudio Valerio's avatar
Claudio Valerio committed
22
 *
Claudio Valerio's avatar
Claudio Valerio committed
23
 * You should have received a copy of the GNU General Public License
Claudio Valerio's avatar
Claudio Valerio committed
24
 * along with OpenBoard. If not, see <http://www.gnu.org/licenses/>.
Claudio Valerio's avatar
Claudio Valerio committed
25 26
 */

27

Claudio Valerio's avatar
Claudio Valerio committed
28

Claudio Valerio's avatar
Claudio Valerio committed
29

Claudio Valerio's avatar
Claudio Valerio committed
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
#include "UBYouTubePublisher.h"



#include "frameworks/UBFileSystemUtils.h"

#include "core/UBApplication.h"
#include "core/UBSettings.h"
#include "core/UBSetting.h"

#include "gui/UBMainWindow.h"

#include "network/UBNetworkAccessManager.h"
#include "network/UBServerXMLHttpRequest.h"

45 46
#include "core/memcheck.h"

Claudio Valerio's avatar
Claudio Valerio committed
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
// API key linked to account dev.mnemis@gmail.com
const QString UBYouTubePublisher::sYouTubeDeveloperKey("AI39si62ga82stA4YBr5JjkfuRsFT-QyC4UYsFn7yYQFMe_dzg8xOc0r91BOhxSEhEr0gdWJGNnDsYbv9wvpyROd2Yre-6Zh7g");

UBYouTubePublisher::UBYouTubePublisher(QObject* pParent)
    : QObject(pParent)
    , mAuthRequest(0)
    , mUploadRequest(0)
{
    // NOOP
}


UBYouTubePublisher::~UBYouTubePublisher()
{
    // NOOP
}


void UBYouTubePublisher::uploadVideo(const QString& videoFilePath)
{
    mVideoFilePath = videoFilePath;

    UBYouTubePublishingDialog pub(videoFilePath, UBApplication::mainWindow);

    pub.title->setText(QFileInfo(mVideoFilePath).completeBaseName());
72
    pub.keywords->setText(qApp->applicationName());
Claudio Valerio's avatar
Claudio Valerio committed
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109

    QString defaultEMail = UBSettings::settings()->youTubeUserEMail->get().toString();
    pub.email->setText(defaultEMail);

    QString defaultPassword = UBSettings::settings()->password(defaultEMail);
    pub.password->setText(defaultPassword);

    if (pub.exec() == QDialog::Accepted)
    {
        mTitle = pub.title->text();
        mDescription = pub.description->toPlainText();
        mCategories << pub.category->itemData(pub.category->currentIndex()).toString();
        mKeywords = pub.keywords->text();

        QString email = pub.email->text();
        UBSettings::settings()->youTubeUserEMail->set(email);

        QString password = pub.password->text();

        UBSettings::settings()->setPassword(email, password);

        postClientLoginRequest(email, password);
    }
    else
    {
        deleteLater();
    }
}


void UBYouTubePublisher::postClientLoginRequest(const QString& userName, const QString& password)
{
    QString mUserName = userName;

    QUrl url("https://www.google.com/youtube/accounts/ClientLogin");

    mAuthRequest = new UBServerXMLHttpRequest(UBNetworkAccessManager::defaultAccessManager()
110
                                              , "application/x-www-form-urlencoded"); // destroyed in postClientLoginResponse
Claudio Valerio's avatar
Claudio Valerio committed
111 112 113 114 115 116

    connect(mAuthRequest, SIGNAL(finished(bool, const QByteArray&)), this, SLOT(postClientLoginResponse(bool, const QByteArray&)));

    mAuthRequest->addHeader("X-GData-Key", sYouTubeDeveloperKey);

    QString payload = QString("Email=%1&Passwd=%2&service=youtube&source=%3")
117 118
            .arg(userName)
            .arg(password)
119
            .arg(qApp->applicationName());
Claudio Valerio's avatar
Claudio Valerio committed
120 121 122 123 124 125 126 127

    mAuthRequest->post(url, payload.toUtf8());

}


void UBYouTubePublisher::postClientLoginResponse(bool success, const QByteArray& pPayload)
{
Claudio Valerio's avatar
Claudio Valerio committed
128
    Q_UNUSED(success);
Claudio Valerio's avatar
Claudio Valerio committed
129 130 131 132 133 134 135 136 137 138 139 140
    mAuthToken = "";

    QString auth = QString::fromUtf8(pPayload);

    if (auth.contains("Auth="))
    {
        QStringList lines = auth.split("\n");

        foreach(QString line, lines)
        {
            if(line.startsWith("Auth="))
            {
141 142
                mAuthToken = line.replace("Auth=", "");
                break;
Claudio Valerio's avatar
Claudio Valerio committed
143 144 145 146 147 148 149 150 151 152
            }
        }
    }

    mAuthRequest->deleteLater();
    mAuthRequest = 0;

    if(mAuthToken.length() == 0)
    {
        UBApplication::showMessage(tr("YouTube authentication failed."));
153
        //        success = false;
Claudio Valerio's avatar
Claudio Valerio committed
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
        deleteLater();
    }
    else
    {
        qDebug() << "Retreived youtube auth token" << mAuthToken;
        postVideoUploadRequest();
    }
}


void UBYouTubePublisher::postVideoUploadRequest()
{
    /*
     *  POST /feeds/api/users/default/uploads HTTP/1.1
        Host: gdata.youtube.com
        Authorization: GoogleLogin auth=<authentication_token>
        GData-Version: 2
        X-GData-Client: <client_id>
        X-GData-Key: key=<developer_key>
        Slug: <video_filename>
        Content-Type: multipart/related; boundary="<boundary_string>"
        Content-Length: <content_length>
        Connection: close

        --<boundary_string>
        Content-Type: application/atom+xml; charset=UTF-8

        API_XML_request
        --<boundary_string>
        Content-Type: <video_content_type>
        Content-Transfer-Encoding: binary

        <Binary File Data>
        --<boundary_string>--
     */

    QFile videoFile(mVideoFilePath);

    if(!videoFile.open(QIODevice::ReadOnly))
    {
        qWarning() << "Cannot open file" << mVideoFilePath << "for upload to youtube";
        return;
    }

    QUrl url("http://uploads.gdata.youtube.com/feeds/api/users/default/uploads");

    QString boundary = "---------------------------f93dcbA3";
    QString contentType = QString("multipart/related; boundary=\"%1\"").arg(boundary);

    mUploadRequest = new UBServerXMLHttpRequest(UBNetworkAccessManager::defaultAccessManager()
204
                                                , contentType); // destroyed in postVideoUploadResponse
Claudio Valerio's avatar
Claudio Valerio committed
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221

    mUploadRequest->setVerbose(true);
    connect(mUploadRequest, SIGNAL(progress(qint64, qint64)), this,  SLOT(progress(qint64, qint64)));

    connect(mUploadRequest, SIGNAL(finished(bool, const QByteArray&)), this, SLOT(postVideoUploadResponse(bool, const QByteArray&)));

    mUploadRequest->addHeader("X-GData-Key", "key=" + sYouTubeDeveloperKey);
    mUploadRequest->addHeader("Authorization", QString("GoogleLogin auth=%1").arg(mAuthToken));
    mUploadRequest->addHeader("GData-Version", "2");

    QFileInfo fi(mVideoFilePath);
    mUploadRequest->addHeader("Slug", fi.fileName());
    mUploadRequest->addHeader("Connection", "close"); // do we really ned that ?

    QByteArray payload;

    payload.append(QString("\n--" + boundary + "\n").toUtf8())
222 223
            .append(QString("Content-Type: application/atom+xml; charset=UTF-8\n\n").toUtf8())
            .append(youtubeMetadata().toUtf8());
Claudio Valerio's avatar
Claudio Valerio committed
224 225 226 227 228 229

    payload.append(QString("\n--" + boundary + "\n").toUtf8());

    QString videoMimeType = UBFileSystemUtils::mimeTypeFromFileName(mVideoFilePath);

    payload.append((QString("Content-Type: %1\n").arg(videoMimeType)).toUtf8())
230
            .append(QString("Content-Transfer-Encoding: binary\n\n").toUtf8());
Claudio Valerio's avatar
Claudio Valerio committed
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285

    payload.append(videoFile.readAll());

    payload.append(QString("\n--" + boundary + "--\n").toUtf8());

    mUploadRequest->post(url, payload);
}


void UBYouTubePublisher::postVideoUploadResponse(bool success, const QByteArray& pPayload)
{
    mUploadRequest->deleteLater();

    if(success)
    {
        UBApplication::showMessage("The video has been uploaded to youtube", false);
    }
    else
    {
        qWarning() << "error uploading video to youtube" << QString::fromUtf8(pPayload);

        UBApplication::showMessage(tr("Error while uploading video to YouTube (%1)").arg(QString::fromUtf8(pPayload)), false);
    }

    deleteLater();
}


QString UBYouTubePublisher::youtubeMetadata()
{
    QString workingTitle;

    if (mTitle.length() > 0)
    {
        workingTitle = mTitle;
    }
    else
    {
        workingTitle = QFileInfo(mVideoFilePath).completeBaseName();
    }

    QString metadata;

    metadata += "<?xml version=\"1.0\"?>\n";
    metadata += "<entry xmlns=\"http://www.w3.org/2005/Atom\" xmlns:media=\"http://search.yahoo.com/mrss/\" xmlns:yt=\"http://gdata.youtube.com/schemas/2007\">\n";
    metadata += "  <media:group>\n";
    metadata += QString("    <media:title type=\"plain\">%1</media:title>\n").arg(workingTitle);

    QString workingDescription = mDescription;

    if (workingDescription.length() > 4900)
    {
        workingDescription = workingDescription.left(4900) + "...";
    }

286
    workingDescription += "\n\nhttp://www.openboard.org";
Claudio Valerio's avatar
Claudio Valerio committed
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350

    if(workingDescription.length() == 0)
    {
        workingDescription = workingTitle;
    }

    metadata += QString("    <media:description type=\"plain\">%1</media:description>\n").arg(workingDescription);

    foreach(QString cat, mCategories)
    {
        metadata += QString("    <media:category scheme=\"http://gdata.youtube.com/schemas/2007/categories.cat\">%1</media:category>\n").arg(cat);
    }

    if (mKeywords.length() > 0)
    {
        metadata += QString("    <media:keywords>%1</media:keywords>\n").arg(mKeywords);
    }

    metadata += "  </media:group>\n";
    metadata += "</entry>";

    return metadata;

}


void UBYouTubePublisher::progress (qint64 bytesSent, qint64 bytesTotal )
{
    int percentage = (((qreal)bytesSent / (qreal)bytesTotal ) * 100);

    UBApplication::showMessage(tr("Upload to YouTube in progress %1 %").arg(percentage), percentage < 100);
}



UBYouTubePublishingDialog::UBYouTubePublishingDialog(const QString& videoFilePath, QWidget *parent)
    : QDialog(parent)
{
    Q_UNUSED(videoFilePath);

    Ui::YouTubePublishingDialog::setupUi(this);

    QMap<QString, QString> cats = categories();

    category->clear();
    int index = 0;
    foreach(QString cat, cats.keys())
    {
        category->addItem(cats.value(cat), cat);
        if(cat == "Education")
            category->setCurrentIndex(index);

        index++;
    }

    connect(dialogButtons, SIGNAL(accepted()), this, SLOT(accept()));
    connect(dialogButtons, SIGNAL(rejected()), this, SLOT(reject()));

    connect(title, SIGNAL(textChanged(const QString&)), this, SLOT(updateUIState(const QString&)));
    connect(description, SIGNAL(textChanged()), this, SLOT(updateUIState()));
    connect(keywords, SIGNAL(textChanged(const QString&)), this, SLOT(updateUIState(const QString&)));

    connect(email, SIGNAL(textChanged(const QString&)), this, SLOT(updateUIState(const QString&)));
    connect(password, SIGNAL(textChanged(const QString&)), this, SLOT(updateUIState(const QString&)));
Claudio Valerio's avatar
Claudio Valerio committed
351
    connect(youtubeCredentialsPersistence,SIGNAL(clicked()), this, SLOT(updateCredentialPersistenceState()));
Claudio Valerio's avatar
Claudio Valerio committed
352 353 354 355

    dialogButtons->button(QDialogButtonBox::Ok)->setEnabled(false);
    dialogButtons->button(QDialogButtonBox::Ok)->setText(tr("Upload"));

356 357 358 359 360
    UBSettings* settings = UBSettings::settings();

    email->setText(settings->youTubeUserEMail->get().toString());
    password->setText(settings->password(email->text()));

Claudio Valerio's avatar
Claudio Valerio committed
361
    youtubeCredentialsPersistence->setChecked(UBSettings::settings()->youTubeCredentialsPersistence->get().toBool());
362
    updatePersistanceEnableState();
Claudio Valerio's avatar
Claudio Valerio committed
363 364 365 366 367 368 369 370 371 372 373 374
}


void UBYouTubePublishingDialog::updateCredentialPersistenceState()
{
    UBSettings::settings()->youTubeCredentialsPersistence->set(QVariant(youtubeCredentialsPersistence->checkState()));
}

void UBYouTubePublishingDialog::updatePersistanceEnableState()
{
    bool enabled = email->text().length() || password->text().length();
    youtubeCredentialsPersistence->setEnabled(enabled);
375
    youtubeCredentialsPersistence->setStyleSheet(enabled ? "color:black;" : "color : lightgrey;");
Claudio Valerio's avatar
Claudio Valerio committed
376 377 378 379 380 381
}

void UBYouTubePublishingDialog::updateUIState(const QString& string)
{
    Q_UNUSED(string);

382 383 384 385 386
    bool ok = title->text().length() > 0
            &&  description->toPlainText().length() > 0
            &&  keywords->text().length() > 0
            &&  email->text().length() > 0
            &&  password->text().length() > 0;
Claudio Valerio's avatar
Claudio Valerio committed
387 388

    dialogButtons->button(QDialogButtonBox::Ok)->setEnabled(ok);
389
    updatePersistanceEnableState();
Claudio Valerio's avatar
Claudio Valerio committed
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
}


QMap<QString, QString> UBYouTubePublishingDialog::categories()
{
    // TODO UB 4.x download localized list from
    // http://code.google.com/apis/youtube/2.0/reference.html#Localized_Category_Lists

    QMap<QString, QString> cats;

    cats.insert("Autos", tr("Autos & Vehicles"));
    cats.insert("Music", tr("Music"));
    cats.insert("Animals", tr("Pets & Animals"));
    cats.insert("Sports", tr("Sports"));
    cats.insert("Travel", tr("Travel & Events"));
    cats.insert("Games", tr("Gaming"));
    cats.insert("Comedy", tr("Comedy"));
    cats.insert("People", tr("People & Blogs"));
    cats.insert("News", tr("News & Politics"));
    cats.insert("Entertainment", tr("Entertainment"));
    cats.insert("Education", tr("Education"));
    cats.insert("Howto", tr("Howto & Style"));
    cats.insert("Nonprofit", tr("Nonprofits & Activism"));
    cats.insert("Tech", tr("Science & Technology"));

    return cats;
}