18045010223
2025-07-07 0d3a683a0c97154b1f2e6657398664537e4e3e82
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
package org.yzh.web.service;
 
import io.netty.buffer.ByteBuf;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.yzh.commons.util.DateUtils;
import org.yzh.commons.util.Exceptions;
import org.yzh.commons.util.IOUtils;
import org.yzh.protocol.jsatl12.DataPacket;
import org.yzh.protocol.jsatl12.T1210;
import org.yzh.protocol.jsatl12.T1211;
import org.yzh.protocol.t808.T0200;
import org.yzh.protocol.t808.T0801;
import org.yzh.web.config.JTProperties;
import org.yzh.web.model.entity.DeviceDO;
import org.yzh.web.model.enums.SessionKey;
 
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.*;
 
/**
 * @author yezhihao
 * https://gitee.com/yezhihao/jt808-server
 */
@Slf4j
@Service
public class FileService {
 
    @Resource
    private JTProperties jtProperties;
 
    private static final Comparator<long[]> comparator = Comparator.comparingLong((long[] a) -> a[0]).thenComparingLong(a -> a[1]);
 
    private String getDir(T1210 alarmId) {
        StringBuilder sb = new StringBuilder(80);
        sb.append(jtProperties.getT9208().getPath()).append('/');
        sb.append(alarmId.getClientId()).append('_');
        DateUtils.yyMMddHHmmss.formatTo(alarmId.getDateTime(), sb);
        sb.append('_').append(alarmId.getSerialNo()).append('/');
        return sb.toString();
    }
 
    /** 创建报警目录及 附件列表日志 */
    public void createDir(T1210 alarmId) {
        String dirPath = getDir(alarmId);
        new File(dirPath).mkdirs();
 
        List<T1210.Item> items = alarmId.getItems();
        StringBuilder fileList = new StringBuilder(items.size() * 50);
        fileList.append(dirPath).append('\n');
 
        for (T1210.Item item : items)
            fileList.append(item.getName()).append('\t').append(item.getSize()).append('\n');
 
        log.warn("文件列表: {}", fileList);
        Exceptions.ignore(() -> FileCopyUtils.copy(fileList.toString().getBytes(StandardCharsets.UTF_8), new File(dirPath, "fs.txt")));
    }
 
    /** 将数据块写入到报警文件,并记录日志 */
    public void writeFile(T1210 alarmId, DataPacket fileData) {
        String dir = getDir(alarmId);
        String name = dir + fileData.getName().trim();
 
        int offset = fileData.getOffset();
        int length = fileData.getLength();
 
        byte[] buffer = ByteBuffer.allocate(8)
                .putInt(offset).putInt(length).array();
 
        RandomAccessFile file = null;
        FileOutputStream filelog = null;
        ByteBuf data = fileData.getData();
        try {
            file = new RandomAccessFile(name + ".tmp", "rw");
            filelog = new FileOutputStream(name + ".log", true);
 
            data.readBytes(file.getChannel(), offset, data.readableBytes());
            filelog.write(buffer);
        } catch (IOException e) {
            log.error("写入报警文件", e);
        } finally {
            IOUtils.close(file, filelog);
        }
    }
 
    public void writeFileSingle(T1210 alarmId, DataPacket fileData) {
        String dir = getDir(alarmId);
        String name = dir + fileData.getName().trim();
 
        int offset = fileData.getOffset();
 
        RandomAccessFile file = null;
        ByteBuf data = fileData.getData();
        try {
            file = new RandomAccessFile(name, "rw");
            data.readBytes(file.getChannel(), offset, data.readableBytes());
        } catch (IOException e) {
            log.error("写入报警文件", e);
        } finally {
            IOUtils.close(file);
        }
    }
 
    /** 根据日志检查文件完整性,并返回缺少的数据块信息 */
    public int[] checkFile(T1210 alarmId, T1211 fileInfo) {
        String dir = getDir(alarmId);
        File logFile = new File(dir + fileInfo.getName() + ".log");
 
        byte[] bytes;
        FileInputStream in = null;
        try {
            in = new FileInputStream(logFile);
            bytes = new byte[in.available()];
            in.read(bytes);
        } catch (FileNotFoundException e) {
            return null;
        } catch (IOException e) {
            log.error("检查文件完整性", e);
            return null;
        } finally {
            IOUtils.close(in);
        }
 
        int size = bytes.length / 8;
        long[][] items = new long[size + 2][2];
        items[size + 1][0] = fileInfo.getSize();
 
        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        for (int i = 1; i <= size; i++) {
            items[i][0] = buffer.getInt();
            items[i][1] = buffer.getInt();
        }
 
        List<Integer> result = new ArrayList<>(items.length);
        int len = items.length - 1;
        Arrays.sort(items, 1, len, comparator);
 
        for (int i = 0; i < len; ) {
            long a = items[i][0] + items[i][1];
            long b = items[++i][0] - a;
            if (b > 0) {
                result.add((int) a);
                result.add((int) b);
            }
        }
 
        if (result.isEmpty()) {
            File file = new File(dir + fileInfo.getName() + ".tmp");
            File dest = new File(dir + fileInfo.getName());
            if (file.renameTo(dest)) {
                logFile.delete();
            }
            return null;
        }
        return result.stream().filter(Objects::nonNull).mapToInt(i -> i).toArray();
    }
 
    /** 多媒体数据上传 */
    public boolean saveMediaFile(T0801 message) {
        DeviceDO device = message.getSession().getAttribute(SessionKey.Device);
        T0200 location = message.getLocation();
 
        StringBuilder filename = new StringBuilder(32);
        filename.append(type(message.getType())).append('_');
        DateUtils.yyMMddHHmmss.formatTo(location.getDeviceTime(), filename);
        filename.append('_');
        filename.append(message.getChannelId()).append('_');
        filename.append(message.getEvent()).append('_');
        filename.append(message.getId()).append('.');
        filename.append(suffix(message.getFormat()));
 
        String deviceId;
        if (device == null)
            deviceId = message.getClientId();
        else
            deviceId = device.getDeviceId();
 
        File dir = new File(jtProperties.getT0801().getPath() + '/' + deviceId);
        dir.mkdirs();
 
        ByteBuf packet = message.getPacket();
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(new File(dir, filename.toString()));
            packet.readBytes(fos.getChannel(), 0, packet.readableBytes());
            return true;
        } catch (IOException e) {
            log.error("多媒体数据保存失败", e);
            return false;
        } finally {
            IOUtils.close(fos);
            packet.release();
        }
    }
 
    private static String type(int type) {
        return switch (type) {
            case 0 -> "image";
            case 1 -> "audio";
            case 2 -> "video";
            default -> "unknown";
        };
    }
 
    private static String suffix(int format) {
        return switch (format) {
            case 0 -> "jpg";
            case 1 -> "tif";
            case 2 -> "mp3";
            case 3 -> "wav";
            case 4 -> "wmv";
            default -> "bin";
        };
    }
}