~fnux/pisk

ref: 42e646bb35ee40097b51aa4785a3d1058c8f759f pisk/disks.pl -rwxr-xr-x 9.5 KiB
42e646bb — Timothée Floure Refresh device list after (un)mounting action 3 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
#!/usr/bin/perl

=encoding utf8
=head1 NAME

disks.pl - Curses application allowing an unpriviledged user to manage disks and partitions

=head1 VERSION 

This documentation refers to disks.pl version 0.0.1.

=head1 USAGE

The application ignore any argument, just call it from a terminal:

  disks.pl

=head1 AUTHOR

Timothée Floure (<timothee.floure@fnux.ch>)

=cut

### Ignore some Perl::Critic rules:
## no critic (ProhibitAccessOfPrivateData)
## no critic (ProhibitHashBarewords)
## no critic (ProhibitNumberedNames)
## no critic (RequireExtendedFormatting)

use utf8;
use strict;
use warnings;
use feature "switch";

use Curses::UI;
use Net::DBus;

### Disks

sub index_block_devices_by_drive {
	my ($block_devices) = @_;

	my %drive_tree = ();
	@{ $block_devices } = sort {
		get_block_device_path($a) cmp get_block_device_path($b)
	} @{ $block_devices };
	foreach my $block_device (@{ $block_devices }) {
		push @{ $drive_tree{$block_device->Drive} }, $block_device }

	return \%drive_tree;
}

sub refresh_listbox_content {
	my ($udisks2, $values, $labels) = @_;

	# Empty the 'values' array first to remove old entries
	splice(@{ $values });
	# FIXME: do the same with the labels

	# Fetch and process the list of block devices
	my $block_devices = get_block_device_list($udisks2);
	my $drive_tree = index_block_devices_by_drive($block_devices);

	foreach my $drive_path (sort keys %{ $drive_tree }) {
		# FIXME: find an elegant way to check the drive exists
		if ($drive_path ne '/') {
			my $drive = $udisks2->get_object($drive_path);
			my $label = sprintf("%-30s\n", $drive->Vendor . $drive->Model);

			push @{ $values }, $drive;
			$labels->{$drive} = $label;
		} else {
			push @{ $values }, $drive_path;
			$labels->{$drive_path} = 'Unknown drive';
		}

		foreach my $block_device (@{ $drive_tree->{$drive_path} }) {
			my $label = sprintf('  %-15s', get_block_device_path($block_device));

			given ($block_device) {
				when (implements_udisks2_interface($_, 'Filesystem')) {
					$label .= $block_device->IdType;

					if (list_filesystem_mountpoints($block_device)) {
						$label .= ' - ' . list_filesystem_mountpoints($block_device);
					}

					my $filesystem = $block_device->as_interface(
						'org.freedesktop.UDisks2.Filesystem'
					);
					my $humanized_size = $filesystem->Size / (2 ** 30);
					$label .= ' - ' . $humanized_size . ' GB';
				}
				when (implements_udisks2_interface($_, 'Swapspace')) {
					$label .= 'Swap space';
				}
				when (implements_udisks2_interface($_, 'Encrypted')) {
					$label .= 'Encrypted';
				}
				when (implements_udisks2_interface($_, 'Partition')) {
					my $partition = $block_device->as_interface(
						'org.freedesktop.UDisks2.Partition'
					);
					my $humanized_size = $partition->Size / (2 ** 30);
					$label .= ' - ' . $humanized_size . ' GB';
				}
			}

			push @{ $values }, $block_device;
			$labels->{$block_device} = $label;
		}
	}

	return;
}

sub get_block_device_list {
	my ($udisks2) = @_;

	# Get and list knwown block devices
	my $manager = $udisks2->get_object(
		'/org/freedesktop/UDisks2/Manager',
		'org.freedesktop.UDisks2.Manager'
	);
	my $paths = $manager->GetBlockDevices({'auth.no_user_interaction' => 0});

	my @block_devices = ();
	foreach my $path (@{ $paths }) {
		my $block_device = $udisks2->get_object($path);
		dbus_introspect($block_device);
		push @block_devices, $block_device;
	}

	return \@block_devices;
}

