FileUpload.vue 11 KB
Newer Older
1
2
3
  <template>
  <div>
    <div class="ui top attached tabular menu">
4
      <a :class="['item', {active: currentTab === 'summary'}]" @click="currentTab = 'summary'"><translate>Summary</translate></a>
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
      <a :class="['item', {active: currentTab === 'uploads'}]" @click="currentTab = 'uploads'">
        <translate>Uploading</translate>
        <div v-if="files.length === 0" class="ui label">
          0
        </div>
        <div v-else-if="files.length > uploadedFilesCount + erroredFilesCount" class="ui yellow label">
          {{ uploadedFilesCount + erroredFilesCount }}/{{ files.length }}
        </div>
        <div v-else :class="['ui', {'green': erroredFilesCount === 0}, {'red': erroredFilesCount > 0}, 'label']">
          {{ uploadedFilesCount + erroredFilesCount }}/{{ files.length }}
        </div>
      </a>
      <a :class="['item', {active: currentTab === 'processing'}]" @click="currentTab = 'processing'">
        <translate>Processing</translate>
        <div v-if="processableFiles === 0" class="ui label">
          0
        </div>
        <div v-else-if="processableFiles > processedFilesCount" class="ui yellow label">
          {{ processedFilesCount }}/{{ processableFiles }}
        </div>
Eliot Berriot's avatar
Eliot Berriot committed
25
        <div v-else :class="['ui', {'green': uploads.errored === 0}, {'red': uploads.errored > 0}, 'label']">
26
27
28
29
          {{ processedFilesCount }}/{{ processableFiles }}
        </div>
      </a>
    </div>
30
31
32
33
34
35
36
37
38
39
40

    <div :class="['ui', 'bottom', 'attached', 'segment', {hidden: currentTab != 'summary'}]">
      <h2 class="ui header"><translate>Upload new tracks</translate></h2>
      <div class="ui message">
        <p><translate>You are about to upload music to your library. Before proceeding, please ensure that:</translate></p>
        <ul>
          <li v-if="library.privacy_level != 'me'">
            You are not uploading copyrighted content in a public library, otherwise you may be infringing the law
          </li>
          <li>
            <translate>The music files you are uploading are tagged properly:</translate>
Allan Nordhøy's avatar
Allan Nordhøy committed
41
            <a href="http://picard.musicbrainz.org/" target='_blank'><translate>We recommend using Picard for that purpose.</translate></a>
42
43
44
45
46
47
48
49
50
51
52
53
          </li>
          <li>
            <translate>The uploaded music files are in OGG, Flac or MP3 format</translate>
          </li>
        </ul>
      </div>

      <div class="ui form">
        <div class="fields">
          <div class="ui four wide field">
            <label><translate>Import reference</translate></label>
            <p><translate>This reference will be used to group imported files together.</translate></p>
54
            <input name="import-ref" type="text" v-model="importReference" />
55
56
57
58
59
60
          </div>
        </div>

      </div>
      <div class="ui green button" @click="currentTab = 'uploads'"><translate>Proceed</translate></div>
    </div>
61
62
63
64
65
66
67
68
    <div :class="['ui', 'bottom', 'attached', 'segment', {hidden: currentTab != 'uploads'}]">
      <div class="ui container">
        <file-upload-widget
          :class="['ui', 'icon', 'basic', 'button']"
          :post-action="uploadUrl"
          :multiple="true"
          :data="uploadData"
          :drop="true"
69
          :extensions="supportedExtensions"
70
71
72
73
74
          v-model="files"
          name="audio_file"
          :thread="1"
          @input-file="inputFile"
          ref="upload">
75
          <i class="upload icon"></i>&nbsp;
76
          <translate>Click to select files to upload or drag and drop files or directories</translate>
77
78
79
          <br />
          <br />
          <i><translate :translate-params="{extensions: supportedExtensions.join(', ')}">  Supported extensions: %{ extensions }</translate></i>
80
81
82
83
84
        </file-upload-widget>
      </div>
      <table v-if="files.length > 0" class="ui single line table">
        <thead>
          <tr>
