From fdd671785447d8f8691fbb07706ed32fb513498b Mon Sep 17 00:00:00 2001 From: Sakith B Date: Tue, 24 Oct 2023 20:31:03 +0530 Subject: [PATCH] use gjs to clear cache --- prefs.js | 59 ++++++++++++++++++++++++++++++++++++------ utils.js | 78 ++++++-------------------------------------------------- 2 files changed, 59 insertions(+), 78 deletions(-) diff --git a/prefs.js b/prefs.js index 18b04ed..5808e04 100644 --- a/prefs.js +++ b/prefs.js @@ -6,10 +6,12 @@ import Gdk from "gi://Gdk"; import GLib from "gi://GLib"; import Adw from "gi://Adw"; -import { execCommunicate } from "./utils.js"; - import { ExtensionPreferences, gettext as _ } from "resource:///org/gnome/Shell/Extensions/js/extensions/prefs.js"; +Gio._promisify(Gio.File.prototype, "query_info_async"); +Gio._promisify(Gio.File.prototype, "enumerate_children_async"); +Gio._promisify(Gio.File.prototype, "delete_async"); + export default class MediaControlsPreferences extends ExtensionPreferences { _ontracklabelchanged(settings, trackLabelOptKeys, trackLabelSep, trackLabelStart, trackLabelEnd) { let currentTrackLabel = settings.get_strv("track-label"); @@ -831,29 +833,70 @@ export default class MediaControlsPreferences extends ExtensionPreferences { } async _getCacheSize() { - // Command: du -hs [data_directory]/media-controls | awk '{NF=1}1' try { - let dir = GLib.get_user_config_dir() + "/media-controls"; - const result = await execCommunicate(["/bin/bash", "-c", `du -hs ${dir} | awk '{NF=1}1'`]); - return result || "0K"; + const path = GLib.get_user_config_dir() + "/media-controls/cache"; + const directory = Gio.File.new_for_path(path); + const iterator = await directory.enumerate_children_async( + "standard::*", + Gio.FileQueryInfoFlags.NOFOLLOW_SYMLINKS, + GLib.PRIORITY_DEFAULT, + null + ); + + let sizeInBytes = 0; + + for await (const fileInfo of iterator) { + const fileType = fileInfo.get_file_type(); + if (fileType === Gio.FileType.REGULAR) { + const fileSize = fileInfo.get_size(); + sizeInBytes += fileSize; + } + } + + return this._bytesToSize(sizeInBytes); } catch (error) { logError(error); } } async _clearcache(widgetCacheSize, clearcachespinner) { - let dir = GLib.get_user_config_dir() + "/media-controls"; try { clearcachespinner.start(); - await execCommunicate(["rm", "-r", dir]); + + const path = GLib.get_user_config_dir() + "/media-controls/cache"; + const directory = Gio.File.new_for_path(path); + const iterator = await directory.enumerate_children_async( + "standard::*", + Gio.FileQueryInfoFlags.NOFOLLOW_SYMLINKS, + GLib.PRIORITY_DEFAULT, + null + ); + + const promises = []; + + for await (const fileInfo of iterator) { + const file = iterator.get_child(fileInfo); + promises.push(file.delete_async(GLib.PRIORITY_DEFAULT, null)); + } + + await Promise.all(promises); + widgetCacheSize.set_text(await this._getCacheSize()); clearcachespinner.stop(); } catch (error) { + logError(error); widgetCacheSize.set_text(_("Failed to clear cache")); clearcachespinner.stop(); } } + _bytesToSize(bytes) { + const sizes = ["Bytes", "KB", "MB", "GB", "TB"]; + if (bytes === 0) return "0 Bytes"; + const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024))); + return Math.round(bytes / Math.pow(1024, i)) + " " + sizes[i]; + } + _onclearcacheclicked(widgetCacheSize, clearcachespinner) { this._clearcache(widgetCacheSize, clearcachespinner); } diff --git a/utils.js b/utils.js index 4bf3d1e..93f90a8 100644 --- a/utils.js +++ b/utils.js @@ -49,8 +49,7 @@ export const parseMetadata = (_metadata) => { let metadata = {}; for (let key in metadataKeys) { let val = _metadata[key]; - metadata[metadataKeys[key]] = - val instanceof GLib.Variant ? val.recursiveUnpack() : val; + metadata[metadataKeys[key]] = val instanceof GLib.Variant ? val.recursiveUnpack() : val; } let title = metadata.title || metadata.url || metadata.id; @@ -71,10 +70,7 @@ export const parseMetadata = (_metadata) => { let image = metadata.image; if (image) { - image = image.replace( - "https://open.spotify.com/image/", - "https://i.scdn.co/image/" - ); + image = image.replace("https://open.spotify.com/image/", "https://i.scdn.co/image/"); } metadata.title = title; @@ -91,70 +87,12 @@ export const getRequest = (url) => { return new Promise((resolve, reject) => { let _session = new Soup.Session(); let _request = Soup.Message.new("GET", url); - _session.send_and_read_async( - _request, - GLib.PRIORITY_DEFAULT, - null, - (_session, result) => { - if (_request.get_status() === Soup.Status.OK) { - let bytes = _session.send_and_read_finish(result); - resolve(bytes); - } else { - reject(new Error("Soup request not resolved")); - } - } - ); - }); -}; - -/** - * Executes a shell command asynchronously - * @param {Array} argv array of arguments - * @param {string?} input input to be given to the shell command - * @param {boolean?} cancellable whether the operation is cancellable - * @returns - */ -export const execCommunicate = async ( - argv, - input = null, - cancellable = null -) => { - let cancelId = 0; - let flags = - Gio.SubprocessFlags.STDOUT_PIPE | Gio.SubprocessFlags.STDERR_PIPE; - - if (input !== null) flags |= Gio.SubprocessFlags.STDIN_PIPE; - - let proc = new Gio.Subprocess({ - argv: argv, - flags: flags, - }); - proc.init(cancellable); - - if (cancellable instanceof Gio.Cancellable) { - cancelId = cancellable.connect(() => proc.force_exit()); - } - - return new Promise((resolve, reject) => { - proc.communicate_utf8_async(input, null, (proc, res) => { - try { - let [, stdout, stderr] = proc.communicate_utf8_finish(res); - let status = proc.get_exit_status(); - - if (status !== 0) { - throw new Gio.IOErrorEnum({ - code: Gio.io_error_from_errno(status), - message: stderr ? stderr.trim() : GLib.strerror(status), - }); - } - - resolve(stdout.trim()); - } catch (e) { - reject(e); - } finally { - if (cancelId > 0) { - cancellable.disconnect(cancelId); - } + _session.send_and_read_async(_request, GLib.PRIORITY_DEFAULT, null, (_session, result) => { + if (_request.get_status() === Soup.Status.OK) { + let bytes = _session.send_and_read_finish(result); + resolve(bytes); + } else { + reject(new Error("Soup request not resolved")); } }); });