~aprates/gempress

gempress/src/atom.c -rw-r--r-- 7.2 KiB
fc494358Antonio Prates Fix html lang bug 11 months ago
                                                                                
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
// GemPress feed-to-atom utility, using Sugar-C
// 2021, by Antonio Prates <hello@aprates.dev>
// Trying to comply to Gemini simple feed specification:
// gemini://gemini.circumlunar.space/docs/companion/subscription.gmi

/* USAGE NOTES:

This is a bit of a primitive tool and it expects a few things to work!

1. Gemini file as argument, containing the list of links (=>), like:

   => some-title.gmi YYYY-MM-DD Heading Of The Post

   Make sure that the URLs contain the date, as date is extracted from there.

2. A conf file with the global vars (defined right bellow).
   See also: capsule-example.conf

3. Input filename must be either 'index.gmi' or 'feed.gmi'

*/

#include <sugar.h>

#define OUTPUT_FILE "atom.xml"

// global vars get set when the config gets loaded
string title = "";
string author = "";
string remoteBaseUrl = "";
string feedDir = "log";
number maxAtomEntries = 15;
string rootMeta = "<feed xmlns=\"http://www.w3.org/2005/Atom\">\n\n";
string urlMetaFragment = "\" rel=\"alternate\" />\n    <title>";

// other global vars derivated or set during processing
string id = "";
string links = "";
string lastUpdated = (string)NULL;
bool convertToHttps = false;

string maybeToHttps(string url) {
  if (!convertToHttps)
    return url;
  url = replaceWord(url, "gemini://", "https://");
  return replaceWord(url, ".gmi", ".html");
}

// xml escape code helpers
string escapeE(string text) { return replaceWord(text, "&", "&amp;"); }
string escapeLt(string text) { return replaceWord(text, "<", "&lt;"); }
string escapeGt(string text) { return replaceWord(text, ">", "&gt;"); }
string escapeSq(string text) { return replaceWord(text, "'", "&apos;"); }

// simple isdigit check (no imports required)
bool isDigit(char c) { return ('0' <= c && c <= '9'); }

// removes/escapes/repaces special chars and splits buffer to lines
stringList preProcess(string text) {
  text = replaceWord(text, "\r", ""); // remove \r to support LF/CRLF
  text = escapeSq(escapeGt(escapeLt(escapeE(text))));
  return splitSep(text, '\n'); // …and split to lines
}

// parse / unquote config value
string getConfigValue(string line) {
  stringList parts = splitSep(line, '=');
  if (listCount(parts) > 1) {
    stringList tokens = splitSep(parts[1], '\"');
    if (parts[1][0] == '\"')
      return tokens[0];
    if (listCount(tokens) > 1)
      return tokens[1];
  }
  return "";
}

void readConfigFromLine(string line) {
  if (startsWith(line, "title"))
    title = join3s("  <title>", getConfigValue(line), "</title>\n");

  if (startsWith(line, "author"))
    author = join3s("  <author>\n    <name>", getConfigValue(line),
                    "</name>\n  </author>\n");

  if (startsWith(line, "remoteBaseUrl")) {
    remoteBaseUrl = getConfigValue(line);
    number urlLength = strlen(remoteBaseUrl);
    if (urlLength > 0 && remoteBaseUrl[urlLength - 1] == '/')
      remoteBaseUrl[urlLength - 1] = STR_END; // drop extra slash, if present
  }

  if (startsWith(line, "feedDir"))
    feedDir = getConfigValue(line);

  if (startsWith(line, "absoluteFeedDir"))
    feedDir = getConfigValue(line);

  if (startsWith(line, "maxAtomEntries"))
    maxAtomEntries = ofString(getConfigValue(line));

  if (startsWith(line, "langCode")) {
    string langCode = getConfigValue(line);
    rootMeta = join3s("<feed xmlns=\"http://www.w3.org/2005/Atom\" xml:lang=\"",
                      langCode, "\">\n\n");
    urlMetaFragment = join3s("\" rel=\"alternate\" hreflang=\"", langCode,
                             "\" />\n    <title>");
  }
}

