summaryrefslogtreecommitdiffstats
path: root/dozentenmodul/src/main/java/org/openslx/dozmod/thrift/ThriftActions.java
blob: fba3ed2a8796a59be8e3c8e6becfb10a239370d0 (plain) (blame)
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
package org.openslx.dozmod.thrift;

import java.awt.Frame;
import java.awt.Window;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.swing.JFileChooser;

import org.apache.log4j.Logger;
import org.apache.thrift.TException;
import org.openslx.bwlp.thrift.iface.ImageBaseWrite;
import org.openslx.bwlp.thrift.iface.ImageDetailsRead;
import org.openslx.bwlp.thrift.iface.ImagePermissions;
import org.openslx.bwlp.thrift.iface.ImageVersionDetails;
import org.openslx.bwlp.thrift.iface.ImageVersionWrite;
import org.openslx.bwlp.thrift.iface.LecturePermissions;
import org.openslx.bwlp.thrift.iface.LectureRead;
import org.openslx.bwlp.thrift.iface.LectureSummary;
import org.openslx.bwlp.thrift.iface.LectureWrite;
import org.openslx.bwlp.thrift.iface.Satellite;
import org.openslx.bwlp.thrift.iface.SatelliteServer.Client;
import org.openslx.bwlp.thrift.iface.TAuthorizationException;
import org.openslx.bwlp.thrift.iface.TInvocationException;
import org.openslx.bwlp.thrift.iface.TransferInformation;
import org.openslx.bwlp.thrift.iface.TransferState;
import org.openslx.bwlp.thrift.iface.UserInfo;
import org.openslx.bwlp.thrift.iface.WhoamiInfo;
import org.openslx.dozmod.App;
import org.openslx.dozmod.Config;
import org.openslx.dozmod.Config.SavedSession;
import org.openslx.dozmod.authentication.Authenticator.AuthenticationData;
import org.openslx.dozmod.filetransfer.AsyncHashGenerator;
import org.openslx.dozmod.filetransfer.DownloadTask;
import org.openslx.dozmod.filetransfer.TransferEvent;
import org.openslx.dozmod.filetransfer.TransferEventListener;
import org.openslx.dozmod.filetransfer.UploadTask;
import org.openslx.dozmod.gui.GraphicalCertHandler;
import org.openslx.dozmod.gui.Gui;
import org.openslx.dozmod.gui.MainWindow;
import org.openslx.dozmod.gui.helper.MessageType;
import org.openslx.dozmod.gui.helper.QFileChooser;
import org.openslx.dozmod.gui.window.SatelliteListWindow;
import org.openslx.dozmod.thrift.cache.ImageCache;
import org.openslx.dozmod.thrift.cache.LectureCache;
import org.openslx.dozmod.thrift.cache.MetaDataCache;
import org.openslx.dozmod.thrift.cache.UserCache;
import org.openslx.dozmod.util.FormatHelper;
import org.openslx.dozmod.util.VmWrapper;
import org.openslx.dozmod.util.VmWrapper.MetaDataMissingException;
import org.openslx.sat.thrift.version.Version;
import org.openslx.thrifthelper.ThriftManager;
import org.openslx.util.QuickTimer;
import org.openslx.util.QuickTimer.Task;
import org.openslx.util.Util;
import org.openslx.util.vm.DiskImage;
import org.openslx.util.vm.DiskImage.UnknownImageFormatException;

public class ThriftActions {

	private static final Logger LOGGER = Logger.getLogger(ThriftActions.class);
	private static final long SIZE_CHECK_EXTRA_DL = 50l * 1024l * 1024l;
	private static final long SIZE_CHECK_EXTRA_UL = 150l * 1024l * 1024l;

