Skip to content

Commit

Permalink
use gjs to clear cache
Browse files Browse the repository at this point in the history
  • Loading branch information
sakithb committed Oct 24, 2023
1 parent 8880642 commit fdd6717
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 78 deletions.
59 changes: 51 additions & 8 deletions prefs.js
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -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);
}
Expand Down
78 changes: 8 additions & 70 deletions utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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<string>} 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"));
}
});
});
Expand Down

0 comments on commit fdd6717

Please sign in to comment.