summaryrefslogtreecommitdiff
path: root/src/gempub.c
blob: 1f5d58ce1f0e6aad92668f4b876dd5ed53fc1af0 (plain)
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
/* Copyright 2021 Jaakko Keränen <jaakko.keranen@iki.fi>

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */

#include "gempub.h"
#include "gmutil.h"
#include "lang.h"
#include "defs.h"
#include "gmdocument.h"
#include "gmrequest.h"
#include "ui/util.h"
#include "app.h"

#include <the_Foundation/archive.h>
#include <the_Foundation/file.h>
#include <the_Foundation/path.h>
#include <the_Foundation/regexp.h>

const char *mimeType_Gempub = "application/gpub+zip";

/*----------------------------------------------------------------------------------------------*/

iDeclareType(GempubNavLink)
 
struct Impl_GempubNavLink {
    iString url;
    iString label;
};
    
static void init_GempubNavLink(iGempubNavLink *d) {
    init_String(&d->url);
    init_String(&d->label);
}

static void deinit_GempubNavLink(iGempubNavLink *d) {
    deinit_String(&d->url);
    deinit_String(&d->label);   
}

iDefineTypeConstruction(GempubNavLink)
    
/*----------------------------------------------------------------------------------------------*/
    
struct Impl_Gempub {
    iArchive *arch;
    iString baseUrl;
    iString props[max_GempubProperty];
    iArray *navLinks; /* from index page */
};

iDefineTypeConstruction(Gempub)
    
static void parseNavigationLinks_Gempub_(const iGempub *d) {
    if (!isEmpty_Array(d->navLinks)) {
        return;
    }
    iGmRequest *index = iClob(new_GmRequest(certs_App()));
    setUrl_GmRequest(index, indexPageUrl_Gempub(d));
    submit_GmRequest(index); /* this is just a local file read */
    iAssert(isFinished_GmRequest(index));
    iRangecc src = iNullRange;
    iRegExp *linkPattern = iClob(newGemtextLink_RegExp());
    while (nextSplit_Rangecc(range_Block(body_GmRequest(index)), "\n", &src)) {
        iRangecc line = src;
        trim_Rangecc(&line);
        iRegExpMatch m;
        init_RegExpMatch(&m);
        if (matchRange_RegExp(linkPattern, line, &m)) {
            iBeginCollect();
            const iRangecc url = capturedRange_RegExpMatch(&m, 1);
            iUrl parts;
            init_Url(&parts, collectNewRange_String(url));
            if (isEmpty_Range(&parts.scheme)) {
                iGempubNavLink link;
                init_GempubNavLink(&link);
                set_String(&link.url, absoluteUrl_String(url_GmRequest(index), collectNewRange_String(url)));
                setRange_String(&link.label, capturedRange_RegExpMatch(&m, 2));
                trim_String(&link.label);
                if (isEmpty_String(&link.label)) {
                    setRange_String(&link.label, url);                    
                }
                pushBack_Array(d->navLinks, &link);
            }
            iEndCollect();
        }
    }
}
    
void init_Gempub(iGempub *d) {
    d->arch = NULL;
    init_String(&d->baseUrl);
    iForIndices(i, d->props) {
        init_String(&d->props[i]);
    }
    d->navLinks = new_Array(sizeof(iGempubNavLink));
}

void deinit_Gempub(iGempub *d) {
    iForEach(Array, n, d->navLinks) {
        deinit_GempubNavLink(n.value);
    }
    delete_Array(d->navLinks);
    iForIndices(i, d->props) {
        deinit_String(&d->props[i]);
    }
    deinit_String(&d->baseUrl);
    iRelease(d->arch);
}
    
