tootle-linux-client/src/Utils/Host.vala

86 lines
2.2 KiB
Vala
Raw Normal View History

2020-08-01 19:56:12 +02:00
using GLib;
2021-07-23 13:41:03 +02:00
public class Tootle.Host {
2018-06-06 16:19:11 +02:00
2020-08-01 19:56:12 +02:00
// Open a URI in the user's default application
2021-02-02 15:07:27 +01:00
public static bool open_uri (string _uri) {
var uri = _uri;
2021-02-02 15:17:22 +01:00
if (!(":" in uri))
2021-02-02 15:07:27 +01:00
uri = "file://" + _uri;
2020-08-01 19:56:12 +02:00
message (@"Opening URI: $uri");
try {
2021-02-02 15:07:27 +01:00
var success = AppInfo.launch_default_for_uri (uri, null);
if (!success)
throw new Oopsie.USER (_("launch_default_for_uri() failed"));
2020-08-01 19:56:12 +02:00
}
catch (Error e){
try {
string[] spawn_args = {"/usr/bin/xdg-open", uri};
Process.spawn_sync (null, spawn_args, null, SpawnFlags.SEARCH_PATH, null, null, null);
}
catch (Error e){
2021-07-23 13:41:03 +02:00
//FIXME: WHY DO THESE TWO LINES CRASH THE COMPILER WHAT IS HAPPENING HERE
// warning (@"xdg-open failed too: $(e.message)");
// app.inform (Gtk.MessageType.WARNING, _("Open this URL in your browser"), uri);
return false;
2020-08-01 19:56:12 +02:00
}
}
return true;
}
2021-07-23 13:41:03 +02:00
// FIXME: Copy a string to the clipboard
2020-08-01 19:56:12 +02:00
public static void copy (string str) {
2021-07-23 13:41:03 +02:00
// var clipboard = Gdk.Clipboard.get_for_display (display, Gdk.SELECTION_CLIPBOARD);
// clipboard.set_text (Widgets.RichLabel.restore_entities (str), -1);
2020-08-01 19:56:12 +02:00
}
public static string get_uri_host (string uri) {
var p1 = uri;
if ("//" in uri)
p1 = uri.split ("//")[1];
return p1.split ("/")[0];
}
2020-11-19 10:46:18 +01:00
public async static string download (string url) throws Error {
2020-08-01 19:56:12 +02:00
message (@"Downloading file: $url...");
var file_name = Path.get_basename (url);
var dir_name = Path.get_dirname (url);
var dir_path = Path.build_path (
Path.DIR_SEPARATOR_S,
2021-07-23 13:41:03 +02:00
Environment.get_user_cache_dir (), // Environment.get_user_special_dir (UserDirectory.DOWNLOAD),
Build.DOMAIN,
2020-08-01 19:56:12 +02:00
get_uri_host (dir_name));
var file_path = Path.build_path (
Path.DIR_SEPARATOR_S,
dir_path,
str_hash (dir_name).to_string () + file_name);
2020-11-19 10:46:18 +01:00
var dir = File.new_for_path (dir_path);
if (!dir.query_exists ())
dir.make_directory_with_parents ();
var file = File.new_for_path (file_path);
if (!file.query_exists ()) {
var msg = yield new Request.GET (url)
.await ();
var data = msg.response_body.data;
FileOutputStream stream = file.create (FileCreateFlags.PRIVATE);
stream.write (data);
2021-07-23 13:41:03 +02:00
message (@" OK: File written to: $file_path");
2020-11-19 10:46:18 +01:00
}
else
2021-07-23 13:41:03 +02:00
message (" OK: File already exists");
2020-11-19 10:46:18 +01:00
return file_path;
2020-08-01 19:56:12 +02:00
}
2018-04-25 15:16:57 +02:00
}