sub implements_udisks2_interface {
	my ($dbus_object, $name) = @_;

	if (ref $dbus_object ne 'Net::DBus::RemoteObject') {
		return 0;
	}

	my $interface = 'org.freedesktop.UDisks2.' . $name;
	return $dbus_object->{introspector}->has_interface($interface);
}

sub get_block_device_path {
	my ($block_device) = @_;

	my $char_codes = $block_device->Device;
	my @chars = map { chr($_) } @{ $char_codes };

	# The last item of the array returned by the Device methods is the NULL
	# character
	pop @chars;

	return join('', @chars);
}

sub list_filesystem_mountpoints {
	my ($filesystem) = @_;
	unless (implements_udisks2_interface($filesystem, 'Filesystem')) {
		return;
	}

	my $raw_list = $filesystem->MountPoints;
	my @mountpoints = ();
	foreach my $raw_chars (@{ $raw_list }) {
		my @chars = map { chr($_) } @{ $raw_chars };

		# The last item of the array returned by the Device methods is the NULL
		# character
		pop @chars;

		push @mountpoints, join('', @chars);
	}

	return join(',', @mountpoints);
}

sub dbus_introspect {
	my ($dbus_object) = @_;

	# FIXME: this method is supposed to be private
	return $dbus_object->_net_dbus_introspector();
}

sub mount_filesystem {
	my ($filesystem) = @_;
	my $mountpoint = $filesystem->Mount({});

	return $mountpoint;
}

sub unmount_filesystem {
	my ($filesystem) = @_;
	$filesystem->Unmount({});

	return;
}

### UI

sub define_curses_windows {
	my ($cui) = @_;

	my $main = $cui->add(
		'main', 'Window',
		-title        => 'Disks.pl',
		-border       => 1,
		-titlereverse => 0,
		-padtop       => 0,
		-padbottom    => 3,
		-ipad         => 1,
	);

	my $footer = $cui->add(
		'foot', 'Window',
		-border        => 1,
		-y             => -1,
		-height        => 3,
	);

	my $windows = { main => $main, footer => $footer };
	return $windows;
}

sub define_curses_listbox {
	my ($cui, $window, $udisks2, $values, $labels) = @_;

	my $listbox = $window->add(
		undef, 'Listbox',
		-values => $values,
		-labels => $labels,
		-htmltext => 1,
		-y => 6
	);

	$listbox->focus();
	$listbox->onChange(
		sub {
			handle_listbox_event($cui, $udisks2, $listbox, $values, $labels);
		}
	);

	return $listbox;
}

sub populate_curses_windows {
	my ($win) = @_;

	$win->{main}->add(undef, 'Label',
		-text => 'Manage disks, partitions and filesystems as an unpriviledged' .
		' user.'
	);

	my $list_header = 'Available devices';
	$win->{main}->add(undef, 'Label',
		-text => $list_header,
		-y => 4,
		-bold =>1
	);

	$win->{footer}->add(undef, 'Label',
		-text => 'q: quit   r: refresh    h/j/k/l or arrows: move   enter: select'
	);

	return;
}

sub define_curses_bindings {
	my ($udisks2, $cui, $listbox, $listbox_values, $listbox_labels) = @_;

	$cui->set_binding(
		sub { $cui->mainloopExit() }, "q"
	);
	$cui->set_binding(
		sub {
			refresh_listbox_content($udisks2, $listbox_values, $listbox_labels);
			$listbox->draw();
		},
		"r"
	);

	return;
}

### Main logic

