Skip to content

Commit 4536518

Browse files
committed
[platform] support download node binary from github
- add downloader class to show progress - support download node binary - click reset -> download node binary and copy to target
1 parent 6ef7ec7 commit 4536518

File tree

5 files changed

+190
-26
lines changed

5 files changed

+190
-26
lines changed
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
package seven.drawalive.nodebase;
2+
3+
import android.app.ProgressDialog;
4+
import android.content.Context;
5+
import android.content.DialogInterface;
6+
import android.os.AsyncTask;
7+
8+
import java.io.FileOutputStream;
9+
import java.io.IOException;
10+
import java.io.InputStream;
11+
import java.io.OutputStream;
12+
import java.net.MalformedURLException;
13+
import java.net.URL;
14+
import java.net.URLConnection;
15+
16+
public class Downloader {
17+
public static class DownloadTask extends AsyncTask<String, String, String> {
18+
public DownloadTask(Downloader downloader) {
19+
this.downloader = downloader;
20+
}
21+
22+
@Override
23+
protected String doInBackground(String... strings) {
24+
String url = strings[0];
25+
String outfile = strings[1];
26+
InputStream download_stream = null;
27+
OutputStream output_stream = null;
28+
publishProgress("Starting ...");
29+
try {
30+
URL urlobj = new URL(url);
31+
URLConnection conn = urlobj.openConnection();
32+
int file_len = conn.getContentLength();
33+
byte[] buf = new byte[4096];
34+
int read_len = 0, total_read_len = 0;
35+
download_stream = conn.getInputStream();
36+
Storage.unlink(outfile);
37+
Storage.touch(outfile);
38+
output_stream = new FileOutputStream(outfile);
39+
while ((read_len = download_stream.read(buf)) >= 0) {
40+
if (isCancelled()) {
41+
throw new IOException();
42+
}
43+
total_read_len += read_len;
44+
output_stream.write(buf, 0, read_len);
45+
String read_size = Storage.readableSize(total_read_len);
46+
if (file_len > 0) {
47+
read_size += " / " + Storage.readableSize(file_len);
48+
}
49+
publishProgress(read_size);
50+
}
51+
output_stream.close();
52+
download_stream.close();
53+
publishProgress("Finishing ...");
54+
} catch (MalformedURLException e) {
55+
return null;
56+
} catch (IOException e) {
57+
return null;
58+
} finally {
59+
if (download_stream != null) try {download_stream.close();} catch (IOException e) {}
60+
if (output_stream != null) try {output_stream.close();} catch (IOException e) {}
61+
}
62+
return outfile;
63+
}
64+
65+
@Override
66+
protected void onPreExecute() {
67+
super.onPreExecute();
68+
downloader.progress.setMax(100);
69+
downloader.progress.setProgress(0);
70+
downloader.progress.show();
71+
}
72+
73+
@Override
74+
protected void onProgressUpdate(String... data) {
75+
downloader.progress.setMessage(data[0]);
76+
}
77+
78+
@Override
79+
protected void onPostExecute(String result) {
80+
if (downloader.callback != null) {
81+
downloader.callback.run();
82+
}
83+
downloader.progress.dismiss();
84+
if (result != null) {
85+
External.showToast(downloader.context,"Download successful");
86+
} else {
87+
External.showToast(downloader.context,"Download failed");
88+
}
89+
}
90+
91+
private Downloader downloader;
92+
}
93+
94+
public Downloader(Context context, Runnable callback) {
95+
this.context = context;
96+
progress = new ProgressDialog(context);
97+
progress.setIndeterminate(true);
98+
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
99+
progress.setCancelable(true);
100+
this.callback = callback;
101+
}
102+
103+
public void act(String title, String url, String outfile) {
104+
final DownloadTask task = new DownloadTask(this);
105+
progress.setTitle(title);
106+
progress.setOnCancelListener(new DialogInterface.OnCancelListener() {
107+
@Override
108+
public void onCancel(DialogInterface dialog) {
109+
task.cancel(true);
110+
}
111+
});
112+
task.execute(url, outfile);
113+
}
114+
115+
private Context context;
116+
private Runnable callback;
117+
private ProgressDialog progress;
118+
}

app/app/src/main/java/seven/drawalive/nodebase/External.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import android.content.Context;
44
import android.content.Intent;
55
import android.net.Uri;
6+
import android.support.v7.app.AlertDialog;
7+
import android.widget.Toast;
68

