ref: 6863a7bb8b7c43fa58a6d4b07f36364cc7b29da7
dir: /cache.c/
#include <u.h>
#include <libc.h>
#include <fcall.h>
#include <thread.h>
#include <9p.h>
#include "dat.h"
#include "fns.h"
Bundle*
mkbundle(int z, int x, int y)
{
Bundle *ret = mallocz(sizeof(Bundle), 1);
if (!ret)
sysfatal("%r");
ret->x = x;
ret->y = y;
ret->z = z;
return ret;
}
void
filly(File *root, int z, int x)
{
int i, m;
File *f;
char buf[64];
Dir *d;
m = z*2;
if (m == 0)
m = 1;
for (i = 0; i < m; i++) {
snprint(buf, sizeof buf, "%d", i);
f = createfile(root, buf, uid, 0444, mkbundle(z, x, i));
if (!f)
sysfatal("createfile img %r");
snprint(buf, sizeof buf, "%s/%d/%d/%d", cache, z, x, i);
d = dirstat(buf);
if (!d)
continue;
f->length = d->length;
free(d);
}
}
void
fillx(File *root, int z)
{
int i, m;
File *f;
char buf[5];
m = z*2;
if (m == 0)
m = 1;
for (i = 0; i < m; i++) {
snprint(buf, sizeof buf, "%d", i);
f = createfile(root, buf, uid, 0777|DMDIR, nil);
if (!f)
sysfatal("createfile dir %r");
filly(f, z, i);
}
}
void
inittree(File *root)
{
File *f;
int i;
char buf[3];
for (i = 0; i <= maxzoom; i++) {
snprint(buf, sizeof buf, "%d", i);
f = createfile(root, buf, uid, 0555|DMDIR, nil);
if (!f)
sysfatal("createfile zoomdir %r");
fillx(f, i);
}
}
void
download(Bundle b, char *file)
{
char *cmd = smprint(
"mkdir -p `{basename -d '%s'} && "
"hget https://tile.openstreetmap.org/%d/%d/%d.png | "
"png -t9 > '%s'",
file, b.z, b.x, b.y, file);
execl("/bin/rc", "rc", "-c", cmd, nil);
}
void
requestfile(File *file, Bundle *b, char *dest)
{
int p[2];
int pid;
Dir *d;
switch (pid = fork()) {
case -1:
sysfatal("fork: %r");
default:
close(p[1]);
break;
case 0:
download(*b, dest);
sysfatal("download: %r");
}
while (waitpid() != pid)
;
d = dirstat(dest);
if (d) {
file->length = d->length;
free(d);
}
}