sub handle_listbox_event {
	my ($cui, $udisks2, $listbox, $listbox_values, $listbox_labels) = @_;

	my $device = $listbox->get();
	my $dialog_title = q{}; #Violates ProhibitCallsToUndeclaredSubs
	my $dialog_content = q{}; #Violates ProhibitCallsToUndeclaredSubs
	my @dialog_buttons = ();

	if (implements_udisks2_interface($device, 'Block')) {
		$dialog_title = get_block_device_path($device);
		$dialog_content .= 'Block device ID: ' . $device->Id . "\n";

		if ($device->IdUsage) {
			$dialog_content .= 'Reported usage: ' . $device->IdUsage . "\n";
		}

		if (implements_udisks2_interface($device, 'Partition')) {
			my $partition = $device->as_interface('org.freedesktop.UDisks2.Partition');
			my $humanized_size = $partition->Size / (2 ** 30);
			$dialog_content .= 'Partition size: ' . $humanized_size . ' GB' . "\n";
		}

		if (implements_udisks2_interface($device, 'PartitionTable')) {
			$dialog_content .= 'Partition Table: ' . $device->Type . "\n";
		}

		if (implements_udisks2_interface($device, 'Filesystem')) {
			$dialog_content .= 'Mountable filsystem: ' . $device->IdType . "\n";
			$dialog_content .= 'Mountpoints: ' . list_filesystem_mountpoints($device) . "\n";

			if (list_filesystem_mountpoints($device)) {
				push @dialog_buttons,{
					-label => '< Unmount >',
					-value => 'unmount',
					-shortcut => 1
				}
			}
			else {
				push @dialog_buttons,{
					-label => '< Mount >',
					-value => 'mount',
					-shortcut => 1
				}
			}
		}

		if (implements_udisks2_interface($device, 'Encrypted')) {
			$dialog_content .= 'Encrypted block device: ' . $device->IdType . "\n";
		}

	}
	elsif (implements_udisks2_interface($device, 'Drive')) {
		$dialog_title = $device->Vendor . ' ' . $device->Model;
		$dialog_content .= 'Drive ID: ' . $device->Id . "\n";
		$dialog_content .= 'Drive Size: ' . $device->Size . "\n";
	} else {
		$dialog_title = 'Error.';
		$dialog_content .= 'Could not find a valid object.';
	}

	# Append 'cancel' button to every dialog
	push @dialog_buttons, 'cancel';

	my $action = $cui->dialog(
		-title => $dialog_title,
		-message => $dialog_content,
		-buttons => \@dialog_buttons,
	);

	# Handle actions
	given ($action) {
		when (/^mount$/) {
			mount_filesystem($device)
			refresh_listbox_content($udisks2, $listbox_values, $listbox_labels);
		}
		when (/^unmount$/) {
			unmount_filesystem($device)
			refresh_listbox_content($udisks2, $listbox_values, $listbox_labels);
		}
	}

	# Refresh focus and selection
	$listbox->focus();
	$listbox->clear_selection();

	return;
}

sub main {
	my ($cui, $udisks2) = @_;

	# Define list content
	my $listbox_values = [];
	my $listbox_labels = {};
	refresh_listbox_content($udisks2, $listbox_values, $listbox_labels);

	# Define Curses UI components
	my $windows = define_curses_windows($cui);
	my $listbox = define_curses_listbox($cui, $windows->{main}, $udisks2, $listbox_values, $listbox_labels);
	populate_curses_windows($windows);
	define_curses_bindings($udisks2, $cui, $listbox, $listbox_values, $listbox_labels);

	$cui->mainloop();

	return;
}

### Initialization

sub init_script {
	my $cui = Curses::UI->new(-debug => 0);

	# FIXME: check for errors
	my $bus = Net::DBus->system;
	my $udisks2 = $bus->get_service('org.freedesktop.UDisks2');

	return ($cui, $udisks2);
}

my ($cui, $udisks2) = init_script();
main($cui, $udisks2);