Tasha53505 / 159.356-capstone-project-group

4 stars 0 forks source link

JSON RPC - Dynamic Songs - File can be written to, but not read #72

Closed Tasha53505 closed 1 month ago

Tasha53505 commented 2 months ago

With JSON RPC - I have had no probelm writing to the server.prefs file, but am having trouble READING it. Which doesn't make a lot of sense to me, as if anything I would think it's the other way around https://github.com/Tasha53505/159.356-capstone-project-group/commit/a23f2703a5639c04f1a2b9820510840b8c9ad09e

// ******************************************************************************
//                    ****  Fetch Songs   ****
// *******************************************************************************
// if (params && params[0] === "get" && params[1] === "mediadirs") {
    if (params && params[1][0] === "pref" && params[1][1] === "mediadirs") {

    let filePath;
    if (os.platform() === 'win32' || os.platform() === 'win64') {
        filePath = path.join('C:', 'ProgramData', 'Squeezebox', 'prefs', 'server.prefs');
    } else if (os.platform() === 'linux') {
        filePath = '/var/lib/squeezeboxserver/prefs/server.prefs';
    } else {
        return res.status(500).send('Unsupported OS - This has only been coded for Windows and Linux');
    }

    console.log("MAYBE failed to read FIle path to read:", filePath);

    fs.readFile(filePath, 'utf8', (err, data) => {
        if (err) return res.status(500).send('Error reading prefs file: ', err);

        // Find any mediadirs line
        const mediadirsLine = data.split('\n').find(line => line.includes('mediadirs:'));
        if (mediadirsLine) {
            console.log("Found mediadirs line:", mediadirsLine);
            res.json({ result: mediadirsLine });
        } else {
            res.status(404).send('mediadirs not found');
        }
    });
} else {
    res.status(400).send('Invalid request');
}

});

Doesn't work ^^

but for example, the code below which Writes to server.prefs does:

// ******************************************************************************
//                    ****  Rescan Folder Path Setting  ****
// *******************************************************************************
     if (params && params[1][0] === "pref" && params[1][1] === "mediadirs") {
        const newMediaDir = params[1][2];

        let filePath;
        if (os.platform() === 'win32' || os.platform() === 'win64') {
            filePath = path.join('C:', 'ProgramData', 'Squeezebox', 'prefs', 'server.prefs');
        } else if (os.platform() === 'linux') {
            filePath = '/var/lib/squeezeboxserver/prefs/server.prefs';
        } else {
            return res.status(500).send('Unsupported OS - This has only been coded for Windows and Linux');
        }

        fs.readFile(filePath, 'utf8', (err, data) => {
            if (err) return res.status(500).send('Error reading prefs file');

            // Replace the mediadirs line with the new directory
            const updatedData = data.replace(/mediadirs:\s*\S+/g, `mediadirs: ${newMediaDir}`);

            fs.writeFile(filePath, updatedData, (err) => {
                if (err) return res.status(500).send('Error updating prefs file');
                res.json({ result: 'Media directory updated successfully' });
            });
        });
    } else {
        res.status(400).send('Invalid request');
    }

And the client-side code:

// -------------  Rescan folder path -------------
function updateMediaDirSetting(folderPath) {
    const data = {
        id: 1,
        method: "slim.request",
        params: [0, ["pref", "mediadirs", folderPath]] 
    };

    fetch("http://161.29.197.94.localhost:9000/capstone/jsonrpc.js", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(data => {
        console.log("Media directory updated to:", data);
    })
    .catch(error => {
        console.error("Error updating media directory:", error);
    });
}

document.getElementById('allSongs').addEventListener('click', function() {
    // Create the JSON-RPC request to get the media directories
    const data = {
        id: 1,
        method: "slim.request",
        params: [0, ["pref", "mediadirs"]] 
    };

    fetch("http://161.29.197.94.localhost:9000/capstone/jsonrpc.js", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(data => {
        if (data.result) {
            const folderPath = data.result; // Get the directory path
            console.log("Media directory path:", folderPath);
        } else {
            console.error("No result found:", data);
        }
    })
    .catch(error => {
        console.error("Error fetching media directories:", error);
    });
});
Tasha53505 commented 2 months ago

As rescan button is now fixed (https://github.com/Tasha53505/159.356-capstone-project-group/issues/73) I should be able to implement this. it's on my to-do list. will try and look at today or tomorrow

Tasha53505 commented 1 month ago

Dynamic songs are now fixed. I added a redirection to the IFrame back to the Songs List. Home