forked from hslbck/gnome-shell-extension-radio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
io.js
88 lines (83 loc) · 2.63 KB
/
io.js
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
const Gio = imports.gi.Gio;
const GLib = imports.gi.GLib;
const Extension = imports.misc.extensionUtils.getCurrentExtension();
const Shell = imports.gi.Shell;
const FILE_NAME = 'channelList.json'
const DIR_NAME = '.gse-radio'
function read(){
let dir_path = GLib.get_home_dir() + "/" + DIR_NAME ;
create(dir_path);
let file_path = GLib.get_home_dir() + "/" + DIR_NAME + "/" + FILE_NAME;
let content;
let channelList;
try {
content = Shell.get_file_contents_utf8_sync(file_path);
} catch (e) {
global.logError('Failed to load channelList.json: ' + e);
return null;
}
// parse json file
try {
channelList = JSON.parse(content);
} catch (e) {
global.logError('Failed to parse channelList.json: ' + e);
return null;
}
return channelList;
}
// create channelList file in home directory
// ~/.gse-radio/channelList.json
function create(dir_path) {
let dir = Gio.file_new_for_path(dir_path);
let source_file = Gio.file_new_for_path(Extension.path).get_child(FILE_NAME);
if (!dir.query_exists(null)) {
try {
dir.make_directory(null);
let file = dir.get_child(FILE_NAME);
source_file.copy(file, Gio.FileCopyFlags.NONE, null, null);
} catch (e) {
global.logError('Failed to create directory and/or file! ' + e);
}
} else {
let file = dir.get_child(FILE_NAME);
if (!file.query_exists(null)) {
try {
source_file.copy(file, Gio.FileCopyFlags.NONE, null, null);
} catch (e) {
global.logError('Failed to create file! ' + e);
}
}
}
}
function write(channels, lastPlayed) {
if (channels != null && channels.length > 0) {
let filepath = GLib.get_home_dir() + "/" + DIR_NAME + "/" + FILE_NAME;
let file = Gio.file_new_for_path(filepath);
let raw = file.replace(null, false, Gio.FileCreateFlags.NONE, null);
let out = Gio.BufferedOutputStream.new_sized(raw, 4096);
// Format output and write channels
Shell.write_string_to_stream(out, "{ \"channels\":[\n");
for (var i = 0; i < channels.length; i++) {
Shell.write_string_to_stream(out, "\t");
Shell.write_string_to_stream(out, JSON.stringify({
name: channels[i].getName(),
address: channels[i].getUri(),
favourite: channels[i].getFavourite(),
encoding: channels[i].getEncoding()
}, null, "\t"));
// remove last comma
if (i != channels.length - 1) {
Shell.write_string_to_stream(out, ",");
}
}
// write lastplayed channel
Shell.write_string_to_stream(out, "\n],\n\n \"lastplayed\":");
Shell.write_string_to_stream(out, JSON.stringify({
name: lastPlayed.getName(),
address: lastPlayed.getUri(),
encoding: lastPlayed.getEncoding()
}, null, "\t"));
Shell.write_string_to_stream(out, "\n}");
out.close(null);
}
}