	/* *******************************************************************************
	 * 
	 * LOGIN
	 * 
	 * Login methods
	 * 
	 * **************************************************************************
	 * ****
	 */
	/**
	 * @param window the parentWindow
	 * @param data AuthenticationData as received from a successful login, or
	 *            null if trying to resume a saved sessions
	 * @param forceCustomSatellite show satellite selection dialog even if there
	 *            is just one
	 * @param loginWindow
	 * @return true if initialising the session worked, false otherwise
	 */
	public static boolean initSession(AuthenticationData data, boolean forceCustomSatellite, Window window) {
		Client client = null;
		WhoamiInfo whoami = null;
		String address = null;
		String satToken = null;
		String masterToken = null;
		if (data == null) {
			// in session resume
			SavedSession session = Config.getSavedSession();
			if (session == null)
				return false;
			address = session.address;
			satToken = session.token;
			masterToken = session.masterToken;
		} else {
			// after login
			Satellite sat = null;
			if (data.satellites != null && data.satellites.size() == 1 && !forceCustomSatellite) {
				sat = data.satellites.get(0);
			} else {
				sat = SatelliteListWindow.open(window, data.satellites);
			}

			if (sat == null || sat.addressList == null) {
				// TODO: Ask for manual IP address entry
				Gui.asyncMessageBox("Login erfolgreich, aber es wurde kein Satelliten-Server ausgewählt.\n"
						+ "Vorgang abgebrochen.", MessageType.ERROR, LOGGER, null);
				return false;
			}
			if (sat.addressList.isEmpty()) {
				// TODO: Ask for manual IP address entry
				Gui.asyncMessageBox("Login erfolgreich, aber für den ausgewählten Satelliten-Server ist\n"
						+ "keine Adresse hinterlegt. Kann nicht verbinden.", MessageType.ERROR, LOGGER, null);
				return false;
			}
			address = sat.addressList.get(0);
			satToken = data.satelliteToken;
			masterToken = data.masterToken;

		}
		// try to get a new client
		client = ThriftManager.getNewSatelliteClient(GraphicalCertHandler.getSslContext(address), address,
				App.THRIFT_SSL_PORT, App.THRIFT_TIMEOUT_MS);
		if (client == null) {
			if (data != null) {
				Gui.asyncMessageBox(
						"Authentifizierung erfolgreich, die Verbindung zum Satelliten-Server ist jedoch nicht möglich.\n\n"
								+ "Möglicherweise ist der Server nicht verfügbar, oder die Netzwerkverbindung gestört.",
						MessageType.ERROR, null, null);
			}
			return false;
		}

		// check our version
		long remoteVersion = 0;
		try {
			remoteVersion = client.getVersion();
		} catch (TException e) {
			LOGGER.debug("Failed to retrieve remote version: ", e);
			return false;
		}
		if (remoteVersion != Version.VERSION) {
			if (data != null) {
				Gui.asyncMessageBox(
						"Das von Ihnen verwendete Dozentenmodul ist nicht mit dem Satelliten-Server kompatibel.\n"
								+ "Ihre Version: " + Version.VERSION + "\n" + "Satelliten-Version: "
								+ remoteVersion, MessageType.ERROR, LOGGER, null);
			}
			return false;
		}
		// all good, try to get the whoami info
		try {
			whoami = client.whoami(satToken);
		} catch (TAuthorizationException e) {
			if (data != null) {
				Gui.asyncMessageBox(
						"Authentifizierung erfolgreich, der Satellit verweigert jedoch die Verbindung.\n\n"
								+ "Grund: " + e.number.toString() + " (" + e.message + ")",
						MessageType.ERROR, null, null);
			}
			return false;
		} catch (TInvocationException e) {
			if (data != null) {
				Gui.asyncMessageBox(
						"Authentifizierung erfolgreich, bei der Kommunikation mit dem Satelliten trat jedoch ein interner Server-Fehler auf.",
						MessageType.ERROR, LOGGER, e);
			}
			return false;
		} catch (Exception e) {
			if (data != null) {
				Gui.asyncMessageBox(
						"Authentifizierung erfolgreich, aber der Satellit akzeptiert das Sitzungstoken nicht.",
						MessageType.ERROR, LOGGER, e);
			}
			return false;
		}

		if (whoami != null) {
			Session.initialize(whoami, address, satToken, masterToken);
			ThriftManager.setSatelliteAddress(
					GraphicalCertHandler.getSslContext(Session.getSatelliteAddress()),
					Session.getSatelliteAddress(), App.THRIFT_SSL_PORT, App.THRIFT_TIMEOUT_MS);
			QuickTimer.scheduleOnce(new Task() {
				@Override
				public void fire() {
					// Cache useful data from server
					MetaDataCache.getOperatingSystems();
					MetaDataCache.getVirtualizers();
					UserCache.getAll();
					ImageCache.get(false);
					LectureCache.get(false);
				}
			});
			return true;
		}
		return false;
	}

	/* *******************************************************************************
	 * 
	 * IMAGE CREATION
	 * 
	 * Creates a base image with the given name
	 * 
	 * **************************************************************************
	 * ****
	 */
	/**
	 * GUI-BLOCKING Creates the image with the given name. Returns the uuid
	 * returned by the server
	 * 
	 * @param frame calling this action
	 * @return uuid as String, or null if the creation failed
	 */
	public static String createImage(final Frame frame, final String name) {
		String uuid = null;
		try {
			uuid = ThriftManager.getSatClient().createImage(Session.getSatelliteToken(), name);
		} catch (TException e) {
			ThriftError.showMessage(frame, LOGGER, e, "Erstellen des Images fehlgeschlagen");
		} catch (Exception e) {
			Gui.showMessageBox(frame, "Unbekannter Fehler beim Erstellen der VM", MessageType.ERROR, LOGGER,
					e);
		}
		return uuid;
	}

	/**
	 * GUI-BLOCKING Pushes a new image base to the server with the given
	 * imageBaseId and the meta information in meta
	 * 
	 * @param frame to show user feedback on
	 * @param imageBaseId image's id we are writing meta information of
	 * @param meta actual meta information as ImageBaseWrite
	 */
	public static boolean updateImageBase(final Frame frame, final String imageBaseId,
			final ImageBaseWrite meta) {
		try {
			ThriftManager.getSatClient().updateImageBase(Session.getSatelliteToken(), imageBaseId, meta);
		} catch (TException e) {
			ThriftError.showMessage(frame, LOGGER, e, "Konnte Metadaten des Images nicht übertragen");
			return false;
		}
		return true;
	}