static iBool parseMetadata_Gempub_(iGempub *d) {
    iAssert(isOpen_Archive(d->arch));
    /* Parse the metadata and check if the required contents are present. */
    const iBlock *metadata = dataCStr_Archive(d->arch, "metadata.txt");
    if (!metadata) {
        return iFalse;
    }
    static const char *labels[max_GempubProperty] = {
        "title:",
        "index:",
        "author:",
        "language:",
        "description:",
        "published:",
        "publishDate:",
        "revisionDate:",
        "copyright:",
        "license:",
        "version:",
        "cover:",
    };
    /* Default values. */
    setCStr_String(&d->props[title_GempubProperty], "${gempub.cover.untitled}");
    setCStr_String(&d->props[cover_GempubProperty],
                   entryCStr_Archive(d->arch, "cover.jpg") ? "cover.jpg" :
                   entryCStr_Archive(d->arch, "cover.png") ? "cover.png" : "");
    setCStr_String(&d->props[index_GempubProperty], "index.gmi");
    iRangecc line = iNullRange;
    while (nextSplit_Rangecc(range_Block(metadata), "\n", &line)) {
        iRangecc clean = line;
        trim_Rangecc(&clean);
        iForIndices(i, d->props) {
            if (startsWithCase_Rangecc(clean, labels[i])) {
                setRange_String(&d->props[i],
                                (iRangecc){ clean.start + strlen(labels[i]), clean.end });
                trim_String(&d->props[i]);
            }
        }
    }
    return iTrue;
}    

iBool open_Gempub(iGempub *d, const iBlock *data) {
    close_Gempub(d);
    d->arch = new_Archive();
    if (openData_Archive(d->arch, data) && parseMetadata_Gempub_(d)) {
        return iTrue;
    }
    close_Gempub(d);
    return iFalse;
}

iBool openFile_Gempub(iGempub *d, const iString *path) {
    close_Gempub(d);
    iFile *f = new_File(path);
    if (open_File(f, readOnly_FileMode)) {
        iBlock *data = readAll_File(f);
        open_Gempub(d, data);
        delete_Block(data);
        setBaseUrl_Gempub(d, collect_String(makeFileUrl_String(path)));
    }
    iRelease(f);
    return isOpen_Gempub(d);
}

iBool openUrl_Gempub(iGempub *d, const iString *url) {
    if (!openFile_Gempub(d, collect_String(localFilePathFromUrl_String(url)))) {
        setBaseUrl_Gempub(d, url);
        close_Gempub(d);
        return iFalse;
    }
    return iTrue;
}

void close_Gempub(iGempub *d) {
    if (d->arch) {
        iReleasePtr(&d->arch);
    }
    iForIndices(i, d->props) {
        clear_String(&d->props[i]);
    }
}

void setBaseUrl_Gempub(iGempub *d, const iString *url) {
    set_String(&d->baseUrl, collect_String(urlDecodeExclude_String(url, "/:")));
}

iBool isOpen_Gempub(const iGempub *d) {
    return d->arch != NULL;
}

const iString *property_Gempub(const iGempub *d, enum iGempubProperty prop) {
    return &d->props[prop];
}

const iString *coverPageUrl_Gempub(const iGempub *d) {
    return &d->baseUrl;
}

const iString *indexPageUrl_Gempub(const iGempub *d) {
    iAssert(!isEmpty_String(&d->baseUrl));
    iString *dir = collect_String(copy_String(&d->baseUrl));
    appendCStr_String(dir, "/");
    return absoluteUrl_String(dir, &d->props[index_GempubProperty]);
}

const iString *navStartLinkUrl_Gempub(const iGempub *d) {
    parseNavigationLinks_Gempub_(d);
    if (isEmpty_Array(d->navLinks)) {
        return NULL; /* has no navigation structure */
    }
    return &((const iGempubNavLink *) constFront_Array(d->navLinks))->url;
}

size_t navSize_Gempub(const iGempub *d) {
    parseNavigationLinks_Gempub_(d);
    return size_Array(d->navLinks);
}

size_t navIndex_Gempub(const iGempub *d, const iString *url) {
    parseNavigationLinks_Gempub_(d);
    const iString *normUrl = withSpacesEncoded_String(url);
    iConstForEach(Array, i, d->navLinks) {
        const iGempubNavLink *nav = i.value;
        if (equalCase_String(&nav->url, normUrl)) {
            return index_ArrayConstIterator(&i);
        }
    }
    return iInvalidPos;
}

const iString *navLinkUrl_Gempub(const iGempub *d, size_t index) {
    parseNavigationLinks_Gempub_(d);
    if (index < size_Array(d->navLinks)) {
        return &constValue_Array(d->navLinks, index, iGempubNavLink).url;
    }
    return NULL;
}

