source: smplayer/trunk/src/findsubtitles/findsubtitleswindow.cpp@ 156

Last change on this file since 156 was 156, checked in by Silvan Scherrer, 11 years ago

SMPlayer: update trunk to 0.8.6

  • Property svn:eol-style set to LF
File size: 25.9 KB
Line 
1/* smplayer, GUI front-end for mplayer.
2 Copyright (C) 2006-2013 Ricardo Villalba <rvm@users.sourceforge.net>
3
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17*/
18
19#include "findsubtitleswindow.h"
20#include "findsubtitlesconfigdialog.h"
21
22#include "osclient.h"
23#include "filehash.h"
24#include "languages.h"
25#include <QStandardItemModel>
26#include <QSortFilterProxyModel>
27#include <QHeaderView>
28#include <QMessageBox>
29#include <QDesktopServices>
30#include <QUrl>
31#include <QMap>
32#include <QMenu>
33#include <QAction>
34#include <QClipboard>
35#include <QSettings>
36
37#ifdef DOWNLOAD_SUBS
38#include <QBuffer>
39#include "filedownloader.h"
40#include "subchooserdialog.h"
41#include "fixsubs.h"
42
43#ifdef USE_QUAZIP
44#include "quazip.h"
45#include "quazipfile.h"
46#include <QTemporaryFile>
47#else
48#include <zlib.h>
49#endif
50
51#endif
52
53//#define NO_SMPLAYER_SUPPORT
54
55#ifndef NO_SMPLAYER_SUPPORT
56#include "images.h"
57#endif
58
59#define COL_LANG 0
60#define COL_NAME 1
61#define COL_FORMAT 2
62#define COL_FILES 3
63#define COL_DATE 4
64#define COL_USER 5
65
66FindSubtitlesWindow::FindSubtitlesWindow( QWidget * parent, Qt::WindowFlags f )
67 : QDialog(parent,f)
68{
69 setupUi(this);
70
71 set = 0; // settings
72
73 subtitles_for_label->setBuddy(file_chooser);
74
75 progress->hide();
76
77 connect( file_chooser, SIGNAL(fileChanged(QString)),
78 this, SLOT(setMovie(QString)) );
79 connect( file_chooser, SIGNAL(textChanged(const QString &)),
80 this, SLOT(updateRefreshButton()) );
81
82 connect( refresh_button, SIGNAL(clicked()),
83 this, SLOT(refresh()) );
84
85 connect( download_button, SIGNAL(clicked()),
86 this, SLOT(download()) );
87
88 /*
89 connect( language_filter, SIGNAL(editTextChanged(const QString &)),
90 this, SLOT(applyFilter(const QString &)) );
91 */
92 connect( language_filter, SIGNAL(activated(int)),
93 this, SLOT(applyCurrentFilter()) );
94
95 table = new QStandardItemModel(this);
96 table->setColumnCount(COL_USER + 1);
97
98 proxy_model = new QSortFilterProxyModel(this);
99 proxy_model->setSourceModel(table);
100 proxy_model->setFilterKeyColumn(COL_LANG);
101 proxy_model->setFilterRole(Qt::UserRole);
102
103 view->setModel(proxy_model);
104 view->setRootIsDecorated(false);
105 view->setSortingEnabled(true);
106 view->setAlternatingRowColors(true);
107 view->header()->setSortIndicator(COL_LANG, Qt::AscendingOrder);
108 view->setEditTriggers(QAbstractItemView::NoEditTriggers);
109 view->setContextMenuPolicy( Qt::CustomContextMenu );
110
111 connect(view, SIGNAL(activated(const QModelIndex &)),
112 this, SLOT(itemActivated(const QModelIndex &)) );
113 connect(view->selectionModel(), SIGNAL(currentChanged(const QModelIndex &,const QModelIndex &)),
114 this, SLOT(currentItemChanged(const QModelIndex &,const QModelIndex &)) );
115
116 connect(view, SIGNAL(customContextMenuRequested(const QPoint &)),
117 this, SLOT(showContextMenu(const QPoint &)) );
118
119 /*
120 downloader = new SimpleHttp(this);
121
122 connect( downloader, SIGNAL(downloadFailed(QString)),
123 this, SLOT(showError(QString)) );
124 connect( downloader, SIGNAL(downloadFinished(QByteArray)),
125 this, SLOT(downloadFinished()) );
126 connect( downloader, SIGNAL(downloadFinished(QByteArray)),
127 this, SLOT(parseInfo(QByteArray)) );
128 connect( downloader, SIGNAL(stateChanged(int)),
129 this, SLOT(updateRefreshButton()) );
130
131 connect( downloader, SIGNAL(connecting(QString)),
132 this, SLOT(connecting(QString)) );
133 connect( downloader, SIGNAL(dataReadProgress(int, int)),
134 this, SLOT(updateDataReadProgress(int, int)) );
135 */
136
137 osclient = new OSClient();
138 connect( osclient, SIGNAL(searchFinished()), this, SLOT(downloadFinished()) );
139 connect( osclient, SIGNAL(searchFinished()), this, SLOT(parseInfo()) );
140 connect( osclient, SIGNAL(loginFailed()), this, SLOT(showLoginFailed()) );
141 connect( osclient, SIGNAL(searchFailed()), this, SLOT(showSearchFailed()) );
142 connect( osclient, SIGNAL(errorFound(int, const QString &)), this, SLOT(showErrorOS(int, const QString &)) );
143
144#ifdef DOWNLOAD_SUBS
145 include_lang_on_filename = true;
146
147 file_downloader = new FileDownloader(this);
148 file_downloader->setModal(false);
149 connect( file_downloader, SIGNAL(downloadFailed(QString)),
150 this, SLOT(showError(QString)), Qt::QueuedConnection );
151 connect( file_downloader, SIGNAL(downloadFinished(const QByteArray &)),
152 this, SLOT(archiveDownloaded(const QByteArray &)), Qt::QueuedConnection );
153 connect( this, SIGNAL(subtitleDownloaded(const QString &)),
154 this, SLOT(fixSubtitles(const QString &)) );
155#endif
156
157 // Actions
158 downloadAct = new QAction(this);
159 downloadAct->setEnabled(false);
160 connect( downloadAct, SIGNAL(triggered()), this, SLOT(download()) );
161
162 copyLinkAct = new QAction(this);
163 copyLinkAct->setEnabled(false);
164 connect( copyLinkAct, SIGNAL(triggered()), this, SLOT(copyLink()) );
165
166 context_menu = new QMenu(this);
167 context_menu->addAction(downloadAct);
168 context_menu->addAction(copyLinkAct);
169
170 retranslateStrings();
171
172 language_filter->setCurrentIndex(0);
173
174 // Opensubtitles server
175 /* os_server = "http://www.opensubtitles.org"; */
176 os_server = "http://api.opensubtitles.org/xml-rpc";
177 osclient->setServer(os_server);
178
179 // Proxy
180 use_proxy = false;
181 proxy_type = QNetworkProxy::HttpProxy;
182 proxy_host = "";
183 proxy_port = 0;
184 proxy_username = "";
185 proxy_password = "";
186
187 setupProxy();
188}
189
190FindSubtitlesWindow::~FindSubtitlesWindow() {
191 if (set) saveSettings();
192}
193
194void FindSubtitlesWindow::setSettings(QSettings * settings) {
195 set = settings;
196 loadSettings();
197 setupProxy();
198}
199
200void FindSubtitlesWindow::setProxy(QNetworkProxy proxy) {
201 /*
202 downloader->abort();
203 downloader->setProxy(proxy);
204 */
205 osclient->setProxy(proxy);
206
207#ifdef DOWNLOAD_SUBS
208 file_downloader->setProxy(proxy);
209#endif
210
211 qDebug("FindSubtitlesWindow::setProxy: host: '%s' port: %d type: %d",
212 proxy.hostName().toUtf8().constData(), proxy.port(), proxy.type());
213}
214
215void FindSubtitlesWindow::retranslateStrings() {
216 retranslateUi(this);
217
218 QStringList labels;
219 labels << tr("Language") << tr("Name") << tr("Format")
220 << tr("Files") << tr("Date") << tr("Uploaded by");
221
222 table->setHorizontalHeaderLabels( labels );
223
224 // Language combobox
225 //int language_index = language_filter->currentIndex();
226 QString current_language = language_filter->itemData(language_filter->currentIndex()).toString();
227 language_filter->clear();
228
229 QMap<QString,QString> l1 = Languages::most_used_list();
230 QMapIterator<QString, QString> i1(l1);
231 while (i1.hasNext()) {
232 i1.next();
233 language_filter->addItem( i1.value() + " (" + i1.key() + ")", i1.key() );
234 }
235 language_filter->addItem( tr("Portuguese - Brasil") + " (pb)", "pb");
236 language_filter->model()->sort(0);
237 #if QT_VERSION >= 0x040400
238 language_filter->insertSeparator(language_filter->count());
239 #endif
240
241 QMap<QString,QString> l2 = Languages::list();
242 QMapIterator<QString, QString> i2(l2);
243 while (i2.hasNext()) {
244 i2.next();
245 if (language_filter->findData(i2.key()) == -1) {
246 language_filter->addItem( i2.value() + " (" + i2.key() + ")", i2.key() );
247 }
248 }
249 //language_filter->model()->sort(0);
250 language_filter->insertItem( 0, tr("All"), "*" );
251 #if QT_VERSION >= 0x040400
252 language_filter->insertSeparator(1);
253 #endif
254 //language_filter->setCurrentIndex(language_index);
255 language_filter->setCurrentIndex(language_filter->findData(current_language));
256
257#if QT_VERSION < 0x040300
258 QPushButton * close_button = buttonBox->button(QDialogButtonBox::Close);
259 close_button->setText( tr("Close") );
260#endif
261
262 // Actions
263 downloadAct->setText( tr("&Download") );
264 copyLinkAct->setText( tr("&Copy link to clipboard") );
265
266 // Icons
267#ifndef NO_SMPLAYER_SUPPORT
268 download_button->setIcon( Images::icon("download") );
269 configure_button->setIcon( Images::icon("prefs") );
270 refresh_button->setIcon( Images::icon("refresh") );
271
272 downloadAct->setIcon( Images::icon("download") );
273 copyLinkAct->setIcon( Images::icon("copy") );
274#endif
275}
276
277void FindSubtitlesWindow::setMovie(QString filename) {
278 qDebug("FindSubtitlesWindow::setMovie: '%s'", filename.toLatin1().constData());
279
280 if (filename == last_file) {
281 return;
282 }
283
284 file_chooser->setText(filename);
285 table->setRowCount(0);
286
287 QString hash = FileHash::calculateHash(filename);
288 if (hash.isEmpty()) {
289 qWarning("FindSubtitlesWindow::setMovie: hash invalid. Doing nothing.");
290 } else {
291 qint64 file_size = QFileInfo(filename).size();
292 osclient->search(hash, file_size);
293 last_file = filename;
294 }
295}
296
297void FindSubtitlesWindow::refresh() {
298 last_file = "";
299 setMovie(file_chooser->text());
300}
301
302void FindSubtitlesWindow::updateRefreshButton() {
303 qDebug("FindSubtitlesWindow::updateRefreshButton:");
304 refresh_button->setEnabled(true);
305}
306
307void FindSubtitlesWindow::currentItemChanged(const QModelIndex & current, const QModelIndex & /*previous*/) {
308 qDebug("FindSubtitlesWindow::currentItemChanged: row: %d, col: %d", current.row(), current.column());
309 download_button->setEnabled(current.isValid());
310 downloadAct->setEnabled(current.isValid());
311 copyLinkAct->setEnabled(current.isValid());
312}
313
314void FindSubtitlesWindow::applyFilter(const QString & filter) {
315 proxy_model->setFilterWildcard(filter);
316}
317
318void FindSubtitlesWindow::applyCurrentFilter() {
319 //proxy_model->setFilterWildcard(language_filter->currentText());
320 QString filter = language_filter->itemData( language_filter->currentIndex() ).toString();
321 applyFilter(filter);
322}
323
324void FindSubtitlesWindow::setLanguage(const QString & lang) {
325 int idx = language_filter->findData(lang);
326 if (idx < 0) idx = 0;
327 language_filter->setCurrentIndex(idx);
328}
329
330QString FindSubtitlesWindow::language() {
331 int idx = language_filter->currentIndex();
332 return language_filter->itemData(idx).toString();
333}
334
335void FindSubtitlesWindow::showError(QString error) {
336 status->setText( tr("Download failed") );
337
338 QMessageBox::information(this, tr("Error"),
339 tr("Download failed: %1.")
340 .arg(error));
341}
342
343void FindSubtitlesWindow::connecting(QString host) {
344 status->setText( tr("Connecting to %1...").arg(host) );
345}
346
347void FindSubtitlesWindow::showLoginFailed() {
348 status->setText( tr("Login to opensubtitles.org has failed") );
349}
350
351void FindSubtitlesWindow::showSearchFailed() {
352 status->setText( tr("Search has failed") );
353}
354
355void FindSubtitlesWindow::showErrorOS(int, const QString & error) {
356 status->setText(error);
357}
358
359void FindSubtitlesWindow::updateDataReadProgress(int done, int total) {
360 qDebug("FindSubtitlesWindow::updateDataReadProgress: %d, %d", done, total);
361
362 status->setText( tr("Downloading...") );
363
364 if (!progress->isVisible()) progress->show();
365 progress->setMaximum(total);
366 progress->setValue(done);
367}
368
369void FindSubtitlesWindow::downloadFinished() {
370 status->setText( tr("Done.") );
371 progress->setMaximum(1);
372 progress->setValue(0);
373 progress->hide();
374}
375
376void FindSubtitlesWindow::parseInfo() {
377 bool ok = true;
378
379 table->setRowCount(0);
380
381 QMap <QString,QString> language_list = Languages::list();
382
383 if (ok) {
384 QList<OSSubtitle> l = osclient->subtitleList();
385 for (int n=0; n < l.count(); n++) {
386
387 QString title_name = l[n].movie;
388 if (!l[n].releasename.isEmpty()) {
389 title_name += " - " + l[n].releasename;
390 }
391
392 QStandardItem * i_name = new QStandardItem(title_name);
393 i_name->setData( l[n].link );
394 #if QT_VERSION < 0x040400
395 i_name->setToolTip( l[n].link );
396 #endif
397
398 QStandardItem * i_lang = new QStandardItem(l[n].language);
399 i_lang->setData(l[n].iso639, Qt::UserRole);
400 #if QT_VERSION < 0x040400
401 i_lang->setToolTip(l[n].iso639);
402 #endif
403 if (language_list.contains(l[n].iso639)) {
404 i_lang->setText( language_list[ l[n].iso639 ] );
405 }
406
407 table->setItem(n, COL_LANG, i_lang);
408 table->setItem(n, COL_NAME, i_name);
409 table->setItem(n, COL_FORMAT, new QStandardItem(l[n].format));
410 table->setItem(n, COL_FILES, new QStandardItem(l[n].files));
411 table->setItem(n, COL_DATE, new QStandardItem(l[n].date));
412 table->setItem(n, COL_USER, new QStandardItem(l[n].user));
413
414 }
415 status->setText( tr("%1 files available").arg(l.count()) );
416 applyCurrentFilter();
417
418 qDebug("sort column: %d", view->header()->sortIndicatorSection());
419 qDebug("sort indicator: %d", view->header()->sortIndicatorOrder());
420
421 table->sort( view->header()->sortIndicatorSection(),
422 view->header()->sortIndicatorOrder() );
423 } else {
424 status->setText( tr("Failed to parse the received data.") );
425 }
426
427 view->resizeColumnToContents(COL_NAME);
428}
429
430void FindSubtitlesWindow::itemActivated(const QModelIndex & index ) {
431 qDebug("FindSubtitlesWindow::itemActivated: row: %d, col %d", proxy_model->mapToSource(index).row(), proxy_model->mapToSource(index).column());
432
433 QString download_link = table->item(proxy_model->mapToSource(index).row(), COL_NAME)->data().toString();
434
435 qDebug("FindSubtitlesWindow::itemActivated: download link: '%s'", download_link.toLatin1().constData());
436
437#ifdef DOWNLOAD_SUBS
438 file_downloader->download( QUrl(download_link) );
439 file_downloader->show();
440#else
441 QDesktopServices::openUrl( QUrl(download_link) );
442#endif
443}
444
445void FindSubtitlesWindow::download() {
446 qDebug("FindSubtitlesWindow::download");
447 if (view->currentIndex().isValid()) {
448 itemActivated(view->currentIndex());
449 }
450}
451
452void FindSubtitlesWindow::copyLink() {
453 qDebug("FindSubtitlesWindow::copyLink");
454 if (view->currentIndex().isValid()) {
455 const QModelIndex & index = view->currentIndex();
456 QString download_link = table->item(proxy_model->mapToSource(index).row(), COL_NAME)->data().toString();
457 qDebug("FindSubtitlesWindow::copyLink: link: '%s'", download_link.toLatin1().constData());
458 qApp->clipboard()->setText(download_link);
459 }
460}
461
462void FindSubtitlesWindow::showContextMenu(const QPoint & pos) {
463 qDebug("FindSubtitlesWindow::showContextMenu");
464
465 context_menu->move( view->viewport()->mapToGlobal(pos) );
466 context_menu->show();
467}
468
469// Language change stuff
470void FindSubtitlesWindow::changeEvent(QEvent *e) {
471 if (e->type() == QEvent::LanguageChange) {
472 retranslateStrings();
473 } else {
474 QWidget::changeEvent(e);
475 }
476}
477
478#ifdef DOWNLOAD_SUBS
479
480#ifndef USE_QUAZIP
481void FindSubtitlesWindow::archiveDownloaded(const QByteArray & buffer) {
482 qDebug("FindSubtitlesWindow::archiveDownloaded");
483 QByteArray uncompress_data = gUncompress(buffer);
484 //qDebug("uncompress_data: %s", uncompress_data.constData());
485
486 if (uncompress_data.isEmpty()) {
487 status->setText(tr("Download failed"));
488 return;
489 }
490
491 QString lang = "unknown";
492 QString extension = "unknown";
493 if (view->currentIndex().isValid()) {
494 const QModelIndex & index = view->currentIndex();
495 lang = table->item(proxy_model->mapToSource(index).row(), COL_LANG)->data(Qt::UserRole).toString();
496 extension = table->item(proxy_model->mapToSource(index).row(), COL_FORMAT)->text();
497 }
498
499 QFileInfo fi(file_chooser->text());
500 QString output_name = fi.completeBaseName();
501 if (include_lang_on_filename) output_name += "_"+ lang;
502 output_name += "." + extension;
503
504 QString output_file = fi.absolutePath() + "/" + output_name;
505 qDebug("FindSubtitlesWindow::archiveDownloaded: save subtitle as '%s'", output_file.toUtf8().constData());
506
507 QFile file(output_file);
508 file.open(QIODevice::WriteOnly);
509 bool error = (file.write(uncompress_data) == -1);
510 file.close();
511
512 if (error) {
513 qWarning("FindSubtitlesWindow::archiveDownloaded: can't write subtitle file");
514 QMessageBox::warning(this, tr("Error saving file"),
515 tr("It wasn't possible to save the downloaded\n"
516 "file in folder %1\n"
517 "Please check the permissions of that folder.").arg(fi.absolutePath()));
518 } else {
519 emit subtitleDownloaded( output_file );
520 }
521}
522
523QByteArray FindSubtitlesWindow::gUncompress(const QByteArray &data)
524{
525 if (data.size() <= 4) {
526 qWarning("gUncompress: Input data is truncated");
527 return QByteArray();
528 }
529
530 QByteArray result;
531
532 int ret;
533 z_stream strm;
534 static const int CHUNK_SIZE = 1024;
535 char out[CHUNK_SIZE];
536
537 /* allocate inflate state */
538 strm.zalloc = Z_NULL;
539 strm.zfree = Z_NULL;
540 strm.opaque = Z_NULL;
541 strm.avail_in = data.size();
542 strm.next_in = (Bytef*)(data.data());
543
544 ret = inflateInit2(&strm, 15 + 32); // gzip decoding
545 if (ret != Z_OK)
546 return QByteArray();
547
548 // run inflate()
549 do {
550 strm.avail_out = CHUNK_SIZE;
551 strm.next_out = (Bytef*)(out);
552
553 ret = inflate(&strm, Z_NO_FLUSH);
554 Q_ASSERT(ret != Z_STREAM_ERROR); // state not clobbered
555
556 switch (ret) {
557 case Z_NEED_DICT:
558 ret = Z_DATA_ERROR; // and fall through
559 case Z_DATA_ERROR:
560 case Z_MEM_ERROR:
561 (void)inflateEnd(&strm);
562 return QByteArray();
563 }
564
565 result.append(out, CHUNK_SIZE - strm.avail_out);
566 } while (strm.avail_out == 0);
567
568 // clean up and return
569 inflateEnd(&strm);
570 return result;
571}
572
573#else
574
575void FindSubtitlesWindow::archiveDownloaded(const QByteArray & buffer) {
576 qDebug("FindSubtitlesWindow::archiveDownloaded");
577
578 QString temp_dir = QDir::tempPath();
579 if (!temp_dir.endsWith("/")) temp_dir += "/";
580
581 QTemporaryFile file(temp_dir + "archive_XXXXXX.zip");
582 file.setAutoRemove(false);
583
584 qDebug("FindSubtitlesWindow::archiveDownloaded: a temporary file will be saved in folder '%s'", temp_dir.toUtf8().constData());
585
586 if (file.open()) {
587 QString filename = file.fileName();
588 file.write( buffer );
589 file.close();
590
591 qDebug("FindSubtitlesWindow::archiveDownloaded: file saved as: %s", filename.toUtf8().constData());
592
593 /*
594 QMessageBox::information(this, tr("Downloaded"), tr("File saved as %1").arg(filename));
595 return;
596 */
597
598 status->setText(tr("Temporary file %1").arg(filename));
599
600 QString lang = "unknown";
601 QString extension = "unknown";
602 if (view->currentIndex().isValid()) {
603 const QModelIndex & index = view->currentIndex();
604 lang = table->item(proxy_model->mapToSource(index).row(), COL_LANG)->data(Qt::UserRole).toString();
605 extension = table->item(proxy_model->mapToSource(index).row(), COL_FORMAT)->text();
606 }
607
608 QFileInfo fi(file_chooser->text());
609 QString output_name = fi.completeBaseName();
610 if (include_lang_on_filename) output_name += "_"+ lang;
611 output_name += "." + extension;
612
613 if (!uncompressZip(filename, fi.absolutePath(), output_name)) {
614 status->setText(tr("Download failed"));
615 }
616 file.remove();
617 }
618 else {
619 qWarning("FindSubtitlesWindow::archiveDownloaded: can't write temporary file");
620 QMessageBox::warning(this, tr("Error saving file"),
621 tr("It wasn't possible to save the downloaded\n"
622 "file in folder %1\n"
623 "Please check the permissions of that folder.").arg(temp_dir));
624 }
625}
626
627
628bool FindSubtitlesWindow::uncompressZip(const QString & filename, const QString & output_path, const QString & preferred_output_name) {
629 qDebug("FindSubtitlesWindow::uncompressZip: zip file '%s', output_path '%s', save subtitle as '%s'",
630 filename.toUtf8().constData(), output_path.toUtf8().constData(),
631 preferred_output_name.toUtf8().constData());
632
633 QuaZip zip(filename);
634
635 if (!zip.open(QuaZip::mdUnzip)) {
636 qWarning("FindSubtitlesWindow::uncompressZip: open zip failed: %d", zip.getZipError());
637 return false;
638 }
639
640 zip.setFileNameCodec("IBM866");
641 qDebug("FindSubtitlesWindow::uncompressZip: %d entries", zip.getEntriesCount());
642 qDebug("FindSubtitlesWindow::uncompressZip: global comment: '%s'", zip.getComment().toUtf8().constData());
643
644 QStringList sub_files;
645 QuaZipFileInfo info;
646
647 for (bool more=zip.goToFirstFile(); more; more=zip.goToNextFile()) {
648 if (!zip.getCurrentFileInfo(&info)) {
649 qWarning("FindSubtitlesWindow::uncompressZip: getCurrentFileInfo(): %d\n", zip.getZipError());
650 return false;
651 }
652 qDebug("FindSubtitlesWindow::uncompressZip: file '%s'", info.name.toUtf8().constData());
653 if (QFileInfo(info.name).suffix() != "nfo") sub_files.append(info.name);
654 }
655
656 qDebug("FindSubtitlesWindow::uncompressZip: list of subtitle files:");
657 for (int n=0; n < sub_files.count(); n++) {
658 qDebug("FindSubtitlesWindow::uncompressZip: subtitle file %d '%s'", n, sub_files[n].toUtf8().constData());
659 }
660
661 if (sub_files.count() == 1) {
662 // If only one file, just extract it
663 QString output_name = output_path +"/"+ preferred_output_name;
664 if (extractFile(zip, sub_files[0], output_name )) {
665 status->setText(tr("Subtitle saved as %1").arg(preferred_output_name));
666 emit subtitleDownloaded(output_name);
667 } else {
668 return false;
669 }
670 } else {
671 // More than one file
672 SubChooserDialog d(this);
673
674 for (int n=0; n < sub_files.count(); n++) {
675 d.addFile(sub_files[n]);
676 }
677
678 if (d.exec() == QDialog::Rejected) return false;
679
680 QStringList files_to_extract = d.selectedFiles();
681 int extracted_count = 0;
682 for (int n=0; n < files_to_extract.count(); n++) {
683 QString file = files_to_extract[n];
684 bool ok = extractFile(zip, file, output_path +"/"+ file);
685 qDebug("FindSubtitlesWindow::uncompressZip: extracted %s ok: %d", file.toUtf8().constData(), ok);
686 if (ok) extracted_count++;
687 }
688 status->setText(tr("%n subtitle(s) extracted","", extracted_count));
689 if (extracted_count > 0) {
690 emit subtitleDownloaded( output_path +"/"+ files_to_extract[0] );
691 }
692 }
693
694 zip.close();
695 return true;
696}
697
698bool FindSubtitlesWindow::extractFile(QuaZip & zip, const QString & filename, const QString & output_name) {
699 qDebug("FindSubtitlesWindow::extractFile: '%s', save as '%s'", filename.toUtf8().constData(), output_name.toUtf8().constData());
700
701 if (QFile::exists(output_name)) {
702 if (QMessageBox::question(this, tr("Overwrite?"),
703 tr("The file %1 already exits, overwrite?").arg(output_name), QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
704 {
705 return false;
706 }
707 }
708
709 if (!zip.setCurrentFile(filename)) {
710 qDebug("FindSubtitlesWindow::extractFile: can't select file %s", filename.toUtf8().constData());
711 return false;
712 }
713
714 // Saving
715 char c;
716 QuaZipFile file(&zip);
717 QFile out(output_name);
718
719 if (!file.open(QIODevice::ReadOnly)) {
720 qWarning("FindSubtitlesWindow::extractFile: can't open file for reading: %d", file.getZipError());
721 return false;
722 }
723
724 if (out.open(QIODevice::WriteOnly)) {
725 // Slow like hell (on GNU/Linux at least), but it is not my fault.
726 // Not ZIP/UNZIP package's fault either.
727 // The slowest thing here is out.putChar(c).
728 while(file.getChar(&c)) out.putChar(c);
729 out.close();
730
731 file.close();
732 } else {
733 qWarning("FindSubtitlesWindow::extractFile: can't open %s for writing", output_name.toUtf8().constData());
734 return false;
735 }
736
737 return true;
738}
739#endif // USE_QUAZIP
740
741void FindSubtitlesWindow::fixSubtitles(const QString & filename) {
742 qDebug("FindSubtitlesWindow::fixSubtitles: %s", filename.toUtf8().constData());
743
744 QFileInfo fi(filename);
745 if (fi.suffix().toLower() == "sub") {
746 qDebug("FindSubtitlesWindow::fixSubtitles: fixing end of lines");
747 if (FixSubtitles::fix(filename) != FixSubtitles::NoError) {
748 status->setText( tr("Error fixing the subtitle lines") );
749 qDebug("FindSubtitlesWindow::fixSubtitles: error fixing the subtitles");
750 }
751 }
752}
753
754#endif // DOWNLOAD_SUBS
755
756void FindSubtitlesWindow::on_configure_button_clicked() {
757 qDebug("FindSubtitlesWindow::on_configure_button_clicked");
758
759 FindSubtitlesConfigDialog d(this);
760
761 d.setServer( os_server );
762 d.setUseProxy( use_proxy );
763 d.setProxyHostname( proxy_host );
764 d.setProxyPort( proxy_port );
765 d.setProxyUsername( proxy_username );
766 d.setProxyPassword( proxy_password );
767 d.setProxyType( proxy_type );
768
769 if (d.exec() == QDialog::Accepted) {
770 os_server = d.server();
771 use_proxy = d.useProxy();
772 proxy_host = d.proxyHostname();
773 proxy_port = d.proxyPort();
774 proxy_username = d.proxyUsername();
775 proxy_password = d.proxyPassword();
776 proxy_type = d.proxyType();
777
778 osclient->setServer(os_server);
779 setupProxy();
780 }
781}
782
783void FindSubtitlesWindow::setupProxy() {
784 QNetworkProxy proxy;
785
786 if ( (use_proxy) && (!proxy_host.isEmpty()) ) {
787 proxy.setType((QNetworkProxy::ProxyType) proxy_type);
788 proxy.setHostName(proxy_host);
789 proxy.setPort(proxy_port);
790 if ( (!proxy_username.isEmpty()) && (!proxy_password.isEmpty()) ) {
791 proxy.setUser(proxy_username);
792 proxy.setPassword(proxy_password);
793 }
794 qDebug("FindSubtitlesWindow::userProxy: using proxy: host: %s, port: %d, type: %d",
795 proxy_host.toUtf8().constData(), proxy_port, proxy_type);
796 } else {
797 // No proxy
798 proxy.setType(QNetworkProxy::NoProxy);
799 qDebug("FindSubtitlesDialog::userProxy: no proxy");
800 }
801
802 setProxy(proxy);
803}
804
805void FindSubtitlesWindow::saveSettings() {
806 qDebug("FindSubtitlesWindow::saveSettings");
807
808 set->beginGroup("findsubtitles");
809
810 set->setValue("xmlrpc_server", os_server);
811 set->setValue("language", language());
812#ifdef DOWNLOAD_SUBS
813 set->setValue("include_lang_on_filename", includeLangOnFilename());
814#endif
815 set->setValue("proxy/use_proxy", use_proxy);
816 set->setValue("proxy/type", proxy_type);
817 set->setValue("proxy/host", proxy_host);
818 set->setValue("proxy/port", proxy_port);
819 set->setValue("proxy/username", proxy_username);
820 set->setValue("proxy/password", proxy_password);
821
822 set->endGroup();
823}
824
825void FindSubtitlesWindow::loadSettings() {
826 qDebug("FindSubtitlesWindow::loadSettings");
827
828 set->beginGroup("findsubtitles");
829
830 os_server = set->value("xmlrpc_server", os_server).toString();
831 setLanguage( set->value("language", language()).toString() );
832#ifdef DOWNLOAD_SUBS
833 setIncludeLangOnFilename( set->value("include_lang_on_filename", includeLangOnFilename()).toBool() );
834#endif
835 use_proxy = set->value("proxy/use_proxy", use_proxy).toBool();
836 proxy_type = set->value("proxy/type", proxy_type).toInt();
837 proxy_host = set->value("proxy/host", proxy_host).toString();
838 proxy_port = set->value("proxy/port", proxy_port).toInt();
839 proxy_username = set->value("proxy/username", proxy_username).toString();
840 proxy_password = set->value("proxy/password", proxy_password).toString();
841
842 set->endGroup();
843}
844
845#include "moc_findsubtitleswindow.cpp"
846
Note: See TracBrowser for help on using the repository browser.