LocalMovieScanUtils.java 11 KB
package com.gimi.common.cinema.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.gimi.common.cinema.model.AsyncCallback;
import com.gimi.common.cinema.model.FolderItem;
import com.gimi.common.cinema.model.LocalMovieMessage;
import com.gimi.common.cinema.model.MovieMessage;
import com.gimi.common.cinema.model.Rating;
import com.gimi.common.cinema.model.SambaMsg;
import com.xgimi.gimicinema.BuildConfig;
import com.xgimi.gimicinema.R;
import com.xgimi.gimicinema.activity.CinemaConfig;

import java.io.File;
import java.util.ArrayList;

/**
 * movie scan
 * Created by 李攀 on 2015/4/29.
 */
public class LocalMovieScanUtils {
    private String[] picExtensions;
    private String[] mediaExtensions;

    public LocalMovieScanUtils(Context context) {
        picExtensions = context.getResources().getStringArray(R.array.photo_filter);
        mediaExtensions = context.getResources().getStringArray(R.array.video_filter);
    }

    private ArrayList<FolderItem> getTypes(String rootPath) {
        ArrayList<FolderItem> types = new ArrayList<>();
        File file = new File(rootPath);
        String[] fileDirs = file.list();
        if (fileDirs == null || fileDirs.length == 0) {//防止中文目录挂失败
            return types;
        }
        for (String fileDir : fileDirs) {
            File curFile = new File(rootPath + fileDir);
            if (curFile.isDirectory()) {
                FolderItem folderItem = new FolderItem();
                folderItem.setFolderName(fileDir);
                folderItem.setFolderPath(rootPath + fileDir + "/");
//                if (fileDir.contains("3D")) {
                types.add(folderItem);
//                }
            }
        }
        return types;
    }

    private boolean checkType(String name, String[] extensions) {
        for (String end : extensions) {
            // Name never to null, without exception handling
            if (name.toLowerCase().endsWith(end)) {
                return true;
            }
        }
        return false;
    }

    private String getMedia(String path, String[] extensions) {
        String mediaPath;
        if (path.endsWith(".BD/") || path.endsWith(".ISO/")) {
            mediaPath = getBDPlayPath(path, extensions);
        } else {
            File file = new File(path);
            String[] files = file.list();
            mediaPath = null;
            if (files == null || files.length == 0) {
                return null;
            }
            for (String file1 : files) {
                if (checkType(path + file1, extensions)) {
                    mediaPath = path + file1;
                    break;
                }
            }
        }
        return mediaPath;
    }

    private String getMediaPicture(String path, String[] extensions) {
        String posterPath;

        File file = new File(path);
        String[] files = file.list();
        if (files == null || files.length == 0) {
            return null;
        }
        posterPath = null;
        for (String file1 : files) {
            if (checkType(path + file1, extensions)) {
                posterPath = path + file1;
                break;
            }
        }
        return posterPath;
    }

    private String getBDPlayPath(String path, String[] extensions) {
        String mediaPath = null;

        ArrayList<String> strings1 = new ArrayList<>();
        ArrayList<String> strings = find(path, extensions, strings1);
        if (strings.size() >= 1) {
            for (String string : strings) {
                mediaPath = getBiggerVideoPath(mediaPath, string);
            }
        }
        return mediaPath;
    }

    private ArrayList<String> find(String path, String[] reg, ArrayList<String> result) {
        File file = new File(path);
        File[] arr = file.listFiles();
        for (File anArr : arr) {
            //判断是否是文件夹,如果是的话,再调用一下find方法
            if (anArr.isDirectory()) {
                find(anArr.getAbsolutePath(), reg, result);
            } else if (checkType(anArr.getAbsolutePath(), reg)) {
                result.add(anArr.getAbsolutePath());
            }
        }
        return result;
    }

    private String getBiggerVideoPath(String oldPath, String newPath) {
        if (oldPath == null) {
            return newPath;
        }
        File oFile = new File(oldPath);
        File nFile = new File(newPath);

        if (oFile.length() > nFile.length()) {
            return oldPath;
        }

        return newPath;
    }

    private void setDoubanMsg(String mmPath, LocalMovieMessage localMovieMessage) {
        MovieMessage mm = MovieMessageUtils.getLocalMovieMessage(mmPath);
        if (mm != null) {
            Rating rating = mm.getRating();
            double average = 0;//rating
            if (rating != null) {
                average = rating.getAverage();
            }
            String[] genres = mm.getGenres();
            //clazz
            if (!TextUtils.isEmpty(mm.getId())) {
                localMovieMessage.setDoubanId(mm.getId());
            }
            //types
            StringBuilder types = new StringBuilder();
            localMovieMessage.setDoubanRating(average);
            if (genres.length > 0) {
                types.append(genres[0]);
            }
            for (int i = 1; i < genres.length; i++) {
                types.append("/").append(genres[i]);
            }
            localMovieMessage.setScreenTime(mm.getYear());
            localMovieMessage.setClassDescribe(types.toString());
        }
    }