	/**
	 * GUI-BLOCKING Pushes the given permission map as custom permission for the
	 * given imageBaseId
	 * 
	 * @param frame to show user feedback on
	 * @param imageBaseId image's id we are writing permissions of
	 * @param permissions actual permissions map to write
	 */
	public static boolean writeImagePermissions(final Frame frame, final String imageBaseId,
			final Map<String, ImagePermissions> permissions) {
		try {
			ThriftManager.getSatClient().writeImagePermissions(Session.getSatelliteToken(), imageBaseId,
					permissions);
		} catch (TException e) {
			ThriftError.showMessage(frame, LOGGER, e, "Konnte Berechtigungen nicht übertragen");
			return false;
		}
		return true;
	}

	/* *******************************************************************************
	 * 
	 * IMAGE VERSION UPLOAD
	 * 
	 * Methods to upload an image version. This is compromised of two distinct
	 * steps: - requestVersionUpload(..) to request the upload at the server -
	 * initUpload(..) to actually start the upload of the file
	 * 
	 * **************************************************************************
	 * ****
	 */
	/**
	 * GUI-BLOCKING Request the upload of an image version. Returns the
	 * TransferInformation received by the server or null if the request failed.
	 * Will give user feedback about failures.
	 * 
	 * @param frame caller of this method
	 * @param imageBaseId uuid of the image to upload a version of
	 * @param fileSize size in bytes(?) of the uploaded file
	 * @param blockHashes
	 * @param machineDescription
	 * @param callback
	 * @return TransferInformation received by the server, null if the request
	 *         failed.
	 */
	public static TransferInformation requestVersionUpload(final Frame frame, final String imageBaseId,
			final long fileSize, final List<ByteBuffer> blockHashes, final ByteBuffer machineDescription) {
		try {
			if (ThriftManager.getSatClient().getStatus().getAvailableStorageBytes() < fileSize
					+ SIZE_CHECK_EXTRA_UL) {
				Gui.showMessageBox(
						frame,
						"Nicht genügend Speicherplatz Satelliten. Löschen Sie nicht verwendete Imageversionen oder kontaktieren sie den Administrator.",
						MessageType.ERROR, LOGGER, null);
				return null;
			}
		} catch (TException e1) {
			ThriftError.showMessage(frame, LOGGER, e1, "Konnte Status des Satelliten nicht abfragen!");
			return null;
		}
		TransferInformation ti = null;
		try {
			ti = ThriftManager.getSatClient().requestImageVersionUpload(Session.getSatelliteToken(),
					imageBaseId, fileSize, null, // TODO remove deprecated parameter
					machineDescription);
			LOGGER.info("Version upload granted, versionId: '" + ti.toString());
		} catch (TAuthorizationException e) {
			ThriftError.showMessage(frame, LOGGER, e, "Upload einer neuen Version nicht erlaubt!");
		} catch (TException e) {
			ThriftError.showMessage(frame, LOGGER, e, "Upload-Anfrage gescheitert!");
		}
		return ti;
	}

	/**
	 * GUI-BLOCKING Starts uploading the given diskFile using the
	 * transferInformation and hashGen
	 * 
	 * @param frame caller of this method
	 * @param transferInformation transfer information to use for the upload
	 * @param hashGen hash generator for this file
	 * @param diskFile the file to upload
	 * @return UploadTask if the uploading initialized, or null if uploading
	 *         failed
	 */
	public static InitUploadStatus initUpload(final Frame frame,
			final TransferInformation transferInformation, final File diskFile) {
		UploadTask uploadTask = null;
		// do actually start the upload now
		LOGGER.debug("Starting upload for: " + diskFile.toPath());
		try {
			uploadTask = new UploadTask(Session.getSatelliteAddress(), transferInformation.getPlainPort(),
					transferInformation.getToken(), diskFile);
		} catch (FileNotFoundException e) {
			Gui.asyncMessageBox(
					"Kann VM nicht hochladen: Datei nicht gefunden\n\n" + diskFile.getAbsolutePath(),
					MessageType.ERROR, LOGGER, e);
			return null;
		}
		AsyncHashGenerator hashGen = null;
		try {
			hashGen = new AsyncHashGenerator(transferInformation.token, diskFile);
			hashGen.start();
			Util.sleep(50);// A little ugly... Give the hash generator a head
			// start
		} catch (FileNotFoundException | NoSuchAlgorithmException e) {
			Gui.showMessageBox(frame, "Kann keine Block-Hashes für den Upload berechnen, "
					+ "automatische Fehlerkorrektur deaktiviert.", MessageType.WARNING, LOGGER, e);
		}
		Util.sleep(50); // A little ugly... Give the hash generator a head start
		Thread uploadThread = new Thread(uploadTask);
		uploadThread.setDaemon(true);
		uploadThread.start();
		do { // Even more ugly - block the GUI thread so we know whether the
				// upload started, and only then switch to the next page
			Util.sleep(5);
		} while (uploadTask.getFailCount() == 0 && uploadTask.getTransferCount() == 0
				&& !uploadTask.isCanceled());

		if (uploadTask.getTransferCount() == 0) {
			Gui.asyncMessageBox("Aufbau der Verbindung zum Hochladen fehlgeschlagen", MessageType.ERROR,
					LOGGER, null);
			hashGen.cancel();
			uploadTask.cancel();
			uploadTask = null;
		}
		return new InitUploadStatus(uploadTask, hashGen);
	}