79
import java.io.File;
810

@@ -33,4 +35,18 @@ public static void shareInformation(
3335
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3436
context.startActivity(Intent.createChooser(intent, title));
3537
}
38+
39+
public static void showMessage(Context context, String text, String title) {
40+
AlertDialog.Builder builder = new AlertDialog.Builder(context);
41+
builder.setMessage(text);
42+
if (title != null) builder.setTitle(title);
43+
builder.create().show();
44+
}
45+
public static void showMessage(Context context, String text) {
46+
showMessage(context, text, null);
47+
}
48+
49+
public static void showToast(Context context, String text) {
50+
Toast.makeText(context.getApplicationContext(), text, Toast.LENGTH_SHORT).show();
51+
}
3652
}

app/app/src/main/java/seven/drawalive/nodebase/NodeBase.java

Lines changed: 34 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package seven.drawalive.nodebase;
22

33
import android.content.Intent;
4-
import android.support.v7.app.AlertDialog;
54
import android.support.v7.app.AppCompatActivity;
65
import android.os.Bundle;
76
import android.text.Editable;
@@ -15,7 +14,6 @@
1514
import android.widget.LinearLayout;
1615
import android.widget.ScrollView;
1716
import android.widget.TextView;
18-
import android.widget.Toast;
1917

2018
import java.io.File;
2119
import java.util.ArrayList;
@@ -38,6 +36,9 @@ protected void onCreate(Bundle savedInstanceState) {
3836
Permission.request(this);
3937

4038
setContentView(view);
39+
if (!Storage.exists(config.nodeBin())) {
40+
resetNode();
41+
}
4142
}
4243

