1

I am creating a custom module to track the file download time and user id with a file link or path. I have tried multiple modules but the download the file time tracking option is not available.

How I can programmatically track the file download time?

This is the code I am using.

function mymodule_file_download($uri) {
$scheme = \Drupal::service('file_system')->uriScheme($uri);
  if (in_array($scheme, ['private', 'temporary', 'session'])) {
    $permission = "read $scheme files";
    $current_user = \Drupal::currentUser();
    $account = $current_user->getAccount();
    if ($account->hasPermission($permission)) {
      return [
        'Content-Type: text/plain',
      ];
    }
  

    if (\Drupal::currentUser()->isAnonymous()) {
      throw new NotFoundHttpException();
   }

  }
  elseif (in_array($scheme, ['public'])){
    $current_user = \Drupal::currentUser();
    $account = $current_user->getAccount();
   \Drupal::logger('downloads_tracker1')->notice($account); 
  }

}
  • first you need to create a module and a schema that will hold your data , then you need to make eather a custom route that will redirect to the file and insert the time / user data in to that that table. – taggartJ Sep 15 at 22:03
  • I have already uploaded files in content type then why i need to create a custom route? – Adi Sep 16 at 6:46
  • Since the question is about code, we need to see the code you wrote so far. If you haven't written any code, you are asking the question too early. If you had a specific doubt about how to use a class/method/function, the question could be acceptable, as long as the question isn't too broad or subjective. – kiamlaluno Sep 16 at 9:29
  • 1
    You need custom code because there is nothing out of the box that will track metrics like this. Those metrics would be tracked in their own table. To trigger the behavior, you would need to serve the files from a particular route. – Kevin Sep 16 at 12:39
  • @kiamlaluno I have updated my question with code. – Adi Sep 16 at 20:45
0

hook_file_download doesn't run for public file downloads.

Control access to private file downloads and specify HTTP headers.

If you want to track public file downloads, you will need a different approach.

For example, track downloads with Google Analytics event tracking

| improve this answer | |
  • Thanks for your reply. Is there any way to do using custom code without google analytics event tracking? – Adi Sep 18 at 11:02
  • @Adi you would need to write your own javascript code to store the link click, otherwise some server logs may also show the request for the file. GA is just a bit easier and does that for you. – David Thomas 2 days ago

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.