	/**
	 * GUI-BLOCKING Gives user feedback TODO
	 * 
	 * @param frame
	 * @param transferInformation
	 * @param versionInfo
	 */
	public static boolean updateImageVersion(final Frame frame, final String versionId,
			final ImageVersionWrite versionInfo) {
		try {
			ThriftManager.getSatClient().updateImageVersion(Session.getSatelliteToken(), versionId,
					versionInfo);
		} catch (TException e) {
			Gui.showMessageBox(frame, "Konnte neue Version nicht erstellen!", MessageType.ERROR, LOGGER, e);
			return false;
		}
		return true;
	}

	/* *******************************************************************************
	 * 
	 * IMAGE VERSION DOWNLOAD
	 * 
	 * Download image version action composed of the interface
	 * 'DownloadCallback' and the actual static method 'initDownload' to start
	 * the download.
	 * 
	 * **************************************************************************
	 * ****
	 */
	/**
	 * The callback interface to inform the GUI about the status of the
	 * operation
	 */
	public interface DownloadCallback {
		void downloadInitialized(boolean success);
	}

	/**
	 * NON-BLOCKING Initialises the download of the given imageVersionId saving
	 * it to the given imageName
	 * 
	 * @param frame caller of this method
	 * @param imageVersionId image version id to download
	 * @param imageName destination file name
	 * @param virtualizerId id of the virtualizer
	 * @param imageSize size in bytes of the image to download
	 * @param callback callback function to return status of this operation to
	 *            the GUI
	 */
	public static void initDownload(final Frame frame, final String imageVersionId, final String imageName,
			final String virtualizerId, final int osId, final long imageSize, final DownloadCallback callback) {
		// TODO: Return value? Callback?
		QFileChooser fc = new QFileChooser(Config.getDownloadPath(), true);
		fc.setDialogTitle("Bitte wählen Sie einen Speicherort");
		int action = fc.showSaveDialog(frame);
		File selected = fc.getSelectedFile();
		if (action != JFileChooser.APPROVE_OPTION || selected == null) {
			if (callback != null)
				callback.downloadInitialized(false);
			return;
		}

		final File destDir = new File(selected, generateDirname(imageName, imageVersionId));
		final File tmpDiskFile = new File(destDir.getAbsolutePath(), VmWrapper.generateFilename(imageName,
				null) + ".part");

		if (destDir.exists()) {
			boolean ret = Gui.showMessageBox(frame, "Verzeichnis '" + destDir.getAbsolutePath()
					+ "' existiert bereits, wollen Sie die VM darin überschreiben?",
					MessageType.QUESTION_YESNO, LOGGER, null);
			if (!ret) {
				// user aborted
				if (callback != null)
					callback.downloadInitialized(false);
				return;
			}
			// delete it
			if (!tmpDiskFile.delete() && tmpDiskFile.exists()) {
				Gui.showMessageBox(frame, "Datei konnte nicht überschrieben werden!", MessageType.ERROR,
						LOGGER, null);
				if (callback != null)
					callback.downloadInitialized(false);
				return;
			}
		} else {
			destDir.getAbsoluteFile().mkdirs();
		}

		// Check the free space on disk
		if (destDir.getUsableSpace() < imageSize + SIZE_CHECK_EXTRA_DL) {
			Gui.showMessageBox(frame, "Nicht genügend Speicherplatz im ausgewählten Verzeichnis verfügbar.\n"
					+ "Brauche: " + FormatHelper.bytes(imageSize + SIZE_CHECK_EXTRA_DL, false) + "\n"
					+ "Habe: " + FormatHelper.bytes(destDir.getUsableSpace(), false), MessageType.ERROR,
					LOGGER, null);
			if (callback != null)
				callback.downloadInitialized(false);
			return;
		}

		QuickTimer.scheduleOnce(new Task() {
			@Override
			public void fire() {
				final TransferInformation transInf;
				try {
					transInf = ThriftManager.getSatClient().requestDownload(Session.getSatelliteToken(),
							imageVersionId);
				} catch (TException e) {
					ThriftError.showMessage(frame, LOGGER, e, "Die Download-Anfrage ist gescheitert");
					if (callback != null)
						callback.downloadInitialized(false);
					return;
				}

				final DownloadTask dlTask;
				try {
					dlTask = new DownloadTask(Session.getSatelliteAddress(), transInf.getPlainPort(),
							transInf.getToken(), tmpDiskFile, imageSize, null);
				} catch (FileNotFoundException e) {
					Gui.asyncMessageBox(
							"Konnte Download nicht vorbereiten: Der gewählte Zielort ist nicht beschreibbar",
							MessageType.ERROR, LOGGER, e);
					if (callback != null)
						callback.downloadInitialized(false);
					return;
				}

				dlTask.addListener(new TransferEventListener() {
					@Override
					public void update(TransferEvent event) {
						if (event.state != TransferState.FINISHED)
							return;
						DiskImage diskImage = null;
						String ext = virtualizerId;
						try {
							diskImage = new DiskImage(tmpDiskFile);
						} catch (IOException | UnknownImageFormatException e) {
							LOGGER.warn("Could not open downloaded image for analyze step", e);
						}
						if (diskImage != null) {
							if (diskImage.format != null) {
								ext = diskImage.format.extension;
							}
							if (diskImage.isCompressed) {
								Gui.asyncMessageBox("Die heruntergeladene VM '" + imageName + "' ist ein"
										+ "\nkomprimiertes Abbild. Sie müssen das Abbild dekomprimieren,"
										+ "\nbevor Sie es verändern können."
										+ "\n\n(TODO: Hinweis vmware disk tools)", MessageType.WARNING, null,
										null); // TODO
							}
						}
						File destImage = new File(destDir.getAbsolutePath(), VmWrapper.generateFilename(
								imageName, ext));
						destImage.delete();
						if (!tmpDiskFile.renameTo(destImage)) {
							destImage = tmpDiskFile; // Must be Windows...
						}
						try {
							VmWrapper.wrapVm(destImage, imageName, transInf.getMachineDescription(),
									virtualizerId, osId, diskImage);
						} catch (MetaDataMissingException | IOException e) {
							Gui.asyncMessageBox(
									"Zur heruntergeladenen VM konnte keine vmx-Datei angelegt werden."
											+ "\nSie können versuchen, das Abbild manuell in den VMWare-Player zu importieren.",
									MessageType.WARNING, LOGGER, e);
						}
					}
				});

				Gui.asyncExec(new Runnable() {
					@Override
					public void run() {
						MainWindow.addDownload(imageName, tmpDiskFile.getName(), dlTask);
					}
				});

				new Thread(dlTask).start();

				Config.setDownloadPath(destDir.getParentFile().getAbsolutePath());
				if (callback != null)
					callback.downloadInitialized(true);
			}
		});
	}

