Images not writing with my routines

I don’t think i understand this sorry hugs D

the ahr ajax doe not do this

All file and sql are places on the system by add_track.php , however for some reason fwrite( is not supported and sdoesnt work so I am forced to ftp the image up to server location in /images/nowplaying_artwork_2.png which produces no error

my function in /js/fetch_updater.js in the debugger is loaded and run bbut does not provide base 64 information I dont know why

function CheckResponse(transport)
{
    var content = transport.responseText;
    
    var image = document.createElement("img");
    image.src = 'http://www.deniserose.epizy.com/images/nowplaying_artwork_2.png';

    var base64file1;
   
    toDataURL("/images/nowplaying_artwork_2.png", function(data) {
        then(dataUrl => console.log('RESULT:', dataUrl));
        base64file1 = dataUrl;
        });
    
    //image.remove();
    //base64file1 = base64_encode(base64file1);
    //var base64file2 =  document.getElementById("outer_img").GetElementsById("np_track_artwork").src.data;
    var base64file2 = $("img#np_track_artwork").attr("src", "data:image/png;base64,"+data);
    
    if(base64file1 != base64file2) {
    

       
      gCurrentCheck = content;
       
      new Ajax.Request(gContentUrl, {
            method: "get",onSuccess:function t() { 
                this.document.getElementById(gUpdateDiv).innerHTML = t.responseText;  /*t.response.json()*/
            }
      });
      
      $time = new Date().getTime();
      new Ajax.Request("outer_img2", {
          method: "get",onSuccess:function s() { 
                this.document.getElementById("outer_img").innerHTML = "<img id=#np_track_artwork src=/images/nowplaying_artwork_2.png?t="+$time+" alt='Playing track artwork' width=200 height=200>"}
      });
    
    }
  
}

Additionally my main page reading from the sql database is loosing information

And here when refreshed after several songs looses the information in red and some songs there appear to be no integrity in data?

The data base shows Current selection does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available . But the time is for a unknow reason not unique suggesting its been changed when i run

ALTER TABLE epiz_33087480__song_history.played_songs DROP INDEX datetime, ADD PRIMARY KEY (datetime) USING BTREE;

I get

# Error

**SQL query:**

``

```
ALTER TABLE `epiz_33087480__song_history`.`played_songs` DROP INDEX `datetime`, ADD PRIMARY KEY (`datetime`) USING BTREE
```

**MySQL said:** [![Documentation](http://185.27.134.10/themes/dot.gif "Documentation")](http://185.27.134.10/url.php?url=https%3A%2F%2Fdev.mysql.com%2Fdoc%2Frefman%2F5.7%2Fen%2Ferror-messages-server.html)

`#1062 - Duplicate entry '2022-12-03 14:15:58' for key 'PRIMARY'`

I have deleted all data truncating it to put new primary key in

Exactly THAT is the complication!

instead of the client browser doing it…

What you are doing is the same as if someone has a security camera and uploads images through FTP here to the server (which is not allowed - too many connections to FTP)

I don’t know why album covers matter at all :slight_smile:

Here is my example of behavior:
I’m doing something on the computer and I want music to play along the way

I go to your page, press play, and minimize that window
and I continue to work on the computer

I don’t constantly look at your page or ask myself “hmm, I’m really interested in what kind of album cover this song has”

if I’m interested, I can find it on google.

what would be better in my opinion is if you have a history in the list (a song that was playing 5 minutes ago but is no longer visible because it has disappeared) so that if I like a song I can find it.

6 Likes

Everything I see here only strengthens my belief that this is just caused by browser cache. The fact that you could refresh the page to fetch the latest image means that the image has been correctly written to disk and is being served to the visitor browser if the browser requests this file, which it doesn’t because our hosting enforces quite strong browser cache by default.

I don’t see any evidence that your upload code is not working or that there is something wrong with the server storage.

The simplest way to fix this is to add a query parameter to the URL, and the easiest way to do this is through the PHP code. Simply having any query parameter will disabled caching functionality. So simply changing the code to this will result in browsers always downloading the latest image:

<img  src='images/nowplaying_artwork_2.png?version=latest' ...>

If you want to make it fancy and make sure you’re really getting a different URL each time, you could do it like this:

<img  src='images/nowplaying_artwork_2.png?t=<?= time() ?>' ...>

But again, this isn’t necessary because just having a query string disables all caching.


There are a lot of ways to make this nicer though.

The LastFM API recommendations are really cool additions to help you make sure you’ll have album art for all your tracks without having to manage the images yourself.

If you do want to mange the images yourself and still want to leverage browser cache, the most common way to do this is to simply store the images per song under a unique URL. So instead of storing every image as nowplaying_artwork_2.png, you could also store the image as pet-shop-boys-a-different-point-of-view.png or track-1234.png, where the current track depends on the results in the database.

5 Likes

My album data is fed else where

my update add record is as follows currently

<!DOCOTYPE html>
<head>
    <title>Add Record</title>
    <meta charset="UTF-8">
    
</head>
<?php
$servername = "sql111.epizy.com";
$username = "epiz_33087480";
$password = "";
$dbname = "epiz_33087480__song_history";


//uses https://www.ascii-code.com/
function _clean($clean) {
$clean = utf8_encode($clean); 
$array_find =    array("è",      "ê",      "é",   "(" , ")" ,   "," , "#" ,  "'" , "@" , ";" , ":" , "&",".");
$array_replace = array("e","&ecirc","&eacute","(",")","","&#35","&#39","@","&#59","&#58","&","&#46");
$cleaned  = str_replace( $array_find,$array_replace, $clean);
return $cleaned;
}

function clean_Num($num_cl) {
 return str_replace(array( "0","1","2","3","4","5","6","7","8","9"),array("\x00","\x01","\x02","\x03","\x04","\x05","\x06","\x07","\x08","\x09"),$str);
   
}
/*$bpm = $_REQUEST['bpm'];
$length =$_REQUEST['len'];
$artist = $_REQUEST['artist'];
$artist= _clean($artist);
$title = $_REQUEST['title'];
$title= _clean($title);
$album = $_REQUEST['album'];
$album= _clean( $album);
$comment  =$_REQUEST['comment'];
$comment= _clean($comment);
*/

//MSQ 8.0
 $bpm = /*isset(*/$_REQUEST['bpm'];//) : throw new \InvalidArgumentException('value not set bpm.');
 $length = /*isset(*/$_REQUEST['len'];// : throw new \InvalidArgumentException('value not set len.');
 $artist = /*isset(*/$_REQUEST['artist'];//) : throw new \InvalidArgumentException('value not set artist.');
$artist= _clean($artist);
$title = /*isset(*/$_REQUEST['title'];//) : throw new \InvalidArgumentException('value not set title.');
$title= _clean($title);
$album = /*isset(*/$_REQUEST['album'];//) : throw new \InvalidArgumentException('value not set album.');
$album= _clean( $album);
$comment = $_REQUEST['comment'];
$comment= _clean($comment);
$genre= $_REQUEST['genre'];
$listeners =  $_REQUEST['listeners'];

// Does not cater for ' " / 3 & in input ' presently.


// note there is now num_rows  in PDO so we have to calculate.
try {
  $n = 0;    
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $sql = "SELECT COUNT(`datetime`) FROM `played_songs` ORDER BY `datetime` ASC";
  $result = $conn->query($sql); // Use query as we are returning records.
  $row=$result->fetch();
  $n = $row["COUNT(`datetime`)"] - 150;
  if( $n >1) { $conn->exec("DELETE FROM `played_songs` LIMIT ".$n );}
  
} catch(PDOException $e) {
  echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
// Add record to database.
$base64="";
if($artwork2 !== false) {$base64 = base64_decode($artwork2);    
} else {
        ReturnError(500, 'Failed to write artwork to a file');
}

var image = document.createElement("img");
image.src = 'http://www.deniserose.epizy.com/images/nowplaying_artwork_2.png?tr=w-200,h-200'
$b64Data= base64_decode($artwork);
const byteCharacters = atob(b64Data);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], {type: contentType});

try {
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $datetime =date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME']);

   $sql = "INSERT INTO `played_songs` (`datetime`,`song`, `artist`, `album`, `length`, `bpm`, `listeners`,`track_user_num`,`track_user_rating`,`genre`,`comment`,`ImageBase64`) VALUES ('$datetime','$title','$artist', '$album', '$length', '$bpm','$listeners',0,0,'$genre', '$comment','blob')";
  $conn->exec($sql);
  echo "New record created successfully";
} catch(PDOException $e) {
  ReturnError(500, 'Failed to write artwork to a file'. $e->getMessage());
}
image.remove();
$conn = null;

//album cover
$artwork = isset($_REQUEST['artwork']) && ($_REQUEST['artwork'] !== '') ? $_REQUEST['artwork'] : false;
if ($artwork !== false) {
    $artwork = base64_decode($artwork);
    $r = fopen('images/nowplaying_artwork_2.png', 'wb');
    if ($r !== false) {
        fwrite($r, $artwork);
        fclose($r);
    } else {
        ReturnError(500, 'Failed to write artwork to a file');
    }
    
} else ReturnError(500, 'Failed to supply artwork in url');

function ReturnError($code, $text) {
    $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0';
    header($protocol . ' ' . $code . ' ' . $text);
    exit();
}

?>

The blob version is here but didnt work but its here

<!DOCOTYPE html>
<head>
    <title>Add Record</title>
    <meta charset="UTF-8">
    
</head>
<?php
$servername = "sql111.epizy.com";
$username = "epiz_33087480";
$password = "";
$dbname = "epiz_33087480__song_history";


//uses https://www.ascii-code.com/
function _clean($clean) {
$clean = utf8_encode($clean); 
$array_find =    array("è",      "ê",      "é",   "(" , ")" ,   "," , "#" ,  "'" , "@" , ";" , ":" , "&",".");
$array_replace = array("e","&ecirc","&eacute","(",")","","&#35","&#39","@","&#59","&#58","&","&#46");
$cleaned  = str_replace( $array_find,$array_replace, $clean);
return $cleaned;
}

function clean_Num($num_cl) {
 return str_replace(array( "0","1","2","3","4","5","6","7","8","9"),array("\x00","\x01","\x02","\x03","\x04","\x05","\x06","\x07","\x08","\x09"),$str);
   
}
/*$bpm = $_REQUEST['bpm'];
$length =$_REQUEST['len'];
$artist = $_REQUEST['artist'];
$artist= _clean($artist);
$title = $_REQUEST['title'];
$title= _clean($title);
$album = $_REQUEST['album'];
$album= _clean( $album);
$comment  =$_REQUEST['comment'];
$comment= _clean($comment);
*/

//MSQ 8.0
 $bpm = /*isset(*/$_REQUEST['bpm'];//) : throw new \InvalidArgumentException('value not set bpm.');
 $length = /*isset(*/$_REQUEST['len'];// : throw new \InvalidArgumentException('value not set len.');
 $artist = /*isset(*/$_REQUEST['artist'];//) : throw new \InvalidArgumentException('value not set artist.');
$artist= _clean($artist);
$title = /*isset(*/$_REQUEST['title'];//) : throw new \InvalidArgumentException('value not set title.');
$title= _clean($title);
$album = /*isset(*/$_REQUEST['album'];//) : throw new \InvalidArgumentException('value not set album.');
$album= _clean( $album);
$comment = $_REQUEST['comment'];
$comment= _clean($comment);
$genre= $_REQUEST['genre'];
$listeners =  $_REQUEST['listeners'];

// Does not cater for ' " / 3 & in input ' presently.


// note there is now num_rows  in PDO so we have to calculate.
try {
  $n = 0;    
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $sql = "SELECT COUNT(`datetime`) FROM `played_songs` ORDER BY `datetime` ASC";
  $result = $conn->query($sql); // Use query as we are returning records.
  $row=$result->fetch();
  $n = $row["COUNT(`datetime`)"] - 150;
  if( $n >1) { $conn->exec("DELETE FROM `played_songs` LIMIT ".$n );}
  
} catch(PDOException $e) {
  echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
// Add record to database.
$base64="";
if($artwork2 !== false) {$base64 = base64_decode($artwork2);    
} else {
        ReturnError(500, 'Failed to write artwork to a file');
}

var image = document.createElement("img");
image.src = 'http://www.deniserose.epizy.com/images/nowplaying_artwork_2.png?tr=w-200,h-200'
$b64Data= base64_decode($artwork);
const byteCharacters = atob(b64Data);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], {type: contentType});

try {
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $datetime =date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME']);

   $sql = "INSERT INTO `played_songs` (`datetime`,`song`, `artist`, `album`, `length`, `bpm`, `listeners`,`track_user_num`,`track_user_rating`,`genre`,`comment`,`ImageBase64`) VALUES ('$datetime','$title','$artist', '$album', '$length', '$bpm','$listeners',0,0,'$genre', '$comment','blob')";
  $conn->exec($sql);
  echo "New record created successfully";
} catch(PDOException $e) {
  ReturnError(500, 'Failed to write artwork to a file'. $e->getMessage());
}
image.remove();
$conn = null;

//album cover
$artwork = isset($_REQUEST['artwork']) && ($_REQUEST['artwork'] !== '') ? $_REQUEST['artwork'] : false;
if ($artwork !== false) {
    $artwork = base64_decode($artwork);
    $r = fopen('images/nowplaying_artwork_2.png', 'wb');
    if ($r !== false) {
        fwrite($r, $artwork);
        fclose($r);
    } else {
        ReturnError(500, 'Failed to write artwork to a file');
    }
    
} else ReturnError(500, 'Failed to supply artwork in url');

function ReturnError($code, $text) {
    $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0';
    header($protocol . ' ' . $code . ' ' . $text);
    exit();
}

?>

It should work but doesn’t its behaving a l little better but still no refresh see below

Thank you admin
I am already doing this but the java script is not working on your site in my file js/fetch_updater.js so it never fires up properly only to run and do nothing as the return of the base64 is not being returned but gives result in debugger ‘Unidentified’ meaning i have no data to compare what is on screen to what is on file. I should point out my add_track.php reports no error

Thank you Admin , I put in <img src='images/nowplaying_artwork_2.png?t=<?php echo time();?> id=‘np_track_artwork’ i now refreshes the image when you refresh the page but the fetch is stll not updating it not returning base64 data from screen and from server copy

in regard to my blob version of Add_track fails but not on the command line
I am wondering if this is better practice to create record then upload blob to sql by amending record?

Just looking at the way you are doing this, I think it will immediately start returning incorrect album covers as soon as more than one person is using the website at the same time.

2 Likes

xhr ajax looks you done already.
I remember now to get toDataUrl working need to add onload ev on method i told before.

= New Ajax.request
Need to checked it out later. Works or not.

<!DOCTYPE html>
<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <meta http-equiv="X-UA-Compatible" content="IE=9" />
   <meta name="viewport" content="width=device-width, initial-scale=1">
   	
   <script type="text/javascript" src="src/js/jquery-3.4.1.min.js"></script>
</head>
<body>
	<img id="img_artwork" width="220" height="277"
src="http://viena.lovestoblog.com/imgEdit/img/edwin.jpg" alt="Lesson">
	<script>
  
  function process() {
	alert("start");
    //var image = document.createElement("img");
    //image.src = 'http://viena.lovestoblog.com/imgEdit/img/nowplaying_artwork_2.png';
    //var base64file1;
    //image.remove();
   
   data=document.getElementById("export").value;
   alert(data);
    var base64file2 = data;
    $("#img_artwork").attr("src", base64file2);
    
    alert("ok");
}
</script>

<h1>HTML DOM Events</h1>
<h2>The onclick Event</h2>

<p>The onclick event triggers a function when an element is clicked on.</p>
<p>Click to trigger a function that will output "Hello World":</p>

<button onclick="myFunction()">Click me</button>
<button onclick="p1()">img Click me</button><br>

<button onclick="process()">Process</button>
<input onkeypress="process()" type="text" id="export" name="export">

<p id="demo"></p>

<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "Hello World";
}

