<?php

/*
downloadToFile($arguments["downloadmedia"], $arguments["fileout"], $arguments["offset"]);
use offset to download only 10 frames or so...

https://docs.madelineproto.xyz/API_docs/methods/upload.getFile.html

yum install mediainfo -y -- use in centosprepare

check for mediainfo @ bot 

downloadToFile() -> FLOOD_PREMIUM_WAIT_11 - in exceptions.inc.php fixed...
-> with madeline 8.3.0 fixed 


$output_file_name = $MadelineProto->downloadToFile(
    $sentMessage,
    new \danog\MadelineProto\FileCallback(
        '/tmp/myname.mp4',
        function ($progress, $speed, $time) use ($MadelineProto, $peer) {
            try {
                $MadelineProto->messages->sendMessage(['peer' => $peer, 'message' => "Download progress: $progress%\nSpeed: $speed mbps\nTime elapsed since start: $time"]);
            } catch (\Throwable $e) {}
        }
    )
);

--> https://docs.madelineproto.xyz/docs/FILES.html#download-to-file


*/


function download($link, $option = null) {
 global $channelInfoNew, $globalsettings;
 // in $option = reupload (?) - reload destination: admin channel - not yet

 $channel=explode("/",$link)[4];
 $peerchannel="-100".$channel;
 
 if (!array_key_exists(5, explode("/", $link))) {
   echo "non valid link \n"; return;
 } // if (!array_key_exists(5, $link)) 
 
 $msgid=explode("/",$link)[5];
 $fileout=$globalsettings["bot"]["downloaddirectory"]."/";
 
 if (asearch($peerchannel, $globalsettings["channels"]["channeldb"])) { 
  $message=made("channels", "getMessages", array("channel" => "-100".$channel, "id" => array($msgid)));
  $downloadmedia=$message['messages'][0]['media'];
  
  $filename=getMessageMediaAttributes($message['messages'][0]["media"]["document"]["attributes"])["filename"];
  $fileout.=$filename;

  made("messages", "sendMessage", array("peer" => $globalsettings["bot"]["pandaownerid"], "message" => "- try download: ".$filename."<br>", "parse_mode" => "html"));

  if (file_exists($fileout)) {
   made("messages", "sendMessage", array("peer" => $globalsettings["bot"]["pandaownerid"], "message" => "❌ file: ".$filename." already exists<br>", "parse_mode" => "html"));	  
   return;
  } 

  $downloadreturn = made("","downloadToFile()", array("downloadmedia" => $downloadmedia, "fileout" => $fileout));
  
  made("messages", "sendMessage", array("peer" => $globalsettings["bot"]["pandaownerid"], "message" => "- download done: ".$filename."<br>", "parse_mode" => "html"));

 } else { 
  $sendmessage="u are not on channel";

  echo $sendmessage."\n"; 
  made("messages", "sendMessage", array("peer" => $globalsettings["bot"]["pandaownerid"], "message" => $sendmessage, "parse_mode" => "html"));
 } // if (asearch($channel, $globalsettings["channels"]["channeldb"]))
} // function end