]> Sergey Matveev's repositories - godlighty.git/blob - meta4/parse.go
Unify copyright comment format
[godlighty.git] / meta4 / parse.go
1 // godlighty -- highly-customizable HTTP, HTTP/2, HTTPS server
2 // Copyright (C) 2021-2024 Sergey Matveev <stargrave@stargrave.org>
3 //
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, version 3 of the License.
7 //
8 // This program is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 // GNU General Public License for more details.
12 //
13 // You should have received a copy of the GNU General Public License
14 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
15
16 package meta4
17
18 import (
19         "encoding/hex"
20         "encoding/xml"
21 )
22
23 var KnownHashes = map[string]string{
24         "blake3-256":   "BLAKE3-256",
25         "sha-256":      "SHA-256",
26         "sha-512":      "SHA-512",
27         "shake128":     "SHAKE128",
28         "shake256":     "SHAKE256",
29         "skein-256":    "Skein-256",
30         "skein-512":    "Skein-512",
31         "streebog-256": "Streebog-256",
32         "streebog-512": "Streebog-512",
33 }
34
35 type ForHTTP struct {
36         Hashes   map[string][]byte
37         URLs     []string
38         Torrents []string
39 }
40
41 func Parse(fn string, data []byte) (*ForHTTP, error) {
42         var meta Metalink
43         err := xml.Unmarshal(data, &meta)
44         if err != nil {
45                 return nil, err
46         }
47         for _, f := range meta.Files {
48                 if f.Name != fn {
49                         continue
50                 }
51                 forHTTP := ForHTTP{Hashes: make(map[string][]byte)}
52                 for _, h := range f.Hashes {
53                         name := KnownHashes[h.Type]
54                         if name == "" {
55                                 continue
56                         }
57                         digest, err := hex.DecodeString(h.Hash)
58                         if err != nil {
59                                 return nil, err
60                         }
61                         forHTTP.Hashes[name] = digest
62                 }
63                 for _, u := range f.URLs {
64                         forHTTP.URLs = append(forHTTP.URLs, u.URL)
65                 }
66                 for _, m := range f.MetaURLs {
67                         if m.MediaType == "torrent" {
68                                 forHTTP.Torrents = append(forHTTP.Torrents, m.URL)
69                         }
70                 }
71                 return &forHTTP, nil
72         }
73         return nil, nil
74 }