Added library based archive extracting
[mdictionary] / src / plugins / xdxf / XdxfDictDownloader.cpp
index 2b62ff6..677be7f 100644 (file)
 #include "XdxfDictDownloadProgressDialog.h"
 #include <QDebug>
 
+#include <bzlib.h>
+#include <libtar.h>
+#include <stdio.h>
+#include <fcntl.h>
+
+typedef void BZFILE;
+
+
 
 XdxfDictDownloader::XdxfDictDownloader(QObject *parent) :
     QObject(parent) {
@@ -91,6 +99,7 @@ void XdxfDictDownloader::processFinished(int exitcode) {
         process->start(commands[currentCommand]);
     }
     else {
+        qDebug() << "EXTRACT" << extract("/tmp/" + _fileName);
         downloadComplete();
     }
 }
@@ -106,6 +115,7 @@ void XdxfDictDownloader::downloadComplete() {
     QFile dictFile("/tmp/mdict/" + dictDirName + "/dict.xdxf");
     dictFile.copy(QDir::homePath() + "/.mdictionary/" + dictDirName + ".xdxf");
     QFile::remove("/tmp/" + _fileName);
+    QFile::remove("/tmp/" + _fileName.replace(QRegExp(".bz2$"), ""));
 
     _downloadedFile = QDir::homePath() + "/.mdictionary/" + dictDirName + ".xdxf";
 
@@ -175,8 +185,55 @@ void XdxfDictDownloader::dictListReceived(QNetworkReply *reply) {
         // page and js scripts and thats all
         // Maybe calling wget is not pretty one but its working!
         commands.push_back("wget --quiet -P /tmp/ " + url);
-        commands.push_back(QString("tar -xjvf /tmp/") + _fileName + QString(" -C /tmp/mdict"));
+
+        //commands.push_back(QString("tar -xjvf /tmp/") + _fileName + QString(" -C /tmp/mdict"));
 
         process->start(commands[0]);
     }
 }
+
+bool XdxfDictDownloader::extract(QString file) {
+    // Extracting bz2
+    FILE * archive = fopen(file.toStdString().c_str(), "rb");
+    if (archive == 0)
+        return false;
+    int err;
+    BZFILE * afterbzFile = BZ2_bzReadOpen(&err, archive, 0, 0, 0, 0);
+    if(err != BZ_OK) {
+        BZ2_bzReadClose(&err, afterbzFile);
+        return false;
+    }
+
+    FILE * tarfile = fopen(file.replace(QRegExp(".bz2$"), "").
+            toStdString().c_str(), "w");
+
+    int bufflen = 100;
+    char buff[bufflen];
+    while(err == BZ_OK) {
+        int len = BZ2_bzRead(&err, afterbzFile, buff, bufflen);
+        if(fwrite(buff, 1, len, tarfile) != len)
+            return false;
+    }
+    BZ2_bzReadClose(&err, afterbzFile);
+    fclose(tarfile);
+    fclose(archive);
+
+    // Extracting tar
+    TAR *t;
+    char * tarfname = new char[file.replace(QRegExp(".bz2%"), "").size()+1];
+    strcpy(tarfname, file.replace(QRegExp(".bz2%"), "").toStdString().c_str());
+
+    err = tar_open(&t, tarfname, 0, O_RDONLY, 0, 0);
+    if(err == -1)
+        return false;
+
+    err = tar_extract_all(t, "/tmp/mdict/");
+    if(err == -1) {
+        return false;
+    }
+    tar_close(t);
+
+    return true;
+}
+
+