Files.vue 22 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<template>
  <div>
    <!-- Only display a spinner if the files are not loaded yet -->
    <div v-if="!loaded.files">
      <b-row>
        <b-col align="center">
          <img
            src="../../assets/radio.gif"
            alt="loading data"
          >
        </b-col>
      </b-row>
    </div>

    <!-- If all file data is loaded we can present an upload button and
    a table of files (if there are already any or if there are any already
    being uploaded/imported )-->
    <div v-else>
      <!-- Modal: Add new file
      This is the modal that is used when the user clicks on the
      "Upload or add a file" button. When the user hits the OK button,
      the addFile method will be called. -->
      <b-modal
        id="modal-add-file"
25
        ref="modalAddFile"
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
        title="Add new file"
        @ok="addFile"
      >
        <!-- If the checkbox below is checked we only need a simple input
        for entering an URI, instead of a complete file upload dialogue -->
        <div v-if="addNewFileURI">
          <b-row>
            <b-col md="2">
              <b>Link:</b>
            </b-col>
            <b-col>
              <b-form-input
                v-model="uploadSourceURI"
                type="url"
                placeholder="Insert a HTTP(S) link here"
              />
            </b-col>
          </b-row>
        </div>
        <!-- If the checkbox is not checked, we provide a file selection
        dialogue instead of a simple input for an URI -->
        <div v-else>
          <b-form-file
            v-model="uploadSourceFile"
            accept="audio/*"
            placeholder="Choose a file..."
            drop-placeholder="Drop file here..."
          />
        </div>

        <hr>

        <!-- This checkbox determines whether there is just a simple input
        or a file selection dialogue (see above) -->
        <div align="center">
          <b-form-checkbox
            v-model="addNewFileURI"
            value="true"
            unchecked_value="false"
          >
            Download from remote source instead of uploading a file
          </b-form-checkbox>
        </div>
      </b-modal>

      <!-- Modal: Edit meta information
      This modal lets the user change a file's meta information (artist,
      album, title). When the user hits OK, the saveFile method is called.
      -->
      <b-modal
        id="modal-edit-file"
77
        ref="modalEditFile"
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
        title="Edit meta information"
        size="lg"
        @ok="saveFile"
      >
        <!-- Input element: Artist -->
        <b-row>
          <b-col md="2">
            Artist:
          </b-col>
          <b-col>
            <b-form-input
              v-model="filemeta.artist"
              type="text"
            />
          </b-col>
        </b-row>

        <!-- Input element: Album -->
        <b-row>
          <b-col md="2">
            Album:
          </b-col>
          <b-col>
            <b-form-input
              v-model="filemeta.album"
              type="text"
            />
          </b-col>
        </b-row>

        <!-- Input element: Title -->
        <b-row>
          <b-col md="2">
            Title:
          </b-col>
          <b-col>
            <b-form-input
              v-model="filemeta.title"
              type="text"
            />
          </b-col>
        </b-row>

        <hr>

        <!-- As additional orientation we provide the source this file was
        uploaded/imported from. This might help the user to manage all files
        and set the meta information accordingly.
        -->
        <b-row>
          <b-col md="2">
            Sourced from:
          </b-col>
          <b-col>{{ filemeta.uri }}</b-col>
        </b-row>
      </b-modal>

      <!-- Now for the files. If there are none yet, just show an alert and
      a button for uploading/importing a new file -->
      <div
        v-if="files.length === 0"
        align="center"
      >
        <b-alert
          show
          variant="warning"
        >
          There are no files for this show yet.
        </b-alert>
        <b-button
          v-b-modal.modal-add-file
          variant="success"
        >
          Upload or add a file
        </b-button>
      </div>

      <!-- If there already are files for this show we'll show the button
      for uploading/importing a new file and then a table with all files -->
      <div v-else>
        <!-- This is the button -->
        <div
          align="center"
          style="padding-bottom: 1.5em;"
        >
          <b-button
            v-b-modal.modal-add-file
            variant="success"
          >
            Upload or add a file
          </b-button>
        </div>

        <!-- We also import the modal for showing file import logs here -->
