File: SubtitlesDlg.cpp

package info (click to toggle)
fatrat-opensubtitles 1.1.2-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 176 kB
  • ctags: 47
  • sloc: cpp: 466; makefile: 6
file content (366 lines) | stat: -rw-r--r-- 9,584 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
72
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
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
204
205
206
207
208
209
210
211
212
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
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
286
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
/*
FatRat download manager
http://fatrat.dolezel.info

Copyright (C) 2006-2008 Lubos Dolezel <lubos a dolezel.info>

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.

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.
*/

#include "SubtitlesDlg.h"
#include <fatrat/XmlRpc.h>
#include <zlib.h>

#include <fatrat/fatrat.h>
#include <fatrat/RuntimeException.h>
#include <fatrat/Settings.h>

#include <unistd.h>

#include <QMessageBox>
#include <QFileDialog>
#include <QHeaderView>
#include <QtEndian>
#include <QBuffer>
#include <QHttp>
#include <QFile>
#include <QtDebug>

static const char* USER_AGENT = "FatRat " VERSION;
static const char* SERVER_NAME = "www.opensubtitles.org";
static const char* RPC_PATH = "/xml-rpc";

extern const char* g_movieSuffixes[];

SubtitlesDlg::SubtitlesDlg(QWidget* parent)
	: QDialog(parent), m_http(0), m_buffer(0)
{
	setupUi(this);
	
	QStringList hdr = QStringList() << tr("Name") << tr("Language") << tr("Release name") << tr("Part") << tr("Downloads") << tr("Rating");
	treeResults->setHeaderLabels(hdr);
	
	QHeaderView* phdr = treeResults->header();
	phdr->resizeSection(0, 200);
	phdr->resizeSection(1, 80);
	phdr->resizeSection(3, 60);
	phdr->resizeSection(4, 80);
	phdr->resizeSection(5, 80);
	
	connect(toolBrowse, SIGNAL(clicked()), this, SLOT(chooseFile()));
	connect(treeResults, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)), this, SLOT(itemDoubleClicked(QTreeWidgetItem*)));
	connect(this, SIGNAL(finished(int)), this, SLOT(deleteLater()));
	
	m_http = new QHttp(SERVER_NAME, 80, this);
}

QWidget* SubtitlesDlg::create()
{
	return new SubtitlesDlg(getMainWindow());
}

void SubtitlesDlg::chooseFile()
{
	QString filter = "(";
	QString chosenFile;
	
	for(size_t i=0;g_movieSuffixes[i];i++)
	{
		filter += '*';
		filter += g_movieSuffixes[i];
		filter += ' ';
	}
	filter += ')';
	
	chosenFile = QFileDialog::getOpenFileName(this, "FatRat", lineFile->text(), filter);
	
	if(chosenFile.isEmpty())
		return;
	
	search(chosenFile);
}

void SubtitlesDlg::search(QString file)
{
	qint64 filesize;
	QString checksum;
	
	lineFile->setText(file);
	
	checksum = computeMovieHash(file, filesize);
	if(!checksum.isEmpty())
		search(checksum, filesize);
}

void SubtitlesDlg::search(QString checksum, qint64 fileSize)
{
	m_strChecksum = checksum;
	m_fileSize = fileSize;
	
	treeResults->clear();
	treeResults->setEnabled(false);
	toolBrowse->setEnabled(false);
	
	if(m_strSession.isEmpty())
		createSession();
	else
		performSearch();
}

void SubtitlesDlg::createSession()
{
	QByteArray postData;
	m_buffer = new QBuffer(m_http);
	
	postData = XmlRpc::createCall(m_strLastFunction = "LogIn", QVariantList() << "" << "" << "eng" << USER_AGENT);
	
	connect(m_http, SIGNAL(done(bool)), this, SLOT(requestDone(bool)));
	m_http->post(RPC_PATH, postData, m_buffer);
}

void SubtitlesDlg::performSearch()
{
	QVariantList movies;
	QByteArray postData;
	
	QStringList langs = getSettingsValue("subtitle_search/languages").toString().split(';', QString::SkipEmptyParts);
	
	foreach(QString lang, langs)
	{
		QVariantMap movie;
		movie["sublanguageid"] = lang;
		movie["moviehash"] = m_strChecksum;
		movie["moviebytesize"] = double(m_fileSize);
		movies << movie;
	}
	
	postData = XmlRpc::createCall(m_strLastFunction = "SearchSubtitles", QVariantList() << m_strSession << QVariant(movies));
	m_buffer = new QBuffer(m_http);
	m_http->post(RPC_PATH, postData, m_buffer);
}

void SubtitlesDlg::noOperation()
{
	QByteArray postData;
	m_buffer = new QBuffer(m_http);
	
	postData = XmlRpc::createCall(m_strLastFunction = "NoOperation", QVariantList() << m_strSession);
	
	connect(m_http, SIGNAL(done(bool)), this, SLOT(requestDone(bool)));
	m_http->post(RPC_PATH, postData, m_buffer);
}