function p1() {
	alert("00");
  const toDataURL = url => fetch(url)
  .then(response => response.blob())
  .then(blob => new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onloadend = () => resolve(reader.result)
    reader.onerror = reject
    reader.readAsDataURL(blob)
  }))
  alert("11");

toDataURL('http://viena.lovestoblog.com/imgEdit/img/nowplaying_artwork_2.png')
  .then(dataUrl => {
    console.log('RESULT:', dataUrl)
    document.getElementById("export").value = dataUrl;
  })
  
  alert("ok");
}

function px() {
	alert("00");
  const toDataURL = url => fetch(url)
  .then(response => response.blob())
  .then(blob => new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onloadend = () => resolve(reader.result)
    reader.onerror = reject
    reader.readAsDataURL(blob)
  }))

  alert("ok");
}


</script>

</body>
</html>

no. Its the reverse. So take a look of your timer decay. As you requested its all working before.


Where is your decay function i don’t see it anymore.

OK, yes, the background update of the image isn’t affected by this.

I’m not exactly sure how browser cache and AJAX work together.

I would test it, but the fetch_updater.js because of a Uncaught SyntaxError: illegal character U+2018 on fetch_updater.js:103:31. That line renders as var startDate = new Date(‘1/1/2019’); // this, which doesn’t seem OK.

I browser cache with AJAX works the same as without, then adding any query parameter to the fetch URL should solve it. The elapsed time code you have right now should do the trick, but it seems like you’ve tried a lot of different things so I’m not sure if the code is being hit properly.


Also, having file names per track would really help with this too, then you can just use Javascript to update the image src attribute and the browser will load in the new image. Might be a bit easier than downloading it through Ajax.

3 Likes

Fabulous detective work Admin i wish it had better syntax editor in the editor. I will et you know what happens to update have just removed single quotes replacing with double. I hope it solves this .

The weird thing my cloud is still showing old code how do i clear this in debuger please to get a fresh look ?

Hugs D

I don’t think its getting the base64 still Admin

Let’s keep the discussion in this topic since that’s where most of the posts are in:

4 Likes