YouTubeUploader.cpp 7.77 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*****************************************************************************
 * YouTubeUploader.cpp: YouTube Video Uploader class
 *****************************************************************************
 * Copyright (C) 2010 VideoLAN
 *
 * Authors: Rohit Yadav <rohityadav89 AT gmail.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

23 24 25 26
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

27
#include "Services/UploaderIODevice.h"
28
#include "Tools/VlmcDebug.h"
29 30 31 32 33 34 35 36 37 38
#include "YouTubeService.h"
#include "YouTubeUploader.h"
#include "YouTubeFeedParser.h"

#include <QByteArray>
#include <QNetworkRequest>
#include <QString>
#include <QStringList>
#include <QUrl>

39 40
using namespace YouTube;

41
YouTubeUploader::YouTubeUploader( YouTubeService* service,
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
                                  const QString& fileName )
{
    /* Stores pointer to main service object and video file path */
    m_service  = service;
    m_fileName = fileName;

    m_nam = new QNetworkAccessManager( this );

    /* Handles SSL errors for better security */
    #ifndef QT_NO_OPENSSL
    connect( m_nam, SIGNAL( sslErrors( QNetworkReply*, QList<QSslError> ) ),
             m_service, SLOT( sslErrors( QNetworkReply*, QList<QSslError> ) ) );
    #endif

    /* Pointer for custom IODevice needed to upload video */
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
57
    m_ioDevice = nullptr;
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
    uploadInit();
}

YouTubeUploader::~YouTubeUploader()
{
    /* Checks and deletes objects */
    delete m_nam;
    if( m_ioDevice )
        delete m_ioDevice;
}

void
YouTubeUploader::uploadInit()
{
    /* Random 10 digit boundary string, as per protocol */
73
    m_boundary = QString( QString::number( qrand(), 10 ).toLatin1() );
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

    QString privateToken = "";

    if( m_videoData.isPrivate )
        privateToken = "    <yt:private/>\r\n";

    API_XML_REQUEST =
        "<?xml version='1.0'?>\r\n"
        "<entry\r\n"
        "  xmlns='http://www.w3.org/2005/Atom'\r\n"
        "  xmlns:media='http://search.yahoo.com/mrss/'\r\n"
        "  xmlns:yt='http://gdata.youtube.com/schemas/2007'>\r\n"
        "  <media:group>\r\n"
        "    <media:title type='plain'>%1</media:title>\r\n"              // 1 title
        "    <media:description type='plain'>%2</media:description>\r\n"  // 2 description
        "    <media:category scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>%3\r\n" // 3 category
        "    </media:category>\r\n"
91
        "    <media:keywords>%4</media:keywords>\r\n%5"                   // 4 key words, 5 private video
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
        "  </media:group>\r\n"
        "</entry>\r\n";

    /* API Request as per protocol */
    API_XML_REQUEST = API_XML_REQUEST.arg( m_videoData.title, m_videoData.description,
                                           m_videoData.category, m_videoData.keywords,
                                           privateToken );
}

bool
YouTubeUploader::upload()
{
    /* Creates IODevice with all details */
    if( !m_ioDevice )
        m_ioDevice = new UploaderIODevice( this, m_fileName,
                                           getMimeHead(), getMimeTail() );
    else
        m_ioDevice->setFile( m_fileName );

    /* Creates HTTP header */
    QNetworkRequest request = getNetworkRequest();
    request.setHeader( QNetworkRequest::ContentLengthHeader, m_ioDevice->size() );
    request.setRawHeader( "Connection", "close" );

    /* Tries to open file and send a HTTP POST */
    if( m_ioDevice->openFile() )
    {
        QNetworkReply* reply = m_nam->post( request, m_ioDevice );
        m_service->m_state = UploadStart;

        connect( reply, SIGNAL( finished() ),
                 this, SLOT( uploadFinished() ) );
        connect( reply, SIGNAL( uploadProgress( qint64, qint64 ) ),
                 this, SIGNAL( uploadProgress( qint64, qint64 ) ) );
        connect( reply, SIGNAL( error( QNetworkReply::NetworkError ) ),
                 m_service, SLOT( networkError( QNetworkReply::NetworkError ) ) );

        return true;
    }
131
    vlmcDebug() << "[YT UPLOADER]: File opening failed.";
132 133 134 135 136 137 138 139 140 141
    return false;
}

