2 * This file is part of WolneLektury-Mobile, licensed under GNU Affero GPLv3 or later.
3 * Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
6 package pl.org.nowoczesnapolska.wlmobi;
8 import org.json.JSONArray;
9 import org.json.JSONException;
11 import android.util.Log;
12 import android.content.res.AssetManager;
14 import com.phonegap.api.Plugin;
15 import com.phonegap.api.PluginResult;
18 import java.io.FileOutputStream;
19 import java.io.InputStream;
20 import java.io.IOException;
21 import pl.org.nowoczesnapolska.wlmobi.Downloader;
23 public class DBPut extends Plugin{
26 public PluginResult execute(String action, JSONArray args, String callbackId) {
27 if (action.equals("put")) {
29 return this.put(args.getString(0), args.getString(1), args.getString(2));
30 } catch (JSONException e) {
31 return new PluginResult(PluginResult.Status.ERROR, "Param errrors");
34 else if (action.equals("fetch")) {
36 return this.fetch(args.getString(0));
37 } catch (JSONException e) {
38 return new PluginResult(PluginResult.Status.ERROR, "Param errrors");
42 return new PluginResult(PluginResult.Status.INVALID_ACTION);
46 private PluginResult fetch(String url) {
47 String fileName = "0000000000000001.db";
48 String targetPath = "/data/data/" + this.ctx.getPackageName() + "/app_database/file__0/";
50 Log.d("DBPut", "database path: " + targetPath + " / " + fileName);
52 Downloader d = new Downloader();
53 return d.downloadUrl(url, targetPath, fileName, "true");
57 private PluginResult put(String assetPath, String targetPath, String overwrite) {
58 // this hard-coding is kinda creepy, should probably create the db and use getDatabasePath instead
59 String absoluteTargetPath = "/data/data/" + this.ctx.getPackageName() + "/app_database/" + targetPath;
60 int index = absoluteTargetPath.lastIndexOf('/');
61 String targetDir = absoluteTargetPath.substring(0, index);
64 File dir = new File(targetDir);
66 Log.d("DBPut", "directory " + targetDir + " created");
70 File fout = new File(absoluteTargetPath);
72 if(overwrite.equals("false") && fout.exists()) {
73 Log.d("DBPut", "File already exists");
74 return new PluginResult(PluginResult.Status.OK, "exist");
77 FileOutputStream fos = new FileOutputStream(fout);
79 AssetManager assetManager = this.ctx.getResources().getAssets();
80 InputStream is = assetManager.open(assetPath);
82 byte[] buffer = new byte[1024];
85 while ( (len1 = is.read(buffer)) > 0 ) {
86 fos.write(buffer,0, len1);
91 Log.d("DBPut", "Copied to " + absoluteTargetPath);
92 } catch (IOException e) {
93 Log.d("DBPut", "Error: " + e);
94 return new PluginResult(PluginResult.Status.ERROR, "Error: " + e);
96 return new PluginResult(PluginResult.Status.OK, absoluteTargetPath);