shithub: mapfs

ref: e78b966c9df18dce119421db741881d94a549dfd
dir: /cache.c/

View raw version
#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 m)
{
	int i;
	File *f;
	char buf[64];
	Dir *d;
	
	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 m)
{
	int i;
	File *f;
	char buf[5];
	
	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, m);
	}
}

void
inittree(File *root)
{
	File *f;
	int m;
	char buf[3];
	
	for (int 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");
		
		m = 1;
		for (int j = 0; j < i; j++)
			m *= 2;
		fillx(f, i, m);
	}
}

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);
	}
}