Skip to content

Commit

Permalink
feat: extend files with offset field
Browse files Browse the repository at this point in the history
  • Loading branch information
isolomak committed Aug 4, 2023
1 parent af815ac commit 1c4df09
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 13 deletions.
23 changes: 14 additions & 9 deletions src/parse/TorrentParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,6 @@ import { IDotTorrent, IDotTorrentFileInfo } from '../types';

export default class TorrentParser {

/**
* Constructor
*/
// eslint-disable-next-line @typescript-eslint/no-useless-constructor
constructor() {}

/**
* Parse torrent file
*/
Expand Down Expand Up @@ -153,8 +147,19 @@ export default class TorrentParser {
}
}

return Array.from(fileMap.entries())
const files = Array.from(fileMap.entries())
.map(([ key, value ]) => ({ path: key, length: value }));

return files
.map((item, index) => {
let offset = 0;

files
.filter((_, internalIndex) => internalIndex < index)
.forEach(({ length }) => { offset += length; });

return { ...item, offset };
});
}

/**
Expand All @@ -163,7 +168,7 @@ export default class TorrentParser {
private static _name(decodedData: BencodeDictionary): string | null {
const torrentInfo = TorrentParser._info(decodedData);

if (!torrentInfo || !torrentInfo.name) {
if (!torrentInfo?.name) {
return null;
}

Expand Down Expand Up @@ -238,7 +243,7 @@ export default class TorrentParser {
return null;
}

return files.reduce((acc, next) => acc += next.length, 0);
return files.reduce((acc, next) => acc + next.length, 0);
}

/**
Expand Down
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export interface ICreateTorrentParams {
export interface IDotTorrentFileInfo {
length: number;
path: string;
offset: number;
}

/**
Expand Down
8 changes: 4 additions & 4 deletions test/parseFile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ describe('Parse file tests', () => {
createdAt: 1585998070,
encoding: 'UTF-8',
files: [
{ length: 16, path: 'file_1.txt' },
{ length: 16, path: 'file_2.txt' }
{ length: 16, path: 'file_1.txt', offset: 0 },
{ length: 16, path: 'file_2.txt', offset: 16 }
],
infoHash: '46bf9dd414eae4cd74fa4d129d2f23553a21bca7',
name: 'test_torrent',
Expand Down Expand Up @@ -47,8 +47,8 @@ describe('Parse file tests', () => {
createdAt: 1585998070,
encoding: 'UTF-8',
files: [
{ length: 16, path: 'file_1.txt' },
{ length: 16, path: 'file_2.txt' }
{ length: 16, path: 'file_1.txt', offset: 0 },
{ length: 16, path: 'file_2.txt', offset: 16 }
],
infoHash: '46bf9dd414eae4cd74fa4d129d2f23553a21bca7',
name: 'test_torrent',
Expand Down

0 comments on commit 1c4df09

Please sign in to comment.