Allan Nordhøy's avatar
Allan Nordhøy committed
85
            <th><translate>Filename</translate></th>
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
            <th><translate>Size</translate></th>
            <th><translate>Status</translate></th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(file, index) in sortedFiles" :key="file.id">
            <td :title="file.name">{{ file.name | truncate(60) }}</td>
            <td>{{ file.size | humanSize }}</td>
            <td>
              <span v-if="file.error" class="ui tooltip" :data-tooltip="labels.tooltips[file.error]">
                <span class="ui red icon label">
                  <i class="question circle outline icon" /> {{ file.error }}
                </span>
              </span>
              <span v-else-if="file.success" class="ui green label">
                <translate key="1">Uploaded</translate>
              </span>
              <span v-else-if="file.active" class="ui yellow label">
Allan Nordhøy's avatar
Allan Nordhøy committed
104
                <translate key="2">Uploading…</translate>
105
                ({{ parseInt(file.progress) }}%)
106
107
108
109
110
111
112
113
114
115
116
117
118
              </span>
              <template v-else>
                <span class="ui label"><translate key="3">Pending</translate></span>
                <button class="ui tiny basic red icon button" @click.prevent="$refs.upload.remove(file)"><i class="delete icon"></i></button>
              </template>
            </td>
          </tr>
        </tbody>
      </table>

    </div>
    <div :class="['ui', 'bottom', 'attached', 'segment', {hidden: currentTab != 'processing'}]">
      <library-files-table
119
120
        :needs-refresh="needsRefresh"
        @fetch-start="needsRefresh = false"
121
        :filters="{import_reference: importReference}"
Eliot Berriot's avatar
Eliot Berriot committed
122
        :custom-objects="Object.values(uploads.objects)"></library-files-table>
123
124
125
126
127
    </div>
  </div>
</template>

<script>
128
import _ from "@/lodash"
129
130
131
132
133
134
import $ from "jquery";
import axios from "axios";
import logger from "@/logging";
import FileUploadWidget from "./FileUploadWidget";
import LibraryFilesTable from "@/views/content/libraries/FilesTable";
import moment from "moment";
135
136

