1
+ var OS = require ( 'os' ) ;
2
+ var MD5 = require ( 'md5' ) ;
3
+ var Path = require ( 'path' ) ;
4
+ var FS = require ( 'fs-extra' ) ;
5
+ var Fuse = require ( 'fuse-bindings' ) ;
6
+ var USBDetect = require ( 'usb-detection' ) ;
7
+ var spawnFile = require ( 'child_process' ) . spawn ;
8
+
9
+
10
+ var VOLUME_LABEL = 'Android Phone' ;
11
+ var VOLUME_ICON = Path . resolve ( __dirname , 'volicon.icns' ) ;
12
+ var ADB_PATH = Path . resolve ( __dirname , 'adb' ) ;
13
+ var MOUNT_PATH = getTmpDir ( ) ;
14
+
15
+
16
+ var MNT_OPTIONS = {
17
+
18
+ force : true ,
19
+
20
+ options : [
21
+ `volname=${ VOLUME_LABEL } ` ,
22
+ `volicon=${ VOLUME_ICON } ` ,
23
+ 'noappledouble' ,
24
+ 'kill_on_unmount' ,
25
+ 'allow_other' ,
26
+ 'rdonly' ,
27
+ 'local'
28
+ ] ,
29
+
30
+ } ;
31
+
32
+ function getTmpDir ( ) {
33
+ var result = [ new Date ( ) . getTime ( ) , Math . random ( ) ] ;
34
+ return Path . resolve ( OS . tmpdir ( ) , MD5 ( result . join ( '-' ) ) ) ;
35
+ }
36
+
37
+ function runAdb ( args , ret ) {
38
+ var stdout = '' ;
39
+ var proc = spawnFile ( ADB_PATH , args ) ;
40
+ proc . stdout . on ( 'data' , ( data ) => stdout += data ) ;
41
+ proc . on ( 'close' , ( ) => ret ( stdout ) ) ;
42
+ }
43
+
44
+ function doMount ( ret ) {
45
+ if ( ! ret ) ret = ( ( ) => 0 ) ;
46
+ runAdb ( [ 'shell' , '-nT' , 'ls' , '-lLa' , '/' ] , function ( result ) {
47
+ result = result . replace ( / \s + / g, '' ) ;
48
+ console . info ( result )
49
+ if ( result . length === 0 ) return ret ( true ) ;
50
+ FS . ensureDir ( MOUNT_PATH , function ( error ) {
51
+ Fuse . mount ( MOUNT_PATH , MNT_OPTIONS , ret ) ;
52
+ } ) ;
53
+ } ) ;
54
+ }
55
+
56
+ function doUnmount ( ret ) {
57
+ if ( ! ret ) ret = ( ( ) => 0 ) ;
58
+ Fuse . unmount ( MOUNT_PATH , function ( ) {
59
+ FS . remove ( MOUNT_PATH , ret ) ;
60
+ } ) ;
61
+ }
62
+
63
+ function checkAdbDevice ( ) {
64
+ USBDetect . find ( function ( error , devices ) {
65
+ if ( devices . some ( device => device . manufacturer . toLowerCase ( ) === 'xiaomi' ) )
66
+ doMount ( ( error ) => error && setTimeout ( checkAdbDevice , 1000 ) ) ;
67
+ else doUnmount ( ) ;
68
+ } ) ;
69
+ }
70
+
71
+ function doTerminate ( message ) {
72
+ if ( message ) console . info ( message ) ;
73
+ USBDetect . stopMonitoring ( ) ;
74
+ doUnmount ( ( ) => process . exit ( ) ) ;
75
+ }
76
+
77
+ process . on ( 'SIGINT' , doTerminate ) ;
78
+ process . on ( 'SIGTERM' , doTerminate ) ;
79
+ process . on ( 'SIGUSR1' , doTerminate ) ;
80
+ process . on ( 'SIGUSR2' , doTerminate ) ;
81
+ process . on ( 'uncaughtException' , doTerminate ) ;
82
+ USBDetect . on ( 'change' , checkAdbDevice ) ;
83
+ USBDetect . startMonitoring ( ) ;
84
+ checkAdbDevice ( ) ;
0 commit comments