bool loadConfigs(string configPath) {
  string config = readFile(configPath);
  if (config) {
    stringList lines = preProcess(config);
    forEach(listCount(lines), lines, &readConfigFromLine);
    return true;
  }
  return false;
}

// join lines back to single buffer and wrap entries to atom xml boilerplate
string postProcess(number linesCount, stringList lines) {
  return replaceWord(
      join3s(join4s("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n", rootMeta,
                    join5s(id, title, lastUpdated, author, links),
                    "  <generator "
                    "uri=\"https://git.sr.ht/~aprates/gempress\">"
                    "GemPress</generator>\n\n"),
             joinSep(linesCount, lines, '\n'), "\n</feed>\n"),
      "\n", "\r\n");
}

string toAtomEntry(string line) {
  if (startsWith(line, "=&gt;")) {          // => link (escaped)
    stringList words = splitSep(line, ' '); // tokenize the link
    number wordCount = listCount(words);    // count our tokens
    if (wordCount > 3) {                    // must have: => url date desc.
      string url = words[1];                // get url
      // using the initial part of the description as the date YYYY-MM-DD
      string description = joinSep(listCount(&words[2]), &words[2], ' ');
      string date = splitSep(description, ' ')[0];
      if (isDigit(date[0]) && isDigit(date[1]) && isDigit(date[2]) &&
          isDigit(date[3]) && date[4] == '-' && isDigit(date[5]) &&
          isDigit(date[6]) && date[7] == '-' && isDigit(date[9]) &&
          isDigit(date[9])) {
        date[10] = STR_END; // trim to 10 chars
        description = replaceWord(description, date, "");
        if (startsWith(description, " - "))
          description = &description[3];
        if (startsWith(description, " "))
          description = &description[1];
        string updated = join3s("  <updated>", date, "T00:00:00Z</updated>\n");
        if (!lastUpdated)
          lastUpdated = updated;
        else if (strcmp(updated, lastUpdated) > 0)
          lastUpdated = updated;
        url = startsWith(url, "/") ? url : join4s("/", feedDir, "/", url);
        url = maybeToHttps(join2s(remoteBaseUrl, url));
        return join3s(
            join3s("  <entry>\n    <id>", url, "</id>\n"),
            join4s("    <link href=\"", url, urlMetaFragment, description),
            join3s("</title>\n  ", updated, "  </entry>\n"));
      }
    }
  }
  return "";
}

void convert(string path) {
  if (startsWith(path, "https")) {
    convertToHttps = true;
    return;
  } else if (countWord(path, ".gmi")) { // ultra-simple path validadion
    string text = readFile(path); // read and hope content is text/gemini :D
    if (text) {                   // safe-gard / read failure
      id = join3s("  <id>", maybeToHttps(remoteBaseUrl), "/</id>\n");
      string url = maybeToHttps(join3s(remoteBaseUrl, "/", feedDir));
      links =
          join2s(join3s("  <link href=\"", url,
                        "/" OUTPUT_FILE "\" rel=\"self\" />\n"),
                 join3s("  <link href=\"", url, "/\" rel=\"alternate\" />\n"));
      stringList lines = preProcess(text);
      number lineCount = listCount(lines);
      for (number i = 0; i < lineCount && i < maxAtomEntries; i++)
        lines[i] = toAtomEntry(lines[i]); // do the magic :D
      string newPath = replaceWord(path, "index.gmi", OUTPUT_FILE);
      newPath = replaceWord(path, "feed.gmi", OUTPUT_FILE);
      writeFile(postProcess(lineCount, lines), newPath); // and save…
    } else
      println(join2s(path, " -> FAILED!")); // …or complain!
  }
}

app({
  if (argc < 3) {
    println("atom: provide args: <configFile> <file1.gmi> <file2.gmi>…");
  } else if (loadConfigs(argv[1]))
    forEach(argc - 2, &argv[2], &convert);
})