const iString *navLinkLabel_Gempub(const iGempub *d, size_t index) {
    parseNavigationLinks_Gempub_(d);
    if (index < size_Array(d->navLinks)) {
        return &constValue_Array(d->navLinks, index, iGempubNavLink).label;
    }
    return NULL;    
}

static iBool hasProperty_Gempub_(const iGempub *d, enum iGempubProperty prop) {
    return !isEmpty_String(&d->props[prop]);
}

static void appendProperty_Gempub_(const iGempub *d, const char *label,
                                   enum iGempubProperty prop, iString *out) {
    if (hasProperty_Gempub_(d, prop)) {
        appendFormat_String(out, "%s %s\n", label, cstr_String(&d->props[prop]));
    }
}

iBool isRemote_Gempub(const iGempub *d) {
    return !equalCase_Rangecc(urlScheme_String(&d->baseUrl), "file");
}

iString *coverPageSource_Gempub(const iGempub *d) {
    iAssert(!isEmpty_String(&d->baseUrl));
    const iString *baseUrl = withSpacesEncoded_String(&d->baseUrl);
    iString *out = new_String();
    format_String(out, "# %s\n",
                  cstr_String(&d->props[title_GempubProperty]));
    if (!isEmpty_String(&d->props[description_GempubProperty])) {
        appendFormat_String(out, "%s\n", cstr_String(&d->props[description_GempubProperty]));
    }
    appendCStr_String(out, "\n");
    appendProperty_Gempub_(d, "${gempub.meta.author}:", author_GempubProperty, out);
    if (!isRemote_Gempub(d)) {
        appendFormat_String(out, "\n=> %s " book_Icon " ${gempub.cover.view}\n",
                            cstr_String(indexPageUrl_Gempub(d)));
        if (hasProperty_Gempub_(d, cover_GempubProperty)) {
            appendFormat_String(out, "\n=> %s  ${gempub.cover.image}\n",
                                cstrCollect_String(concat_Path(baseUrl, &d->props[cover_GempubProperty])));
        }
    }
    else {
        iString *key = collectNew_String(); /* TODO: add a helper for this */
        toString_Sym(SDLK_s, KMOD_PRIMARY, key);
        appendCStr_String(out, "\n${gempub.cover.viewlocal}\n");
//        appendFormat_String(out,
//                            cstr_Lang("error.unsupported.suggestsave"),
//                            cstr_String(key),
//                            saveToDownloads_Label);
//        appendCStr_String(out, "\n");
    }
    appendCStr_String(out, "\n## ${gempub.cover.aboutbook}\n");
    appendProperty_Gempub_(d, "${gempub.meta.version}:", version_GempubProperty, out);
    appendProperty_Gempub_(d, "${gempub.meta.revdate}:", revisionDate_GempubProperty, out);
    if (hasProperty_Gempub_(d, publishDate_GempubProperty)) {
        appendProperty_Gempub_(d, "${gempub.meta.pubdate}:", publishDate_GempubProperty, out);
    }
    else {
        appendProperty_Gempub_(d, "${gempub.meta.pub}:", published_GempubProperty, out);
    }
    appendProperty_Gempub_(d, "${gempub.meta.lang}:", language_GempubProperty, out);
    appendProperty_Gempub_(d, "${gempub.meta.license}:", license_GempubProperty, out);
    appendProperty_Gempub_(d, "\u00a9", copyright_GempubProperty, out);
    translate_Lang(out);
    return out;
}

iBool preloadCoverImage_Gempub(const iGempub *d, iGmDocument *doc) {
    iBool haveImage = iFalse;
    for (size_t linkId = 1; ; linkId++) {
        const iString *linkUrl = linkUrl_GmDocument(doc, linkId);
        if (!linkUrl) break;
        if (findLinkImage_Media(media_GmDocument(doc), linkId)) {
            continue; /* got this already */
        }
        if (linkFlags_GmDocument(doc, linkId) & imageFileExtension_GmLinkFlag) {
            iString *imgEntryPath = collect_String(copy_String(linkUrl));
            remove_Block(&imgEntryPath->chars, 0, size_String(&d->baseUrl) + 1 /* slash, too */);
            setData_Media(media_GmDocument(doc),
                          linkId,
                          collectNewCStr_String(mediaType_Path(linkUrl)),
                          data_Archive(d->arch, imgEntryPath),
                          0);
            haveImage = iTrue;
        }
    }
    return haveImage;
}