LocalMovieScanUtils.java
18.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
77
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
172
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
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
package com.gimi.common.cinema.utils;
import android.content.Context;
import android.media.MediaPlayer;
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.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 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("AQ")) {
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) {
Log.d("scan-time", "start:" + System.currentTimeMillis());
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));
}
}
Log.d("scan-time", " end:" + System.currentTimeMillis());
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>
*/
private ArrayList<LocalMovieMessage> getAllType(String rootPath, AsyncCallback<Integer> callback) {
ArrayList<LocalMovieMessage> movies = new ArrayList<>();
if (rootPath.contains("lost+found")) {
return movies;
}
if (callback != null) {
String[] split = rootPath.split("/");
callback.onMessage(split[split.length - 1]);
}
File file = new File(rootPath);
String[] fileDirs = file.list();
//遍历
if (fileDirs == null || fileDirs.length == 0) {
return movies;
}
int length = fileDirs.length;
int coreCount = 4;
int poolCount = 9;
ThreadPoolExecutor myExecutor = new ThreadPoolExecutor(coreCount, poolCount,
200, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>());
List<Future<ArrayList<LocalMovieMessage>>> results = new ArrayList<>();
for (int i = 0; i < coreCount; i++) {
ScanTask task = new ScanTask(rootPath, Arrays.copyOfRange(
fileDirs, length * i / coreCount, (length * (i + 1)) / coreCount));
Future<ArrayList<LocalMovieMessage>> result = myExecutor.submit(task);
results.add(result);
}
for (Future<ArrayList<LocalMovieMessage>> f : results) {
try {
movies.addAll(f.get());
} catch (Exception ex) {
ex.printStackTrace();
f.cancel(true);
}
}
myExecutor.shutdown();
// 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,]", "");
//// Log.d("lovely_pinyin", allFirstSpell + ":" + newStr);
// 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;
}
private class ScanTask implements Callable<ArrayList<LocalMovieMessage>> {
private String rootPath;
private String[] dirs;
private ScanTask(String rootPath, String[] dirs) {
this.rootPath = rootPath;
this.dirs = dirs;
}
@Override
public ArrayList<LocalMovieMessage> call() throws Exception {
ArrayList<LocalMovieMessage> movies = new ArrayList<>();
for (String fileDir : dirs) {
File curFiles = new File(rootPath + fileDir);
if (curFiles.isDirectory()) {
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);
curPath = null;
name = null;
allFirstSpell = null;
newStr = null;
media = null;
poster = null;
movieDlTime = null;
}
}
}
return movies;
}
}
/**
* The default thread factory.
*/
private static class MyThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
MyThreadFactory() {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = "pool-" +
poolNumber.getAndIncrement() +
"-thread-";
}
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
t.setDaemon(true);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
private synchronized long getDuration(String path) {
long in = System.currentTimeMillis();
MediaPlayer mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(path);
} catch (IOException e) {
e.printStackTrace();
}
int duration = mMediaPlayer.getDuration();
Log.d("duration", (System.currentTimeMillis() - in) + ":" + duration);
return duration;
}
private long getMovieLength(String mUri) {
long l = System.currentTimeMillis();
long duration = 5400000;
android.media.MediaMetadataRetriever mmr = new android.media.MediaMetadataRetriever();
try {
if (mUri != null) {
HashMap<String, String> headers = null;
if (headers == null) {
headers = new HashMap<String, String>();
headers.put("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.4.2; zh-CN; MW-KW-001 Build/JRO03C) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 UCBrowser/1.0.0.001 U4/0.8.0 Mobile Safari/533.1");
}
mmr.setDataSource(mUri, headers);
}
String durationStr = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION);
duration = Long.parseLong(durationStr);
} catch (Exception ex) {
} finally {
mmr.release();
}
Log.d("getAllType", "" + (System.currentTimeMillis() - l));
return duration;
}
}