export default {
137
  props: ["library", "defaultImportReference"],
138
139
140
141
  components: {
    FileUploadWidget,
    LibraryFilesTable
  },
142
143
144
  data() {
    let importReference = this.defaultImportReference || moment().format();
    this.$router.replace({ query: { import: importReference } });
145
146
    return {
      files: [],
147
      needsRefresh: false,
148
      currentTab: "summary",
149
      uploadUrl: this.$store.getters['instance/absoluteUrl']("/api/v1/uploads/"),
150
      importReference,
151
      supportedExtensions: ["flac", "ogg", "mp3", "opus"],
Eliot Berriot's avatar
Eliot Berriot committed
152
      uploads: {
153
154
155
156
        pending: 0,
        finished: 0,
        skipped: 0,
        errored: 0,
157
        objects: {}
158
159
      },
      processTimestamp: new Date()
160
    };
161
  },
162
163
164
165
166
  created() {
    this.fetchStatus();
    this.$store.commit("ui/addWebsocketEventHandler", {
      eventName: "import.status_updated",
      id: "fileUpload",
167
      handler: this.handleImportEvent
168
    });
169
    window.onbeforeunload = e => this.onBeforeUnload(e);
170
  },
171
172
173
174
175
  destroyed() {
    this.$store.commit("ui/removeWebsocketEventHandler", {
      eventName: "import.status_updated",
      id: "fileUpload"
    });
176
    window.onbeforeunload = null;
177
178
  },
  methods: {
179
180
181
182
183
184
185
186
    onBeforeUnload(e = {}) {
      const returnValue = ('This page is asking you to confirm that you want to leave - data you have entered may not be saved.');
      if (!this.hasActiveUploads) return null;
      Object.assign(e, {
        returnValue,
      });
      return returnValue;
    },
187
188
    inputFile(newFile, oldFile) {
      this.$refs.upload.active = true;
189
    },
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
    fetchStatus() {
      let self = this;
      let statuses = ["pending", "errored", "skipped", "finished"];
      statuses.forEach(status => {
        axios
          .get("uploads/", {
            params: {
              import_reference: self.importReference,
              import_status: status,
              page_size: 1
            }
          })
          .then(response => {
            self.uploads[status] = response.data.count;
          });
      });
206
    },
207
208
209
210
211
212
213
    updateProgressBar() {
      $(this.$el)
        .find(".progress")
        .progress({
          total: this.uploads.length * 2,
          value: this.uploadedFilesCount + this.finishedJobs
        });
214
    },
215
216
    handleImportEvent(event) {
      let self = this;
Eliot Berriot's avatar
Eliot Berriot committed
217
      if (event.upload.import_reference != self.importReference) {
218
        return;
219
      }
220
      this.$nextTick(() => {
221
222
        self.uploads[event.old_status] -= 1;
        self.uploads[event.new_status] += 1;
223
224
        self.uploads.objects[event.upload.uuid] = event.upload;
        self.needsRefresh = true
225
      });
226
    }
227
228
  },
  computed: {
229
230
    labels() {
      let denied = this.$gettext(
Allan Nordhøy's avatar
Allan Nordhøy committed
231
        "Upload denied, ensure the file is not too big and that you have not reached your quota"
232
233
      );
      let server = this.$gettext(
Allan Nordhøy's avatar
Allan Nordhøy committed
234
        "Cannot upload this file, ensure it is not too big"
235
236
237
238
239
240
241
242
      );
      let network = this.$gettext(
        "A network error occured while uploading this file"
      );
      let timeout = this.$gettext("Upload timeout, please try again");
      let extension = this.$gettext(
        "Invalid file type, ensure you are uploading an audio file. Supported file extensions are %{ extensions }"
      );
243
244
245
246
247
      return {
        tooltips: {
          denied,
          server,
          network,
248
249
250
251
          timeout,
          extension: this.$gettextInterpolate(extension, {
            extensions: this.supportedExtensions.join(", ")
          })
252
        }
253
      };
254
    },
255
256
257
258
    uploadedFilesCount() {
      return this.files.filter(f => {
        return f.success;
      }).length;
259
    },
260
261
262
263
    uploadingFilesCount() {
      return this.files.filter(f => {
        return !f.success && !f.error;
      }).length;
264
    },
265
266
267
268
    erroredFilesCount() {
      return this.files.filter(f => {
        return f.error;
      }).length;
269
    },
270
271
272
273
274
275
276
277
    processableFiles() {
      return (
        this.uploads.pending +
        this.uploads.skipped +
        this.uploads.errored +
        this.uploads.finished +
        this.uploadedFilesCount
      );
278
    },
279
280
281
282
    processedFilesCount() {
      return (
        this.uploads.skipped + this.uploads.errored + this.uploads.finished
      );
283
    },
284
    uploadData: function() {
285
      return {
286
287
288
        library: this.library.uuid,
        import_reference: this.importReference
      };
289
    },
290
    sortedFiles() {
291
      // return errored files on top
292
293
294

      return _.sortBy(this.files.map(f => {
        let statusIndex = 0
295
        if (f.errored) {
296
          statusIndex = -1
297
298
        }
        if (f.success) {
299
          statusIndex = 1
300
        }
301
302
303
        f.statusIndex = statusIndex
        return f
      }), ['statusIndex', 'name'])
304
305
306
    },
    hasActiveUploads () {
      return this.sortedFiles.filter((f) => { return f.active }).length > 0
307
308
309
    }
  },
  watch: {
310
311
    uploadedFilesCount() {
      this.updateProgressBar();
312
    },
313
314
    finishedJobs() {
      this.updateProgressBar();
315
    },
316
317
    importReference: _.debounce(function() {
      this.$router.replace({ query: { import: this.importReference } });
318
319
    }, 500)
  }
320
};
321
322
323
324
325
326
327
328
329
330
331
332
333
334
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.file-uploads.ui.button {
  display: block;
  padding: 2em 1em;
  width: 100%;
  box-shadow: none;
  border-style: dashed !important;
  border: 3px solid rgba(50, 50, 50, 0.5);
  font-size: 1.5em;
}
</style>