4344
@Override
@@ -58,7 +59,7 @@ public boolean onCreateOptionsMenu(Menu menu) {
5859
@Override
5960
public boolean onOptionsItemSelected(MenuItem item) {
6061
switch (item.getItemId()) {
61-
case 101:
62+
case 101: // Show Network Interfaces
6263
showNicIps();
6364
break;
6465
case 102: // Show NodeJS Version
@@ -67,10 +68,8 @@ public boolean onOptionsItemSelected(MenuItem item) {
6768
case 103: // Upgrade NodeJS
6869
copyBinNodeFromNodebaseWorkdir();
6970
break;
70-
case 199: // reset
71-
Log.i("UI:ActionButton", "Update node js binary ...");
72-
// copyBinNodeFromNodebaseWorkdir();
73-
refreshAppList();
71+
case 199: // Reset NodeJS
72+
resetNode();
7473
break;
7574
default:
7675
return super.onOptionsItemSelected(item);
@@ -101,7 +100,7 @@ protected LinearLayout prepareLayout() {
101100
subview = new LinearLayout(this);
102101
subview.setOrientation(LinearLayout.HORIZONTAL);
103102
_txtAppRootDir = new EditText(this);
104-
_txtAppRootDir.setText("/sdcard/.nodebase");
103+
_txtAppRootDir.setText(config.workDir());
105104
param = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
106105
_txtAppRootDir.setLayoutParams(param);
107106
subview.addView(_txtAppRootDir);
@@ -131,6 +130,10 @@ protected void prepareEvents() {
131130
public void onClick(View view) {
132131
Log.i("UI:Button", "Refresh app list ...");
133132
String appdir = _txtAppRootDir.getText().toString();
133+
if (appdir.compareTo(config.workDir()) != 0) {
134+
config.set(Configuration.KEYVAL_NODEBASE_DIR, appdir);
135+
config.save();
136+
}
134137
Storage.makeDirectory(config.workDir());
135138
refreshAppList();
136139
}
@@ -163,10 +166,7 @@ protected void refreshAppList() {
163166
File approot = new File(dirname);
164167
_panelAppList.removeAllViews();
165168
if (!approot.isDirectory()) {
166-
Toast.makeText(
167-
getApplicationContext(),
168-
String.format("\"%s\" is not a directory", dirname),
169-
Toast.LENGTH_SHORT).show();
169+
External.showToast(this, String.format("\"%s\" is not a directory", dirname));
170170
return;
171171
}
172172
try {
@@ -236,11 +236,11 @@ private void copyBinNodeFromNodebaseWorkdir() {
236236
String upgrade_node_filename = String.format("%s/.bin/node", dirname);
237237
File f = new File(upgrade_node_filename);
238238
if (!f.exists()) {
239-
AlertDialog.Builder builder = new AlertDialog.Builder(this);
240-
builder.setMessage(
241-
String.format("%s does not exists.", upgrade_node_filename)
242-
).setTitle("Upgrade Failed");
243-
builder.create().show();
239+
External.showMessage(
240+
this,
241+
String.format("%s does not exists.", upgrade_node_filename),
242+
"Upgrade Failed"
243+
);
244244
return;
245245
}
246246
String nodeBin = config.nodeBin();
@@ -261,9 +261,7 @@ private void showNodeVersion() {
261261
} else {
262262
text = String.format("NodeJS: %s", version);
263263
}
264-
AlertDialog.Builder builder = new AlertDialog.Builder(this);
265-
builder.setMessage(text).setTitle("Node Version");
266-
builder.create().show();
264+
External.showMessage(this, text, "Node Version");
267265
}
268266

269267
private void showNicIps() {
@@ -280,10 +278,22 @@ private void showNicIps() {
280278
}
281279
nic_list.append('\n');
282280
}
283-
CharSequence text = new String(nic_list);
284-
AlertDialog.Builder builder = new AlertDialog.Builder(this);
285-
builder.setMessage(text).setTitle("NetworkInterface(s)");
286-
builder.create().show();
281+
String text = new String(nic_list);
282+
External.showMessage(this, text, "NetworkInterface(s)");
283+
}
284+
285+
private void resetNode() {
286+
String workdir = config.workDir();
287+
String workdir_bin = String.format("%s/.bin", workdir);
288+
Storage.makeDirectory(workdir_bin);
289+
String upgrade_node_filename = String.format("%s/node", workdir_bin);
290+
Storage.unlink(upgrade_node_filename);
291+
new Downloader(this, new Runnable() {
292+
@Override
293+
public void run() {
294+
copyBinNodeFromNodebaseWorkdir();
295+
}
296+
}).act("Downlaod NodeJS", Configuration.NODE_URL, upgrade_node_filename);
287297
}
288298

289299
// state

app/app/src/main/java/seven/drawalive/nodebase/NodeService.java

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ public class NodeService extends Service {
1717
public static final HashMap<String, NodeMonitor> services = new HashMap<>();
1818
public static String AUTH_TOKEN = refreshAuthToken();
1919

20-
private enum STATE { READY, RUNNING, DEAD };
20+
private enum STATE { BORN, READY, RUNNING, DEAD };
2121

2222

2323
public static String refreshAuthToken() {
@@ -55,7 +55,7 @@ public interface NodeMonitorEvent {
5555

5656
public static class NodeMonitor extends Thread {
5757
public NodeMonitor(String service_name, String[] command) {
58-
state = STATE.READY;
58+
state = STATE.BORN;
5959
this.service_name = service_name;
6060
this.command = command;
6161
event = null;
@@ -127,6 +127,14 @@ public boolean isRunning() {
127127
return state == STATE.RUNNING;
128128
}
129129

130+
public boolean isReady() {
131+
return state == STATE.READY;
132+
}
133+
134+
public boolean isDead() {
135+
return state == STATE.DEAD;
136+
}
137+
130138
private STATE state;
131139
private String service_name;
132140
private Process node_process;

app/app/src/main/java/seven/drawalive/nodebase/Storage.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ public static boolean download(String url, String outfile) {
1919
try {
2020
URL urlobj = new URL(url);
2121
URLConnection conn = urlobj.openConnection();
22+
// int file_len = conn.getContentLength();
2223
byte[] buf = new byte[4096];
2324
int read_len = 0;
2425
download_stream = conn.getInputStream();
@@ -159,4 +160,15 @@ public static File[] listFiles(String path) {
159160
public static boolean exists(String infile) {
160161
return new File(infile).exists();
161162
}
163+
164+
private static final String[] READABLE_SIZE_UNIT = new String[] {"B", "KB", "MB", "GB", "TB"};
165+
public static String readableSize(int size) {
166+
int index = 0, n = READABLE_SIZE_UNIT.length - 1;
167+
double val = size;
168+
while (val > 1024 && index < n) {
169+
index ++;
170+
val /= 1024.0;
171+
}
172+
return String.format("%.2f %s", val, READABLE_SIZE_UNIT[index]);
173+
}
162174
}

0 commit comments

Comments
 (0)