	/**
	 * Helper to generate a directory name for the given imageName and
	 * imageVersionId.
	 * Uses the given parameters to build a hopefully unique name as it takes
	 * the first 8
	 * chars of the version id...
	 * 
	 * @param imageName name of the image
	 * @param imageVersionId version id
	 * @return generated directory name as String
	 */
	private static String generateDirname(String imageName, String imageVersionId) {
		String fileName = imageName.replaceAll("[^a-zA-Z0-9_\\.\\-]+", "_");
		if (fileName.length() > 50) {
			fileName = fileName.substring(0, 50);
		}
		fileName += "--" + imageVersionId.substring(0, 8);
		return fileName;
	}

	/* *******************************************************************************
	 * 
	 * IMAGE METADATA
	 * 
	 * *******************************************************************************/

	/**
	 * Callback interface for image meta calls
	 */
	public interface ImageMetaCallback {
		void fetchedImageDetails(ImageDetailsRead details, Map<String, ImagePermissions> permissions);
	}

	/**
	 * BLOCKING Gets the image details (w/o permissions) of the given
	 * imageBaseID
	 * 
	 * @param frame to display user feedback on
	 * @param imageBaseId image's id to get the details of
	 * @return details as ImageDetailsRead if fetching worked, null otherwise
	 */
	public static ImageDetailsRead getImageDetails(final Frame frame, final String imageBaseId) {
		ImageDetailsRead details = null;
		try {
			details = ThriftManager.getSatClient().getImageDetails(Session.getSatelliteToken(), imageBaseId);
		} catch (TException e) {
			ThriftError.showMessage(frame, LOGGER, e, "Fehler beim Lesen der Metadaten");
		}
		return details;
	}

	/**
	 * NON-BLOCKING Gets the image details (without permissions) of the given
	 * imageBaseId.
	 * Will return the details (or null if fetching failed) back to the
	 * gui-thread
	 * through the given callback
	 * 
	 * @param frame to display user feedback on
	 * @param imageBaseId image's id to get the details of
	 * @param callback interface to return the details back to the gui
	 */
	public static void getImageDetails(final Frame frame, final String imageBaseId,
			final ImageMetaCallback callback) {
		QuickTimer.scheduleOnce(new Task() {
			ImageDetailsRead details = null;

			@Override
			public void fire() {
				details = ThriftActions.getImageDetails(frame, imageBaseId);
				Gui.asyncExec(new Runnable() {
					@Override
					public void run() {
						if (callback != null) {
							callback.fetchedImageDetails(details, null);
						}
					}
				});
			}
		});
	}

	/**
	 * NON-BLOCKING Gets the image details and the user-specific permission list
	 * of
	 * the given imageBaseId. Will return the objects through the given callback
	 * 
	 * @param frame to display user feedback on
	 * @param imageBaseId image's id to get the full details of
	 * @param callback interface called to return the details back to the gui
	 */
	public static void getImageFullDetails(final Frame frame, final String imageBaseId,
			final ImageMetaCallback callback) {
		QuickTimer.scheduleOnce(new Task() {
			ImageDetailsRead details = null;
			Map<String, ImagePermissions> permissions = null;

			@Override
			public void fire() {
				details = ThriftActions.getImageDetails(frame, imageBaseId);
				permissions = ThriftActions.getImagePermissions(frame, imageBaseId);
				Gui.asyncExec(new Runnable() {
					@Override
					public void run() {
						if (callback != null) {
							callback.fetchedImageDetails(details, permissions);
						}
					}
				});
			}
		});
	}