172
        <import-log ref="importLog" />
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259

        <!-- And here comes the table -->
        <b-table
          ref="filesTable"
          striped
          :fields="filesTableFields"
          :items="files"
        >
          <!-- The first two columns in the table (Index & Artist) are filled
          in automatically, because we do not use these fields for displaying
          upload/import progress information.
          -->

          <!-- Column: Album
          This column displays either the album meta information or, in case
          the file is just being uploaded/imported, a spinner visualising an
          ongoing import.
          -->
          <template v-slot:cell(metadata.album)="data">
            <span v-if="data.item.source.import.state === 'aborted'"><b-badge variant="danger">Error:</b-badge></span>
            <span v-else-if="data.item.source.import.state !== 'done'"><img
              src="../../assets/radio.gif"
              width="24"
              alt="loading data"
            ></span>
            <span v-else>{{ data.value }}</span>
          </template>

          <!-- Column: Title
          This column displays either the title meta information or, in case
          the file is just being uploaded/imported, the current phase
          of the ongoing import (fetching or normalizing).
          -->
          <template v-slot:cell(metadata.title)="data">
            <span v-if="data.item.source.import.state === 'done'">{{ data.value }}</span>
            <span v-else-if="data.item.source.import.state === 'aborted'">import was aborted</span>
            <span v-else-if="data.item.source.import.progress !== undefined">{{ data.item.source.import.progress.step }} :</span>
          </template>

          <!-- Column: Duration
          This column displays either the duration of the audio file, or, if
          the file is just being uploaded/imported, the current progress.
          -->
          <template v-slot:cell(duration)="data">
            <!-- In case the import is already done just print a pretty duration -->
            <div v-if="data.item.source.import.state === 'done'">
              {{ prettyNanoseconds(data.value) }}
            </div>
            <!-- If the import was aborted show some error info -->
            <div v-else-if="data.item.source.import.state === 'aborted'">
              {{ data.item.source.import.error }}
            </div>
            <!-- Or print the progress for ongoing imports. We use the variant
            prop of the b-progress to display the bar in different colours -
            either the info variant for the fetching phase or the success
            variant for the normalizing phase -->
            <div v-else-if="data.item.source.import.progress !== undefined">
              <b-progress
                :value="data.item.source.import.progress.progress"
                :max="1"
                show-progress
                :variant="data.item.source.import.progress.step === 'fetching' ? 'info' : 'success'"
                animated
              />
            </div>
          </template>

          <!-- Column: Size
          This column displays the size of the audio file, if the file is
          already fully imported. Otherwise we'll just leave it empty.
          -->
          <template v-slot:cell(size)="data">
            <span v-if="data.item.source.import.state === 'done'">{{ prettyFileSize(data.value) }}</span>
          </template>

          <!-- Column: Actions
          This column displays the available button for actions  the user can
          take on this file (e.g. editing and deleting).
          -->
          <template v-slot:cell(actions)="data">
            <b-button-group size="sm">
              <b-button @click="editFile(data.item.id)">
                Edit
              </b-button>
              <b-button
                v-b-tooltip.hover
                title="Show import log"
260
                @click="$refs.importLog.openModal(data.item.id)"
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
              >
                &#128220;
              </b-button>
              <b-button
                variant="danger"
                @click="deleteFile(data.item.id)"
              >
                Delete
              </b-button>
            </b-button-group>
          </template>
        </b-table>
      </div>
      <!-- End of files table -->
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import axios from 'axios'
import filesize from 'filesize'
import prettyDate from '../../mixins/prettyDate'
284
import importLog from './ImportLog.vue'
285
286
287
288

