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 androidx.annotation.NonNull; 20 21 import java.io.BufferedReader; 22 import java.io.IOException; 23 import java.io.InputStream; 24 import java.io.InputStreamReader; 25 import java.io.OutputStream; 26 import java.io.PrintWriter; 27 import java.nio.file.FileSystem; 28 import java.nio.file.FileSystems; 29 import java.nio.file.Path; 30 import java.util.Arrays; 31 import java.util.List; 32 import java.util.regex.Matcher; 33 import java.util.regex.Pattern; 34 35 public class PlsPlaylistPersister implements PlaylistPersister { 36 private static final Pattern PATTERN_PLS = Pattern.compile("File(\\d+)=(.+)"); 37 38 @Override read(@onNull InputStream in, @NonNull List<Path> items)39 public void read(@NonNull InputStream in, @NonNull List<Path> items) throws IOException { 40 final FileSystem fs = FileSystems.getDefault(); 41 try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { 42 Path[] res = new Path[0]; 43 44 String line; 45 while ((line = reader.readLine()) != null) { 46 final Matcher matcher = PATTERN_PLS.matcher(line); 47 if (matcher.matches()) { 48 final int index = Integer.parseInt(matcher.group(1)); 49 final Path item = fs.getPath(matcher.group(2).replace('\\', '/')); 50 if (index + 1 > res.length) { 51 res = Arrays.copyOf(res, index + 1); 52 } 53 res[index] = item; 54 } 55 } 56 57 for (int i = 0; i < res.length; i++) { 58 if (res[i] != null) { 59 items.add(res[i]); 60 } 61 } 62 } 63 } 64 65 @Override write(@onNull OutputStream out, @NonNull List<Path> items)66 public void write(@NonNull OutputStream out, @NonNull List<Path> items) throws IOException { 67 try (PrintWriter writer = new PrintWriter(out)) { 68 writer.printf("[playlist]\n"); 69 for (int i = 0; i < items.size(); i++) { 70 writer.printf("File%d=%s\n", i + 1, items.get(i)); 71 } 72 writer.printf("NumberOfEntries=%d\n", items.size()); 73 writer.printf("Version=2\n"); 74 } 75 } 76 } 77