void
YouTubeUploader::uploadFinished()
{
    /* Captures data received after uploading the video */
    QNetworkReply *reply = static_cast<QNetworkReply *>( sender() );
    const QByteArray data = reply->readAll();

142
    vlmcDebug() << "In YouTubeUploader::uploadFinished: data received =" << data;
143 144 145 146 147 148 149
    m_service->m_state = UploadFinish;

    /* Feed parser called to parse the XML data received */
    YouTubeFeedParser parser( data );
    parser.read();

    /* Checks VideoID parsed by the parser */
150 151 152 153 154
    QString videoUrl;
    if ( parser.getVideoId() != "" )
        videoUrl = VIDEO_URL + parser.getVideoId();
    else
        videoUrl = ""; /* Some error may've occured at YouTube */
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170

    emit uploadOver( QString( videoUrl ) );

    disconnect( reply, SIGNAL( finished() ),
                this, SLOT( uploadFinished() ) );
    disconnect( reply, SIGNAL( uploadProgress( qint64, qint64 ) ),
                this, SIGNAL( uploadProgress( qint64, qint64 ) ) );
    disconnect( reply, SIGNAL( error( QNetworkReply::NetworkError ) ),
                m_service, SLOT( networkError( QNetworkReply::NetworkError ) ) );

    reply->close();
    reply->deleteLater();

    if( m_ioDevice )
        delete m_ioDevice;

Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
171
    m_ioDevice = nullptr;
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 204 205 206 207 208 209 210 211
}

QNetworkRequest
YouTubeUploader::getNetworkRequest()
{
    QUrl url( UPLOAD_URL );

    QNetworkRequest request;
    request.setUrl(url);

    /* Use the auth string for authentication of uploading */
    request.setRawHeader( "Authorization", QByteArray( "GoogleLogin auth=" )
                          .append( m_service->getAuthString() ) );

    /* This implements v2.0 protocol */
    request.setRawHeader( "GData-Version", "2" );

    /* Developer is used to track API usage */
    request.setRawHeader( "X-GData-Key", QByteArray( "key=" )
                          .append( m_service->getDeveloperKey() ) );

    /* Name of the video, the user is uploading */
    request.setRawHeader( "Slug", QByteArray( "" ).append( m_fileName ) );

    request.setRawHeader( "Content-Type",
                          QByteArray( "multipart/related; boundary=" )
                          .append( m_boundary ) );

    return request;
}

QByteArray
YouTubeUploader::getMimeHead()
{
    /* Head ByteArray data, as per the protocol */
    QByteArray data;
    data.append( "\r\n\r\n--" + m_boundary + "\r\n" );
    data.append( "Content-Type: application/atom+xml; charset=UTF-8\r\n\r\n" );
    data.append( API_XML_REQUEST );
    data.append( "--" + m_boundary + "\r\n" );
212
    data.append( "Content-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\n\r\n" );
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250

    return data;
}

QByteArray
YouTubeUploader::getMimeTail()
{
    /* Tail ByteArray data, as per the protocol */
    QByteArray data;
    data.append( "\r\n--" + m_boundary + "--\r\n\r\n" );

    return data;
}

const VideoData&
YouTubeUploader::getVideoData()
{
    return m_videoData;
}

void
YouTubeUploader::setServiceProvider(YouTubeService *service)
{
    m_service = service;
}

void
YouTubeUploader::setVideoFile( const QString& fileName )
{
    m_fileName = fileName;
}

void
YouTubeUploader::setVideoData( const VideoData& data )
{
    m_videoData = data;
    uploadInit();
}