    /**
     * scan movies like
     * /mnt/samba/172.21.16.252/root1
     * /mnt/samba/172.21.16.252/root2
     * /mnt/samba/172.21.16.252/folder
     *
     * @param rootPath /mnt/samba/172.21.16.252/
     * @param callback callback
     * @return ArrayList<LocalMovieMessage>
     */
    ArrayList<LocalMovieMessage> getAllLocalMovie(String rootPath, String folder, AsyncCallback<Integer> callback) {
        ArrayList<String> all = new ArrayList<>();
        File file = new File(rootPath);
        if (file.listFiles() != null) {
            for (File file1 : file.listFiles()) {
                if (file1.isDirectory()) {
                    String absolutePath = file1.getAbsolutePath() + "/";
                    if (new File(absolutePath + "TJ").exists()) {
                        all.add(absolutePath);
                    }
                }
            }
        }

        if (BuildConfig.MACHINE_TYPE.equals("himedia")) {
            all.add(CinemaConfig.BASIC_ROOT + "/");
        }
        if (!TextUtils.isEmpty(folder)) {
            String s = rootPath + folder + File.separator;
            if (new File(s).exists()) {
                if (new File(s + "TJ/").exists()) {
                    if (!all.contains(s)) {
                        all.add(s);
                    }
                }
                File file1 = new File(s);
                String[] list = file1.list();
                if (list != null && list.length != 0) {
                    for (String s1 : list) {
                        if (new File(s + s1 + File.separator + "TJ/").exists()) {
                            all.add(s + s1 + File.separator);
                        }
                    }
                }
            }
        }
        if (!all.contains(rootPath + folder + File.separator)) {
            all.add(rootPath + folder + File.separator);
        }
        ArrayList<LocalMovieMessage> moviesItems = new ArrayList<>();
        for (String s : all) {
            ArrayList<FolderItem> types = getTypes(s);
            for (FolderItem type : types) {
                moviesItems.addAll(getAllType(type.getFolderPath(), callback));
            }
        }
        return moviesItems;
    }

    public ArrayList<LocalMovieMessage> getAllLocalMovie(SambaMsg msg, AsyncCallback<Integer> callback) {
        if (BuildConfig.MACHINE_TYPE.equals("himedia")) {
            return getAllLocalMovie(CinemaConfig.BASIC_ROOT, msg.getFolder(), callback);
        }
        return getAllLocalMovie(msg.getRootPath(), msg.getFolder(), callback);
    }


    public ArrayList<LocalMovieMessage> getAllFolderMovies(String rootPath, AsyncCallback<Integer> callback) {
        return getAllType(rootPath, callback);
    }

    /**
     * 扫描电影文件夹添加必要信息
     *
     * @param rootPath movie folder path
     * @param callback callback
     * @return ArrayList<LocalMovieMessage>
     */
    @SuppressLint("SdCardPath")
    private ArrayList<LocalMovieMessage> getAllType(String rootPath, AsyncCallback<Integer> callback) {
        ArrayList<LocalMovieMessage> movies = new ArrayList<>();
        if (rootPath.contains("lost+found")) {
            return movies;
        }
        File file = new File(rootPath);
        String[] fileDirs = file.list();
        //遍历
        if (fileDirs == null || fileDirs.length == 0) {
            return movies;
        }
        for (String fileDir : fileDirs) {
            File curFiles = new File(rootPath + fileDir);
            if (curFiles.isDirectory()) {
                if (callback != null) {
                    callback.onMessage(fileDir);
                }
                String curPath = curFiles.getAbsoluteFile().toString();
                LocalMovieMessage moviesItem = new LocalMovieMessage();
                String name = NameFilterUtils.getName(fileDir).trim();
                moviesItem.setMovieName(name);String allFirstSpell = PinyinUtil.getAllFirstSpell(name);
                String newStr = allFirstSpell.replaceAll("[^\\w,]", "");
                moviesItem.setNamePinyin(newStr);
                String media = getMedia(curPath + "/", mediaExtensions);
                String poster;
                poster = MovieMessageUtils.getLocalMoviePoster(curPath);
                if (TextUtils.isEmpty(poster)) {
                    poster = getMediaPicture(curPath + "/", picExtensions);
                }
                if (!TextUtils.isEmpty(poster)) {
                    moviesItem.setPosterPath(poster);
                }
                if (!TextUtils.isEmpty(media)) {
                    File mFile = new File(media);
                    long length = mFile.length();
                    moviesItem.setMd5(MD5Utils.stringMD5(FileHashUtils.getFileHash(media)));
                    //read douban id and douban msg,至于name id 信息另外做,没有必要每次更新时都去添加
                    try {
                        setDoubanMsg(curPath, moviesItem);
                    } catch (Exception e) {
                        Log.e("otherError", media);
                        e.printStackTrace();
                    }
                    moviesItem.setType(fileDir);
                    moviesItem.setPlayPath(media);
                    String movieDlTime = String.valueOf(mFile.lastModified());
                    moviesItem.setMovieLength(movieDlTime);
                    moviesItem.setDlTime(movieDlTime);
                    moviesItem.setCount(MovieMessageUtils.getPlayCount(curPath));
                    movies.add(moviesItem);
                }
            }
        }
        return movies;
    }
}