	/**
	 * NON-BLOCKING Gets the user-specific permission list for the given
	 * imageBaseId
	 * 
	 * @param frame to display user feedback on
	 * @param imageBaseId image's id to get the permission list of
	 * @param callback interface to return the permission list back to the gui
	 */
	public static void getImagePermissions(final Frame frame, final String imageBaseId,
			final ImageMetaCallback callback) {
		QuickTimer.scheduleOnce(new Task() {
			Map<String, ImagePermissions> permissionMap = null;

			@Override
			public void fire() {
				permissionMap = ThriftActions.getImagePermissions(frame, imageBaseId);
				Gui.asyncExec(new Runnable() {
					@Override
					public void run() {
						if (callback != null) {
							callback.fetchedImageDetails(null, permissionMap);
						}
					}
				});
			}
		});
	}

	/**
	 * BLOCKING Gets the user-specific permission list for the given imageBaseId
	 * 
	 * @param frame to display user feedback on
	 * @param imageBaseId image's base id to get the user permissions of
	 * @return the map userid-permissions if fetching worked, null otherwise
	 */
	public static Map<String, ImagePermissions> getImagePermissions(final Frame frame,
			final String imageBaseId) {
		Map<String, ImagePermissions> permissionMap = null;
		try {
			permissionMap = ThriftManager.getSatClient().getImagePermissions(Session.getSatelliteToken(),
					imageBaseId);
		} catch (TException e) {
			ThriftError.showMessage(frame, LOGGER, e, "Fehler beim Lesen der Metadaten");
		}
		return permissionMap;
	}

	/**
	 * BLOCKING Sets the owner of the given lectureId to newOwner
	 * 
	 * @param frame to display user feedback on
	 * @param lectureId lecture's id to set the new owner of
	 * @param newOwner as UserInfo
	 * @return true if it worked, false otherwise
	 */
	public static boolean setImageOwner(final Frame frame, final String lectureId, final UserInfo newOwner) {
		try {
			ThriftManager.getSatClient().setImageOwner(Session.getSatelliteToken(), lectureId,
					newOwner.getUserId());
		} catch (TException e) {
			ThriftError.showMessage(frame, LOGGER, e, "Fehler beim Übertragen der Besitzrechte");
			return false;
		}
		return true;
	}

	/* *******************************************************************************
	 * 
	 * IMAGE / VERSION DELETION
	 * 
	 * *******************************************************************************/
	/**
	 * Callback interface to be implemented by callers of
	 * ThriftActions.deleteImageVersion(..)
	 */
	public interface DeleteCallback {
		/**
		 * Called once the status of a delete operation is determined
		 * 
		 * @param success true if deleted successfully, false otherwise
		 */
		void isDeleted(boolean success);
	}

	/**
	 * BLOCKING Deletes the base image with the given id. Will call the given
	 * callback to report about the status of this operation
	 * 
	 * @param frame to display user feedback on
	 * @param imageBaseId image base id to delete
	 * @param callback interface to report the outcome to the gui
	 */
	public static void deleteImageBase(final Frame frame, final String imageBaseId,
			final DeleteCallback callback) {
		if (imageBaseId == null || imageBaseId.isEmpty())
			return;
		// first look if we have versions
		ImageDetailsRead details = null;
		// these help construct the question text for the user, bit ugly...
		List<LectureSummary> lecturesToBeDeleted = null;
		List<ImageVersionDetails> versionToBeDeleted = null;
		try {
			details = ThriftManager.getSatClient().getImageDetails(Session.getSatelliteToken(), imageBaseId);
			List<LectureSummary> lectureList = ThriftManager.getSatClient().getLectureList(
					Session.getSatelliteToken(), 100);
			for (LectureSummary lecture : lectureList) {
				if (imageBaseId.equals(lecture.getImageBaseId())) {
					if (lecturesToBeDeleted == null)
						lecturesToBeDeleted = new ArrayList<LectureSummary>();
					lecturesToBeDeleted.add(lecture);
				}
			}
			for (ImageVersionDetails version : details.getVersions()) {
				if (version.isValid) {
					if (versionToBeDeleted == null)
						versionToBeDeleted = new ArrayList<ImageVersionDetails>();
					versionToBeDeleted.add(version);
				}
			}

		} catch (TException e) {
			ThriftError.showMessage(frame, LOGGER, e,
					"Fehler beim Holen der Versionen/Veranstaltung zu folgendes Image: " + imageBaseId);
			return;
		}
		String questionText;
		if (versionToBeDeleted != null && !versionToBeDeleted.isEmpty()) {
			questionText = "Dieses Image hat folgende gültige Versionen:\n";
			for (ImageVersionDetails version : versionToBeDeleted) {
				questionText += version.getVersionId() + "\n";
			}
			questionText += "\n";
		} else {
			questionText = "";
		}
		if (lecturesToBeDeleted != null && !lecturesToBeDeleted.isEmpty()) {
			questionText += "Dieses Image ist mit folgenden Veranstaltungen verknüpft:\n";
			for (LectureSummary lecture : lecturesToBeDeleted) {
				questionText += lecture.getLectureName() + "\n";
			}
			questionText += "\n";
		}
		questionText += "Wollen Sie dieses Image wirklich löschen?";
		if (!userConfirmed(frame, questionText))
			return;
		try {
			ThriftManager.getSatClient().deleteImageBase(Session.getSatelliteToken(), imageBaseId);
		} catch (TException e) {
			ThriftError.showMessage(frame, LOGGER, e, "Konnte Basis-Image nicht löschen!");
		}

	}

