Question:

How do I track a publicly downloaded file?

Easton: 5 days ago

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); 
  }

}

Answer:
Claire: 5 days ago

hook_file_download (https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21File%21file.api.php/function/hook_file_download/8.9.x) 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 (https://support.google.com/analytics/answer/1012044?hl=en#Download)