void SubtitlesDlg::requestDone(bool error)
{
	m_buffer->deleteLater();
	
	try
	{
		if(error)
			throw RuntimeException(tr("The server failed to process our request."));
		
		QVariant result = XmlRpc::parseResponse(m_buffer->data());
		if(result.isNull())
			throw RuntimeException(tr("The server has returned an empty result"));
		
		if(m_strLastFunction == "LogIn")
		{
			QByteArray postData;
			
			m_strSession = result.toMap()["token"].toString();
			
			m_timer.start(10*60*1000);
			connect(&m_timer, SIGNAL(timeout()), this, SLOT(noOperation()));

			if(!m_strChecksum.isEmpty())
				performSearch();
			else
			{
				treeResults->setEnabled(true);
				toolBrowse->setEnabled(true);
			}
		}
		else if(m_strLastFunction == "SearchSubtitles")
		{
			QVariantList list = result.toMap()["data"].toList();
			
			foreach(QVariant sub, list)
			{
				QVariantMap map = sub.toMap();
				
				SubtitleTreeWidgetItem* item = new SubtitleTreeWidgetItem(treeResults);
				
				item->setText(0, QString("%1 (%2)").arg(map["MovieName"].toString()).arg(map["MovieYear"].toString()));
				item->setText(1, map["LanguageName"].toString());
				item->setText(2, map["MovieReleaseName"].toString());
				
				int cds = map["SubSumCD"].toInt();
				if(cds)
					item->setText(3, QString("%1/%2").arg(map["SubActualCD"].toInt()).arg(cds));
				
				item->setText(4, map["SubDownloadsCnt"].toString());
				item->setText(5, map["SubRating"].toString());
				
				item->m_id = map["IDSubtitleFile"].toInt();
				item->m_lang = map["SubLanguageID"].toString();
				item->m_format = map["SubFormat"].toString().toLower();
				
				treeResults->addTopLevelItem(item);
			}
			
			if(list.isEmpty())
				QMessageBox::information(this, "FatRat", tr("No subtitles found!"));
			
			treeResults->setEnabled(true);
			toolBrowse->setEnabled(true);
			m_strChecksum.clear();
		}
		else if(m_strLastFunction == "DownloadSubtitles")
		{
			QString proposedName, originalName, filter;
			originalName = lineFile->text();
			
			SubtitleTreeWidgetItem* item = static_cast<SubtitleTreeWidgetItem*>(treeResults->topLevelItem(m_sel));
			
			int pos = originalName.lastIndexOf('.');
			if(pos < 0)
				pos = originalName.size() - 4;
			
			proposedName = originalName.left(pos+1);
			proposedName += QString("%1.%2").arg(item->m_lang).arg(item->m_format);
			
			filter = QString("(*.%1)").arg(item->m_format);
			
			proposedName = QFileDialog::getSaveFileName(this, "FatRat", proposedName, filter);
			if(!proposedName.isEmpty())
			{
				int fds[2];
				
				if(!::pipe(fds))
				{
					// The server sends it as a string, despite the fact that it's a base64
					// encoded data, for which the XML-RPC specifies a distinct type
					// Therefore we have to do the base64 decoding now
					
					QVariantList list = result.toMap()["data"].toList();
					QByteArray data;
					
					if(list.isEmpty())
						throw RuntimeException(tr("The server didn't return the requested data"));
					
					data = QByteArray::fromBase64(list[0].toMap()["data"].toByteArray());
					
					::write(fds[1], data.constData(), data.size());
					::close(fds[1]);
					
					data.clear();
					
					decompressFile(fds[0], proposedName);
				}
				else
					throw RuntimeException(tr("Failed to allocate a pipe"));
			}
			
			treeResults->setEnabled(true);
			toolBrowse->setEnabled(true);
		}
	}
	catch(const RuntimeException& e)
	{
		QMessageBox::critical(this, "FatRat", e.what());
		toolBrowse->setEnabled(true);
	}
}

QString SubtitlesDlg::computeMovieHash(QString filename, qint64& fsize)
{
	const int CHUNK = 65536;
	qint64* buffer;
	QFile file(filename);
	int read;
	quint64 checksum;
	
	if(!file.open(QIODevice::ReadOnly))
	{
		qDebug() << "Failed to open" << filename;
		return QString();
	}
	
	buffer = new qint64[CHUNK/8];
	checksum = fsize = file.size();
	
	read = file.read((char*) buffer, CHUNK);
	for(int i=0;i<read/8;i++)
		checksum += qFromLittleEndian(buffer[i]);
	
	file.seek(qMax<qint64>(0, fsize-CHUNK));
	
	read = file.read((char*) buffer, CHUNK);
	for(int i=0;i<read/8;i++)
		checksum += qFromLittleEndian(buffer[i]);
	
	delete [] buffer;
	
	if(fsize < 65536)
	{
		QMessageBox::warning(getMainWindow(), "FatRat",
			QObject::tr("You have selected a file smaller than 64 kilobytes. "
				"The OpenSubtitles.org checksumming algorithm is not designed to deal with such files. "
				"Therefore the generated checksum is very likely unusable."));
	}
	
	return QString::number(checksum, 16);
}

void SubtitlesDlg::itemDoubleClicked(QTreeWidgetItem* i)
{
	QByteArray postData;
	QVariantList subs;
	SubtitleTreeWidgetItem* item = static_cast<SubtitleTreeWidgetItem*>(i);
	
	m_buffer = new QBuffer(m_http);
	subs << item->m_id;
	postData = XmlRpc::createCall(m_strLastFunction = "DownloadSubtitles", QVariantList() << m_strSession << QVariant(subs));
	
	treeResults->setEnabled(false);
	toolBrowse->setEnabled(false);
	
	m_sel = treeResults->indexOfTopLevelItem(i);
	m_http->post(RPC_PATH, postData, m_buffer);
}

void SubtitlesDlg::decompressFile(int infd, QString unzipped)
{
	char buffer[4096];
	QFile fout(unzipped);
	gzFile file;
	
	if(!fout.open(QIODevice::WriteOnly))
		return;
	
	file = gzdopen(infd, "rb");
	if(!file)
		return;
	
	while(true)
	{
		int bytes = gzread(file, buffer, sizeof buffer);
		if(bytes <= 0)
			break;
		fout.write(buffer, bytes);
	}
	
	gzclose(file);
}