	/**
	 * BLOCKING Deletes either an image base or an image version depending
	 * on the parameters. To delete an image base, give the imageBaseId and let
	 * imageVersionId be null. To delete an image version, set both imageBaseId
	 * and imageVersionId. The success of the operation will be forwarded to the
	 * GUI through the DeleteCallback.
	 * 
	 * @param frame next parent frame of the caller of this method
	 * @param imageBaseId uuid of the image that belongs to the version
	 * @param imageVersionId id of the image version to be deleted
	 * @param callback called to inform the GUI about the deletion status (see
	 *            DeleteCallback interface)
	 */
	public static void deleteImageVersion(final Frame frame, final String imageVersionId,
			final DeleteCallback callback) {
		if (imageVersionId == null || imageVersionId.isEmpty())
			return;
		boolean success = false;
		List<LectureSummary> lectureList = null;
		try {
			// fetch lectures
			lectureList = ThriftManager.getSatClient().getLectureList(Session.getSatelliteToken(), 100);
		} catch (TException e) {
			ThriftError.showMessage(frame, LOGGER, e, "Fehler beim Holen der Liste der Veranstaltungen");
			if (callback != null)
				callback.isDeleted(success);
			return;
		}
		String questionText = "";
		// represents if we found matches of not, needed to make a proper
		// message
		boolean matches = false;
		if (lectureList != null && !lectureList.isEmpty()) {
			for (LectureSummary lecture : lectureList) {
				if (imageVersionId.equals(lecture.getImageVersionId())) {
					if (!matches)
						questionText = "Diese Version ist zu folgende Veranstaltungen verknüpft:\n";
					matches = true;
					questionText += lecture.getLectureName() + "\n";
				}
			}
			if (matches)
				questionText += "\nWollen Sie diese Version samt Veranstaltungen löschen?\n";
		}
		if (!matches)
			questionText = "Wollen Sie diese Image-Version wirklich löschen?";

		if (!userConfirmed(frame, questionText))
			return;
		try {
			ThriftManager.getSatClient().deleteImageVersion(Session.getSatelliteToken(), imageVersionId);
			LOGGER.info("Deleted version '" + imageVersionId + "'.");
			success = true;
		} catch (TException e) {
			ThriftError.showMessage(frame, LOGGER, e, "Fehler beim Löschen der Version");
			if (callback != null)
				callback.isDeleted(success);
			return;
		}
		final boolean fSuccess = success;
		Gui.asyncExec(new Runnable() {
			@Override
			public void run() {
				if (callback != null)
					callback.isDeleted(fSuccess);
			}
		});
	}

	/* *******************************************************************************
	 * 
	 * LECTURE CREATION
	 * 
	 * *******************************************************************************/
	/**
	 * BLOCKING Creates a lecture with the given meta data
	 * 
	 * @param frame to show user feedback on
	 * @param meta actual meta data as LectureWrite
	 * @return the created lecture's id if it worked, null otherwise
	 */
	public static String createLecture(final Frame frame, final LectureWrite meta) {
		if (meta == null)
			return null;
		String uuid = null;
		try {
			// push to sat
			uuid = ThriftManager.getSatClient().createLecture(Session.getSatelliteToken(), meta);
		} catch (TException e) {
			ThriftError.showMessage(frame, LOGGER, e, "Failed to create lecture");
		}
		return uuid;
	}

	/**
	 * BLOCKING Writes custom lecture permissions (permissions param) for
	 * the given lectureId.
	 * 
	 * @param frame to show user feedback on
	 * @param lectureId lecture's id to write custom permissions for
	 * @param permissions actual permission map to push
	 */
	public static boolean writeLecturePermissions(final Frame frame, final String lectureId,
			final Map<String, LecturePermissions> permissions) {
		try {
			ThriftManager.getSatClient().writeLecturePermissions(Session.getSatelliteToken(), lectureId,
					permissions);
		} catch (TException e) {
			ThriftError.showMessage(frame, LOGGER, e, "Failed to write lecture permissions");
			return false;
		}
		return true;
	}

	/* *******************************************************************************
	 * 
	 * LECTURE METADATA
	 * 
	 * *******************************************************************************/

	/**
	 * Interface for GUI-classes running async lecture meta calls
	 */
	public interface LectureMetaCallback {
		void fetchedLectureAndImageDetails(LectureRead lecture, ImageDetailsRead image);
	}

	/**
	 * NON-BLOCKING Gets the lecture and image details of the given lectureId.
	 * IF the lecture does not exist, both fields returned will be null. If the
	 * lecture exists, the image can still be null, since not all lectures link
	 * to an image at all times.
	 * 
	 * @param frame to display user feedback on
	 * @param lectureId lecture to get the full details of
	 * @param callback interface to return the details to the gui
	 */
	public static void getLectureAndImageDetails(final Frame frame, final String lectureId,
			final LectureMetaCallback callback) {
		QuickTimer.scheduleOnce(new Task() {
			@Override
			public void fire() {
				final LectureRead lecture = ThriftActions.getLectureDetails(frame, lectureId);
				final ImageDetailsRead fImage;
				if (lecture != null && lecture.imageBaseId != null) {
					fImage = ThriftActions.getImageDetails(frame, lecture.getImageBaseId());
				} else {
					fImage = null;
				}
				Gui.asyncExec(new Runnable() {
					@Override
					public void run() {
						if (callback != null) {
							callback.fetchedLectureAndImageDetails(lecture, fImage);
						}
					}
				});
			}
		});
	}

