OSDN Git Service

It's 2011 now.
[qt-creator-jp/qt-creator-jp.git] / src / plugins / cpaster / pastebindotcaprotocol.cpp
1 /**************************************************************************
2 **
3 ** This file is part of Qt Creator
4 **
5 ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
6 **
7 ** Contact: Nokia Corporation (qt-info@nokia.com)
8 **
9 ** No Commercial Usage
10 **
11 ** This file contains pre-release code and may not be distributed.
12 ** You may use this file in accordance with the terms and conditions
13 ** contained in the Technology Preview License Agreement accompanying
14 ** this package.
15 **
16 ** GNU Lesser General Public License Usage
17 **
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file.  Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 **
25 ** In addition, as a special exception, Nokia gives you certain additional
26 ** rights.  These rights are described in the Nokia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 **
29 ** If you have questions regarding the use of this file, please contact
30 ** Nokia at qt-info@nokia.com.
31 **
32 **************************************************************************/
33
34 #include "pastebindotcaprotocol.h"
35
36 #include <utils/qtcassert.h>
37
38 #include <QtNetwork/QNetworkReply>
39 #include <QtCore/QXmlStreamReader>
40 #include <QtCore/QXmlStreamAttributes>
41 #include <QtCore/QStringList>
42
43 static const char urlC[] = "http://pastebin.ca/";
44
45 namespace CodePaster {
46 PasteBinDotCaProtocol::PasteBinDotCaProtocol(const NetworkAccessManagerProxyPtr &nw) :
47     NetworkProtocol(nw),
48     m_fetchReply(0),
49     m_listReply(0),
50     m_pasteReply(0),
51     m_hostChecked(false)
52 {
53 }
54
55 unsigned PasteBinDotCaProtocol::capabilities() const
56 {
57     return ListCapability | PostDescriptionCapability;
58 }
59
60 void PasteBinDotCaProtocol::fetch(const QString &id)
61 {
62     QTC_ASSERT(!m_fetchReply, return)
63     const QString url = QLatin1String(urlC);
64     const QString rawPostFix = QLatin1String("raw/");
65     // Create link as ""http://pastebin.ca/raw/[id]"
66     // If we get a complete URL, just insert 'raw', else build URL.
67     QString link = id;
68     if (link.startsWith(url)) {
69         const int lastSlashPos = link.lastIndexOf(QLatin1Char('/'));
70         if (lastSlashPos != -1)
71             link.insert(lastSlashPos + 1, rawPostFix);
72     } else {
73         link.insert(0, rawPostFix);
74         link.insert(0, url);
75     }
76     m_fetchReply = httpGet(link);
77     connect(m_fetchReply, SIGNAL(finished()), this, SLOT(fetchFinished()));
78     m_fetchId = id;
79 }
80
81 void PasteBinDotCaProtocol::paste(const QString &text,
82                                   ContentType /* ct */,
83                                   const QString &username,
84                                   const QString & /* comment */,
85                                   const QString &description)
86 {
87     QTC_ASSERT(!m_pasteReply, return)
88     QByteArray data = "content=";
89     data += QUrl::toPercentEncoding(fixNewLines(text));
90     data += "&description=";
91     data += QUrl::toPercentEncoding(description);
92     data += "&type=1&expiry=1%20day&name=";
93     data += QUrl::toPercentEncoding(username);
94     // fire request
95     const QString link = QLatin1String(urlC) + QLatin1String("quiet-paste.php");
96     m_pasteReply = httpPost(link, data);
97     connect(m_pasteReply, SIGNAL(finished()), this, SLOT(pasteFinished()));
98 }
99
100 void PasteBinDotCaProtocol::pasteFinished()
101 {
102     if (m_pasteReply->error()) {
103         qWarning("Pastebin.ca protocol error: %s", qPrintable(m_pasteReply->errorString()));
104     } else {
105         /// returns ""SUCCESS:[id]""
106         const QByteArray data = m_pasteReply->readAll();
107         const QString link = QString::fromLatin1(urlC) + QString::fromAscii(data).remove(QLatin1String("SUCCESS:"));
108         emit pasteDone(link);
109     }
110     m_pasteReply->deleteLater();
111     m_pasteReply = 0;
112 }
113
114 void PasteBinDotCaProtocol::fetchFinished()
115 {
116     QString title;
117     QString content;
118     bool error = m_fetchReply->error();
119     if (error) {
120         content = m_fetchReply->errorString();
121     } else {
122         title = QString::fromLatin1("Pastebin.ca: %1").arg(m_fetchId);
123         const QByteArray data = m_fetchReply->readAll();
124         content = QString::fromUtf8(data);
125         content.remove(QLatin1Char('\r'));
126     }
127     m_fetchReply->deleteLater();
128     m_fetchReply = 0;
129     emit fetchDone(title, content, error);
130 }
131
132 void PasteBinDotCaProtocol::list()
133 {
134     QTC_ASSERT(!m_listReply, return);
135     m_listReply = httpGet(QLatin1String(urlC));
136     connect(m_listReply, SIGNAL(finished()), this, SLOT(listFinished()));
137 }
138
139 bool PasteBinDotCaProtocol::checkConfiguration(QString *errorMessage)
140 {
141     if (m_hostChecked) // Check the host once.
142         return true;
143     const bool ok = httpStatus(QLatin1String(urlC), errorMessage);
144     if (ok)
145         m_hostChecked = true;
146     return ok;
147 }
148
149 /* Quick & dirty: Parse the <div>-elements with the "Recent Posts" listing
150  * out of the page.
151 \code
152 <div class="menutitle"><h2>Recent Posts</h2></div>
153     <div class="items" id="idmenurecent-collapse">
154         <div class='recentlink'>
155             <a href="/[id]" class="rjt" rel="/preview.php?id=[id]">[nameTitle]</a>
156             <div class='recentdetail'>[time spec]</div>
157         </div>
158  ...<h2>Create a New Pastebin Post</h2>
159 \endcode */
160
161 static inline QStringList parseLists(QIODevice *io)
162 {
163     enum State { OutsideRecentLink, InsideRecentLink };
164
165     QStringList rc;
166
167     const QString classAttribute = QLatin1String("class");
168     const QString divElement = QLatin1String("div");
169     const QString anchorElement = QLatin1String("a");
170
171     // Start parsing at the 'recent posts' entry as the HTML above is not well-formed
172     // as of 8.4.2010. This will then terminate with an error.
173     QByteArray data = io->readAll();
174     const QByteArray recentPosts("<h2>Recent Posts</h2></div>");
175     const int recentPostsPos = data.indexOf(recentPosts);
176     if (recentPostsPos == -1)
177         return rc;
178     data.remove(0, recentPostsPos + recentPosts.size());
179     QXmlStreamReader reader(data);
180     State state = OutsideRecentLink;
181     while (!reader.atEnd()) {
182         switch(reader.readNext()) {
183         case QXmlStreamReader::StartElement:
184             // Inside a <div> of an entry: Anchor or description
185             if (state == InsideRecentLink && reader.name() == anchorElement) { // Anchor
186                 // Strip host from link
187                 QString link = reader.attributes().value(QLatin1String("href")).toString();
188                 if (link.startsWith(QLatin1Char('/')))
189                     link.remove(0, 1);
190                 const QString nameTitle = reader.readElementText();
191                 rc.push_back(link + QLatin1Char(' ') + nameTitle);
192             } else if (state == OutsideRecentLink && reader.name() == divElement) { // "<div>" state switching
193                 if (reader.attributes().value(classAttribute) == QLatin1String("recentlink"))
194                     state = InsideRecentLink;
195             } // divElement
196             break;
197        default:
198             break;
199         } // switch reader
200     } // while reader.atEnd()
201     return rc;
202 }
203
204 void PasteBinDotCaProtocol::listFinished()
205 {
206     const bool error = m_listReply->error();
207     if (error) {
208         qWarning("pastebin.ca list failed: %s", qPrintable(m_listReply->errorString()));
209     } else {
210         emit listDone(name(), parseLists(m_listReply));
211     }
212     m_listReply->deleteLater();
213     m_listReply = 0;
214 }
215
216 } // namespace CodePaster