]> git.basschouten.com Git - openhab-addons.git/blob
465a2b2bd428d05423c8b9065bcdb4f43c1eb5fc
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.voice.mimic.internal;
14
15 import java.io.File;
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.util.ArrayList;
19 import java.util.List;
20
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.openhab.core.audio.AudioException;
23 import org.openhab.core.audio.AudioFormat;
24 import org.openhab.core.audio.FileAudioStream;
25
26 /**
27  * A FileAudioStream that autodelete after it and its clone are closed
28  * Useful to not congest temporary directory
29  *
30  * @author Gwendal Roulleau - Initial contribution
31  */
32 @NonNullByDefault
33 public class AutoDeleteFileAudioStream extends FileAudioStream {
34
35     private final File file;
36     private final AudioFormat audioFormat;
37     private final List<ClonedFileInputStream> clonedAudioStreams = new ArrayList<>(1);
38     private boolean isOpen = true;
39
40     public AutoDeleteFileAudioStream(File file, AudioFormat format) throws AudioException {
41         super(file, format);
42         this.file = file;
43         this.audioFormat = format;
44     }
45
46     @Override
47     public void close() throws IOException {
48         super.close();
49         this.isOpen = false;
50         deleteIfPossible();
51     }
52
53     protected void deleteIfPossible() {
54         boolean aClonedStreamIsOpen = clonedAudioStreams.stream().anyMatch(as -> as.isOpen);
55         if (!isOpen && !aClonedStreamIsOpen) {
56             file.delete();
57         }
58     }
59
60     @Override
61     public InputStream getClonedStream() throws AudioException {
62         ClonedFileInputStream clonedInputStream = new ClonedFileInputStream(this, file, audioFormat);
63         clonedAudioStreams.add(clonedInputStream);
64         return clonedInputStream;
65     }
66
67     private static class ClonedFileInputStream extends FileAudioStream {
68         protected boolean isOpen = true;
69         private final AutoDeleteFileAudioStream parent;
70
71         public ClonedFileInputStream(AutoDeleteFileAudioStream parent, File file, AudioFormat audioFormat)
72                 throws AudioException {
73             super(file, audioFormat);
74             this.parent = parent;
75         }
76
77         @Override
78         public void close() throws IOException {
79             super.close();
80             this.isOpen = false;
81             parent.deleteIfPossible();
82         }
83     }
84 }