	/**
	 * BLOCKING Gets the lecture details of the lecture with given lectureId
	 * 
	 * @param frame to display user feedback on
	 * @param lectureId lecture to get the details of
	 * @return LectureRead if fetching details worked, null otherwise
	 */
	public static LectureRead getLectureDetails(final Frame frame, final String lectureId) {
		LectureRead lecture = null;
		try {
			lecture = ThriftManager.getSatClient().getLectureDetails(Session.getSatelliteToken(), lectureId);
		} catch (TException e) {
			ThriftError.showMessage(frame, LOGGER, e, "Konnte Veranstaltungdaten nicht abrufen");
		}
		return lecture;
	}

	/**
	 * BLOCKING Updates the lecture with given lectureId to the given lecture
	 * 
	 * @param frame to show user feedback on
	 * @param lectureId lecture's is to update
	 * @param lecture LectureWrite data to update the lecture with
	 * @return
	 */
	public static boolean updateLecture(final Frame frame, final String lectureId,
			final LectureWrite lectureWrite) {
		try {
			ThriftManager.getSatClient().updateLecture(Session.getSatelliteToken(), lectureId, lectureWrite);
		} catch (TException e) {
			ThriftError.showMessage(frame, LOGGER, e, "Fehler beim Updaten der Veranstaltung");
			return false;
		}
		return true;
	}

	/**
	 * BLOCKING Gets the list of user-specific permission for the lecture with
	 * the
	 * given lectureId
	 * 
	 * @param frame to display user feedback on
	 * @param lectureId lecture's id to get the permission list of
	 * @return the map of the userid-permissions if fetching worked, null
	 *         otherwise
	 */
	public static Map<String, LecturePermissions> getLecturePermissions(final Frame frame,
			final String lectureId) {
		Map<String, LecturePermissions> permissions = null;
		try {

			permissions = ThriftManager.getSatClient().getLecturePermissions(Session.getSatelliteToken(),
					lectureId);
		} catch (TException e) {
			ThriftError.showMessage(frame, LOGGER, e, "Konnte Veranstaltungdaten nicht abrufen");
		}
		return permissions;

	}

	/**
	 * BLOCKING Sets the owner of the given lectureId to newOwner
	 * 
	 * @param frame to display user feedback on
	 * @param lectureId lecture's id to set the new owner of
	 * @param newOwner as UserInfo
	 * @return true if it worked, false otherwise
	 */
	public static boolean setLectureOwner(final Frame frame, final String lectureId, final UserInfo newOwner) {
		try {
			ThriftManager.getSatClient().setLectureOwner(Session.getSatelliteToken(), lectureId,
					newOwner.getUserId());
		} catch (TException e) {
			ThriftError.showMessage(frame, LOGGER, e, "Fehler beim Übertragen der Besitzrechte");
			return false;
		}
		return true;
	}

	/* *******************************************************************************
	 * 
	 * LECTURE DELETION
	 * 
	 * *******************************************************************************/
	/**
	 * Callback interface reporting the status of the deletion back to the gui
	 */
	public interface DeleteLectureCallback {
		void deleted(boolean success);
	}

	/**
	 * NON-BLOCKING Deletes the lecture with the given lectureId
	 * 
	 * @param frame to display user feedback on
	 * @param lectureId id of the lecture to delete
	 * @param callback interface to report the status back to the gui
	 */
	public static void deleteLecture(final Frame frame, final String lectureId,
			final DeleteLectureCallback callback) {
		if (lectureId == null)
			return;
		if (!userConfirmed(frame, "Wollen Sie diese Veranstaltung wirklick löschen?"))
			return;
		QuickTimer.scheduleOnce(new Task() {
			boolean success = false;

			@Override
			public void fire() {
				try {
					ThriftManager.getSatClient().deleteLecture(Session.getSatelliteToken(), lectureId);
					success = true;
				} catch (TException e) {
					ThriftError.showMessage(frame, LOGGER, e, "Konnte Veranstaltungdaten nicht abrufen");
				}
				Gui.asyncExec(new Runnable() {
					@Override
					public void run() {
						if (callback != null) {
							callback.deleted(success);
						}
					}
				});
			}
		});
	}

	/* *******************************************************************************
	 * 
	 * PRIVATE HELPERS
	 * 
	 * *******************************************************************************/

	/**
	 * Helper to ask the user for confirmation. Returns his choice.
	 * 
	 * @param frame frame to show this message box on
	 * @param message question message to display to the user
	 * @return true if the user confirmed (clicked yes), false otherwise
	 */
	private static boolean userConfirmed(final Frame frame, final String message) {
		return Gui.showMessageBox(frame, message, MessageType.QUESTION_YESNO, null, null);
	}

	/**
	 * Wrapper class for UploadTask & AsyncHashGenerator
	 * 
	 */
	public static class InitUploadStatus {
		public final UploadTask task;
		public final AsyncHashGenerator hasher;

		public InitUploadStatus(final UploadTask task, final AsyncHashGenerator hasher) {
			this.task = task;
			this.hasher = hasher;
		}
	}

}