export default {
  // include the modal for displaying file import logs
  components: {
289
    'import-log': importLog,
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
  },

  mixins: [ prettyDate ],

  data () {
    return {
      // those are used for the modal to add a new file
      addNewFileURI: false,
      uploadSourceURI: '',
      uploadSourceFile: null,

      // we need this for the modal to edit a file's meta information
      filemeta: {
        id: null,
        artist: '',
        album: '',
        title: ''
      },

      // to poll the progress info of a running update we need an interval
      uploadInterval: null,

      // configuration of the files table, which will use the files array as data
      filesTableFields: [
        { key: 'id', label: 'Index' },
        { key: 'metadata.artist', label: 'Artist' },
        { key: 'metadata.album', label: 'Album' },
        { key: 'metadata.title', label: 'Title' },
        { key: 'duration', label: 'Duration' },
        { key: 'size', label: 'Size' },
        { key: 'actions', label: 'Actions', class: 'text-right' },
      ],

    }
  },

  computed: {
    loaded () {
      return {
        files: this.$store.state.files.loaded.files,
      }
    },

    ...mapGetters({
      selectedShow: 'shows/selectedShow',
335
336
      files: 'files/files',
      getFileById: 'files/getFileById',
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
    })
  },

  methods: {
    // We want to have a nice format for the file size, given a size in Bytes.
    // For that we're useing the filesize npm module.
    prettyFileSize: function (s) {
      return filesize(s)
    },

    // To start modifying the meta information for a file we have to set our
    // temporary data (which will be used to check if anything changed) and
    // then open the editing modal
    editFile: function (id) {
      var file = this.getFileById(id)
      this.filemeta.id = file.id
      this.filemeta.artist = file.metadata.artist
      this.filemeta.album = file.metadata.album
      this.filemeta.title = file.metadata.title
      this.filemeta.uri = file.source.uri
      this.$bvModal.show('modal-edit-file')
    },

360
361
362
363
    saveFile: function (event){
      event.preventDefault()
      let modal = this.$refs.modalEditFile
      let file = this.getFileById(this.filemeta.id)
364
      if (this.filemeta.artist !== file.metadata.artist || this.filemeta.album !== file.metadata.album || this.filemeta.title !== file.metadata.title ) {
365
366
367
368
369
370
371
372
373
        this.$store.dispatch('files/updateFile', {
          show: this.selectedShow.slug,
          file: this.filemeta.id,
          metadata: {
            artist: this.filemeta.artist ? this.filemeta.artist : null,
            album: this.filemeta.album ? this.filemeta.album : null,
            title: this.filemeta.title ? this.filemeta.title : null
          },
          callback: () => { modal.hide() }
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
        })
      }
    },

    // Deletes a file with a specific ID calling the AuRa tank API and afterwards
    // fetching a fresh list of files from it.
    deleteFile: function (id) {
      let uri = process.env.VUE_APP_API_TANK + 'shows/' + this.selectedShow.slug + '/files/' + id
      // TODO: add mechanism to indicate the running delete request in the files table
      axios.delete(uri, {
        withCredentials: true,
        headers: { 'Authorization': 'Bearer ' + this.$store.state.auth.user.access_token },
      }).then(() => {
        this.$log.debug(`Fetching files for show ${this.selectedShow.slug} (ID: ${id})`)
        this.fetchFiles(this.selectedShow.slug)
      }).catch(error => {
        // if there was a 409 Conflict response it means, that this file is
        // still used in one or more playlists.
        if (error.response.status === 409) {
          let pls = error.response.data.detail.playlists.length
          let msg = 'Cannot delete file. Still used in ' + pls + ' playlists:\n\n'
          for (let pl of error.response.data.detail.playlists) {
            msg += 'ID: ' + pl.id
            if (pl.description) {
              msg += ' (' + pl.description + ')'
            }
            msg += '\n'
          }
          msg += '\nIf you want to delete the file, remove it from those playlists first.'
          alert(msg)
        } else {
          this.$log.error(error.response.status + ' ' + error.response.statusText)
          this.$log.error(error.response)
          alert('Error: could not delete file. See console for details.')
        }
      })
    },

    // With this function we add a new file in the AuRa tank by calling its API.
    // Depending on wheter we add a remote file which tank then imports by itself,
    // or if we want to upload a local file, we source-uri has to look different.
    // And for uploading a local file this is just the first step. Afterwards the
    // actual upload has to be started with the startUpload function.
    addFile: function () {
      var uri = process.env.VUE_APP_API_TANK + 'shows/' + this.selectedShow.slug + '/files'
      if (this.addNewFileURI) {
        // TODO: add mechanism to indicate the running post request in the files table
        axios.post(uri, { 'source-uri': this.uploadSourceURI }, {
          withCredentials: true,
          headers: { 'Authorization': 'Bearer ' + this.$store.state.auth.user.access_token }
        }).then(() => {
          this.fetchFiles(this.selectedShow.slug)
          if (this.uploadInterval === null) {
            this.uploadInterval = setInterval(() => { this.fetchImports(this.selectedShow.slug) }, 250)
          }
        }).catch(error => {
          this.$log.error(error.response.status + ' ' + error.response.statusText)
          this.$log.error(error.response)
          alert('Error: could not add the new remote import. See console for details.')
        })
      } else if (this.uploadSourceFile) {
        // TODO: add mechanism to indicate the running post request in the files table
        axios.post(uri, { 'source-uri': encodeURI(encodeURI('upload://' + this.uploadSourceFile.name)) }, {
          withCredentials: true,
          headers: { 'Authorization': 'Bearer ' + this.$store.state.auth.user.access_token }
        }).then(response => {
          this.startUpload(response.data.id)
          this.fetchFiles(this.selectedShow.slug)
          if (this.uploadInterval === null) {
            this.uploadInterval = setInterval(() => { this.fetchImports(this.selectedShow.slug) }, 250)
          }
        }).catch(error => {
          this.$log.error(error.response.status + ' ' + error.response.statusText)
          this.$log.error(error.response)
          alert('Error: could not add the new file upload. See console for details.')
        })
      } else {
        alert('Something is wrong. You have choosen to upload a file, but the corresponding file object does not exist.')
      }
    },

    // When a new file was added with the addFile function we can start an upload
    // fetching the import endpoint of this file and then call the upload
    // function, which atually puts the file onto the server.
    startUpload: function (id) {
      var uri = process.env.VUE_APP_API_TANK + 'shows/' + this.selectedShow.slug + '/files/' + id + '/import'
      axios.get(uri, {
        withCredentials: true,
        headers: { 'Authorization': 'Bearer ' + this.$store.state.auth.user.access_token },
        params: {'wait-for': 'running'}
      }).then(
        this.upload(id)
      ).catch(error => {
        this.$log.error(error.response.status + ' ' + error.response.statusText)
        this.$log.error(error.response)
        alert('Error: could not start the file upload. See console for details.')
      })
    },

    // Upload a file to the AuRa tank API - given it was created with the addFile
    // and started with the startUpload methods.
    upload: function (id) {
      /*
       * NOTE: there is no npm package for flow.js and importing it manually did not
       *       work so far. therefore this is commented out and we are using the simple
       *       upload method, until there is a nice npm package for flow.js or somone
       *       resolves this issue otherwise
      var flow = new Flow({
        target: process.env.VUE_APP_API_TANK + 'shows/' + this.selectedShow.slug + '/files/' + id + '/upload',
        chunkSize: 100 * 1024,
        prioritizeFirstAndLastChunk: true
      })
      flow.on('fileSuccess', function(file, message) {
        this.$log.error(file, message)
      })
      flow.on('fileError', function(file, message) {
        this.$log.error(file, message)
        alert('Error: could not upload your file. See console for details.')
      })
      flow.addFile(this.uploadSourceFile)
      flow.upload()
      */
      var uri = process.env.VUE_APP_API_TANK + 'shows/' + this.selectedShow.slug + '/files/' + id + '/upload'
      axios.put(uri, this.uploadSourceFile, {
        withCredentials: true,
        headers: {
          'Authorization': 'Bearer ' + this.$store.state.auth.user.access_token,
          'Content-Type': 'application/octet-stream'
        }
      }).then(() => {
        this.$log.info('Sucessfully uploaded file.')
        // now we start polling for the import progress
        // the fetchImports function has to make sure to deactivate the interval
        // again, when all running imports are done (in this first raw version;
        // ideally we should refine this so that every single file gets updated independently)
        //this.uploadInterval = setInterval(() => { this.fetchImports(this.selectedShow.slug) }, 100)
      }).catch(error => {
        if (error.response.status === 500 && error.response.data.error === 'ffmpeg returned 1') {
          this.$log.error(error.response.status + ' ' + error.response.statusText)
          this.$log.error(error.response)
          // if we use a file format that is not supported by ffmpeg, we should find
          // the second to last line should notify us about invalid data
          let ffmpegError = error.response.data.detail[error.response.data.detail.length - 2]
          if (ffmpegError.line === 'pipe:: Invalid data found when processing input') {
            // in this case we can make the error message in the files table more specific
            alert('Error: import aborted. The audio data format of your file is not valid!')
          } else {
            alert('Error: ffmpeg could not processs your file! See console for details.')
          }
        } else {
          this.$log.error(error.response.status + ' ' + error.response.statusText)
          this.$log.error(error.response)
          alert('Error: could not finish the file upload/import. See console for details.')
        }
      })
    },

    // This function fetches all running imports for a given show. It should
    // be called periodically to reflect the upload/import progress. When no
    // more active imports are available the corresponding updateInterval
    // should be cleared again.
    fetchImports: function (slug){
      var uri = process.env.VUE_APP_API_TANK + 'shows/' + slug + '/imports'
      axios.get(uri, {
        withCredentials: true,
        headers: { 'Authorization': 'Bearer ' + this.$store.state.auth.user.access_token }
      }).then(response => {
        // if all imports are done, we will receive an empty result set and stop
        // polling the server again. then we can also refetch all file statuses.
        if (response.data.results.length === 0) {
          clearInterval(this.uploadInterval)
          this.uploadInterval = null
          this.fetchShow(slug)
        }
        // if there are still imports going on, we just updated the respective
        // progress information for the import we just fetched and rerender
        // the filesTable
        else {
          for (var i in response.data.results) {
            var f = this.getFileById(response.data.results[i].id)
            if (f) {
              f.source.import.progress = {
                progress: response.data.results[i].progress.progress,
                step: response.data.results[i].progress.step
              }
              let p = '[import]'
              p += ' id: ' + response.data.results[i].id
              p += ', progress: ' + response.data.results[i].progress.progress
              p += ', step: ' + response.data.results[i].progress.step
              this.$log.debug(p)
            }
            this.$refs.filesTable.refresh()
          }
        }
      }).catch(error => {
        // also in case of an error we have to cancel the uploadInterval,
        // otherwise we'll continuosly get alerts if the error is persistent
        clearInterval(this.uploadInterval)
        if (error.response) {
          this.$log.error(error.response.status + ' ' + error.response.statusText)
          this.$log.error(error.response)
        } else {
          this.$log.error(error)
        }
        alert('Error: could not fetch current imports. See console for details.')
      })
    },

    // Fetch all files for a given show from the AuRa tank API
    fetchFiles: function (slug) {
      this.$store.dispatch('files/fetchFiles', {slug: slug})
    },

  },
}
</script>