Refresh attachments with virus scan result

This commit is contained in:
Paul Chavard 2019-05-21 14:21:55 +02:00
parent cc4eba2b36
commit 6a3413018a
5 changed files with 86 additions and 0 deletions

View file

@ -0,0 +1,9 @@
class AttachmentsController < ApplicationController
before_action :authenticate_logged_user!
include ActiveStorage::SetBlob
def show
@attachment = @blob.attachments.find(params[:id])
@user_can_upload = params[:user_can_upload]
end
end

View file

@ -9,6 +9,7 @@ import ReactUJS from '../shared/react-ujs';
import reactComponents from '../shared/react-components';
import '../shared/activestorage/ujs';
import '../shared/activestorage/attachment-checker';
import '../shared/rails-ujs-fix';
import '../shared/safari-11-file-xhr-workaround';
import '../shared/autocomplete';

View file

@ -0,0 +1,66 @@
import Rails from 'rails-ujs';
addEventListener('turbolinks:load', () => {
checker.deactivate();
const attachments = document.querySelectorAll('[data-attachment-check-url]');
for (let attachment of attachments) {
checker.add(attachment.dataset.attachmentCheckUrl);
}
});
addEventListener('attachment:update', ({ detail: { url } }) => {
checker.add(url);
});
class AttachmentChecker {
urls = new Set();
timeout;
checks = 0;
constructor(settings = {}) {
this.interval = settings.interval || 5000;
this.maxChecks = settings.maxChecks || 5;
}
get isEnabled() {
return this.checks <= this.maxChecks;
}
get isActive() {
return this.timeout !== undefined;
}
add(url) {
if (this.isEnabled) {
if (!this.isActive) {
this.activate();
}
this.urls.add(url);
}
}
activate() {
this.timeout = setTimeout(() => {
for (let url of this.urls) {
Rails.ajax({ url, type: 'get' });
}
this.checks++;
this.reset();
}, this.interval);
}
deactivate() {
this.checks = 0;
this.reset();
}
reset() {
clearTimeout(this.timeout);
this.urls = new Set();
this.timeout = undefined;
}
}
const checker = new AttachmentChecker();

View file

@ -0,0 +1,8 @@
<%= render_to_element(".pj-link[data-attachment-id=\"#{@attachment.id}\"]",
partial: 'shared/attachment/show',
outer: true,
locals: { attachment: @attachment, user_can_upload: @user_can_upload }) %>
<% if @attachment.virus_scanner.pending? %>
<%= fire_event('attachment:update', { url: attachment_url(@attachment.id, { signed_id: @attachment.blob.signed_id, user_can_upload: @user_can_upload }) }.to_json ) %>
<% end %>

View file

@ -133,6 +133,8 @@ Rails.application.routes.draw do
post ':position/repetition', to: 'repetition#show', as: :repetition
end
get 'attachments/:id', to: 'attachments#show', as: :attachment
get 'tour-de-france' => 'root#tour_de_france'
get "patron" => "root#patron"
get "accessibilite" => "root#accessibilite"