1 /*
2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.providers.media.playlist;
18 
19 import android.text.TextUtils;
20 
21 import androidx.annotation.NonNull;
22 
23 import java.io.BufferedReader;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.InputStreamReader;
27 import java.io.OutputStream;
28 import java.io.PrintWriter;
29 import java.nio.file.FileSystem;
30 import java.nio.file.FileSystems;
31 import java.nio.file.Path;
32 import java.util.List;
33 
34 public class M3uPlaylistPersister implements PlaylistPersister {
35     @Override
read(@onNull InputStream in, @NonNull List<Path> items)36     public void read(@NonNull InputStream in, @NonNull List<Path> items) throws IOException {
37         final FileSystem fs = FileSystems.getDefault();
38         try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
39             String line;
40             while ((line = reader.readLine()) != null) {
41                 if (!TextUtils.isEmpty(line) && !line.startsWith("#")) {
42                     items.add(fs.getPath(line.replace('\\', '/')));
43                 }
44             }
45         }
46     }
47 
48     @Override
write(@onNull OutputStream out, @NonNull List<Path> items)49     public void write(@NonNull OutputStream out, @NonNull List<Path> items) throws IOException {
50         try (PrintWriter writer = new PrintWriter(out)) {
51             writer.println("#EXTM3U");
52             for (Path item : items) {
53                 writer.println(item);
54             }
55         }
56     }
57 }
58