code:
package raie.mapcomponent;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.ContentConnection;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.location.Coordinates;

import com.nokia.mid.ui.gestures.GestureEvent;
import com.nokia.mid.ui.gestures.GestureInteractiveZone;
import com.nokia.mid.ui.gestures.GestureListener;
import com.nokia.mid.ui.gestures.GestureRegistrationManager;

public class MapComponent extends Canvas implements GestureListener {

	private String mapUrl;
	private int zoom;
	private Coordinates coord;
	private Image zoomIn=null;
	private Image zoomOut=null;
	private GestureInteractiveZone zoomInTouch;
	private GestureInteractiveZone zoomOutTouch;
	private GestureInteractiveZone scrollTouch;

	public MapComponent(){
		super();
	}

	public MapComponent(Coordinates coordinate, int zoomlevel){
		super();
		init();
		this.coord = coordinate;
		this.zoom = zoomlevel;
		this.mapUrl = "http://m.ovi.me/?nord&z="+this.zoom+"&f=1&c="+this.coord.getLatitude()+","+this.coord.getLongitude();
	}

	public void init(){
		this.zoom = 10;
		try {
			zoomIn = Image.createImage("/zoomin.png");
			zoomOut = Image.createImage("/zoomout.png");
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		GestureRegistrationManager.setListener(this, this);
		zoomInTouch = new GestureInteractiveZone(GestureInteractiveZone.GESTURE_TAP);
		zoomOutTouch = new GestureInteractiveZone(GestureInteractiveZone.GESTURE_TAP);
		scrollTouch = new GestureInteractiveZone(GestureInteractiveZone.GESTURE_FLICK);

        zoomInTouch.setRectangle(190, 60, 64, 64); //whole screen
        zoomOutTouch.setRectangle(190, 110, 64, 64); //whole screen
        scrollTouch.setRectangle(0, 0, getWidth(), getHeight());
        GestureRegistrationManager.register(this, zoomInTouch);
        GestureRegistrationManager.register(this, zoomOutTouch);
        GestureRegistrationManager.register(this, scrollTouch);
	}

	protected void paint(Graphics g) {
		int pos = Graphics.TOP|Graphics.LEFT;
		g.fillRect(0, 0, getWidth(), getHeight());
		Image mapImage = null;
		try{
			mapImage = getImageRequest(this.mapUrl);
		}catch(Exception e){}
		g.drawImage(mapImage, 0, 0, pos);
		g.drawImage(zoomIn, 190, 60, pos);
		g.drawImage(zoomOut, 190, 110, pos);
	}

	public void gestureAction(Object container,GestureInteractiveZone gestureInteractiveZone,GestureEvent gestureEvent) {
		if(gestureInteractiveZone.equals(zoomInTouch)){
			if(gestureEvent.getType() == GestureInteractiveZone.GESTURE_TAP){
				this.zoom = this.zoom + 1;
				this.mapUrl = "http://m.ovi.me/?nord&z="+this.zoom+"&f=1&c="+this.coord.getLatitude()+","+this.coord.getLongitude();
				repaint();
				System.err.println("says");
			}
		}
		if(gestureInteractiveZone.equals(zoomOutTouch)){
			if(gestureEvent.getType() == GestureInteractiveZone.GESTURE_TAP){
				this.zoom--;
				this.mapUrl = "http://m.ovi.me/?nord&z="+this.zoom+"&f=1&c="+this.coord.getLatitude()+","+this.coord.getLongitude();
				repaint();
			}
		}
		if(gestureInteractiveZone.equals(scrollTouch)){
			if(gestureEvent.getType() == GestureInteractiveZone.GESTURE_FLICK){
				System.err.println(gestureEvent.getFlickSpeedX()+","+gestureEvent.getFlickSpeedY());
				if(gestureEvent.getFlickSpeedX() != 0){
					if(this.coord.getLatitude()>0){
						this.coord.setLatitude(this.coord.getLatitude() + 3.60/zoom);
					}else{
						this.coord.setLatitude(this.coord.getLatitude() - 3.60/zoom);
					}
				}
				if(gestureEvent.getFlickSpeedY() != 0){
					if(this.coord.getLongitude() > 0){
						this.coord.setLongitude(this.coord.getLongitude() + 0.360/zoom);
					}else{
						this.coord.setLongitude(this.coord.getLongitude() - 0.360/zoom);
					}
				}
				this.mapUrl = "http://m.ovi.me/?nord&z="+this.zoom+"&f=1&c="+this.coord.getLatitude()+","+this.coord.getLongitude();
				repaint();
			}
		}
	}

	//utility function
	public static Image getImageRequest(String urlstring){
		Image im = null;
	   	byte imageData[];
	   	ContentConnection conn = null;
		DataInputStream strim = null;
		ByteArrayOutputStream oStrim = null;
		System.out.println(urlstring);
	   	try{
				conn = (ContentConnection) Connector.open(urlstring);
				strim = conn.openDataInputStream();
				int length = (int) conn.getLength();
				if(!(conn.getType().equals("image/jpeg")||
						conn.getType().equals("image/png")||
						conn.getType().equals("image/gif")||
						conn.getType().equals("image/bmp"))){
					try {
						im = Image.createImage("/gambar/stub2.png");
					} catch (IOException e) {
					}
				}else{
					if (length != -1){
						imageData = new byte[length];
						try{
							strim.read(imageData);
						}catch(Exception e){
							e.printStackTrace();
						}
					} else { // Length not available...
						oStrim = new ByteArrayOutputStream();
						int ch;
						while ((ch = strim.read()) != -1){
							oStrim.write(ch);
						}
						imageData = oStrim.toByteArray();
					}
					im = Image.createImage(imageData, 0, imageData.length);
				}
	   	}catch (Exception e) {
		}finally{
			try { if(oStrim!= null)  oStrim.close(); } catch (IOException ignored) {}
			try { if(strim != null) strim.close();} catch (IOException ignored) {}
			try { if(conn != null) conn.close();} catch (IOException ignored) {}
		}

		return im;
	}

	//getter-setter
	public String getMapUrl(){
		return this.mapUrl;
	}
	public int getZoomLevel(){
		return this.zoom;
	}
	public Coordinates getCoordinates(){
		return this.coord;
	}
	public void setMapUrl(String mapUrl){
		this.mapUrl = mapUrl;
	}
	public void setZoomLevel(int zoomLevel){
		this.zoom = zoomLevel;
	}
	public void setCoordinates(Coordinates c){
		this.coord = c;
	}
}


code:
package raie.mapcomponent;

import javax.microedition.lcdui.Display;
import javax.microedition.location.Coordinates;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class MapMidlet extends MIDlet {

	private MapComponent mc;

	protected void destroyApp(boolean unconditional)
			throws MIDletStateChangeException {
		// TODO Auto-generated method stub

	}

	protected void pauseApp() {
		// TODO Auto-generated method stub

	}

	protected void startApp() throws MIDletStateChangeException {
		Coordinates c = new Coordinates(-6.1753, 106.8272, 1);
		mc = new MapComponent(c,10);
		Display.getDisplay(this).setCurrent(mc);
	}

}

license: unknown


code:
Wine mod for Minetest

by TenPlus1

Depends: Farming Redo

This mod adds a barrel used to ferment grapes into glasses of wine, 9 of which can then be crafted into a bottle of wine.  It can also ferment honey into mead, barley into beer, wheat into weizen (wheat beer), corn into bourbon and apples into cider.

Change log:

- 0.1 - Initial release
- 0.2 - Added protection checks to barrel
- 0.3 - New barrel model from cottages mod (thanks Napiophelios), also wine glass can be placed
- 0.4 - Added ability to ferment barley from farming redo into beer and also honey from mobs redo into honey mead
- 0.5 - Added apple cider
- 0.6 - Added API so drinks can easily be added, also added wheat beer thanks to h-v-smacker and support for pipeworks/tubelib
- 0.7 - Blue Agave now appears in desert areas and spreads very slowly, can me fermented into tequila
- 0.8 - Barrel and Agave both use node timers now thanks to h-v-smacker, added sake
- 0.9 - Added Glass of Rum and Bottle of Rum thanks to acm :) Added {alcohol=1} groups
- 1.0 - Added glass and bottle or Bourbon made by fermenting corn
- 1.1 - Added glass and bottle of Vodka made by fermenting baked potato, Added MineClone2 support and spanish translation
- 1.2 - Added Unified Inventory support for barrel recipes (thanks to realmicu)
- 1.3 - Translations updated and French added thanks to TheDarkTiger

Lucky Blocks: 13

Wine Mod API
------------

wine:add_item(list)

e.g.

wine:add_item({
	{"farming:barley", "wine:glass_beer"},
	{"default:apple", "wine:glass_cider"},
})

repo_name: orbea/wine

license: mit


code:
default?
intllib?
lucky_block?
pipeworks?
bonemeal?
mcl_core?
mcl_sounds?
mcl_loot?
doc?
unified_inventory?
hunger_ng?


code:
local def = minetest.get_modpath("default")

wine = {
	snd_d = def and default.node_sound_defaults(),
	snd_g = def and default.node_sound_glass_defaults(),
	snd_l = def and default.node_sound_leaves_defaults(),
	sand = "default:desert_sand"
}

-- check for MineClone2
local mcl = minetest.get_modpath("mcl_core")

if mcl then
	wine.snd_d = mcl_sounds.node_sound_glass_defaults()
	wine.snd_g = mcl_sounds.node_sound_defaults()
	wine.snd_l = mcl_sounds.node_sound_leaves_defaults()
	wine.sand = "mcl_core:sand"
end

-- check for Unified Inventory
local is_uninv = minetest.global_exists("unified_inventory") or false

-- Intllib
local S
if minetest.get_modpath("intllib") then
	S = intllib.Getter()
else
	S = function(s, a, ...)
		if a == nil then
			return s
		end
		a = {a, ...}
		return s:gsub("(@?)@(%(?)(%d+)(%)?)",
			function(e, o, n, c)
				if e == ""then
					return a[tonumber(n)] .. (o == "" and c or "")
				else
					return "@" .. o .. n .. c
				end
			end)
	end
end

-- Unified Inventory hints
if is_uninv then
	unified_inventory.register_craft_type("barrel", {
		description = "Barrel",
		icon = 'wine_barrel.png',
		width = 1,
		height = 1,
	})
end

local ferment = {
	{"farming:grapes", "wine:glass_wine"},
	{"farming:barley", "wine:glass_beer"},
	{"mobs:honey", "wine:glass_mead"},
	{"default:apple", "wine:glass_cider"},
	{"default:papyrus", "wine:glass_rum"},
	{"wine:blue_agave", "wine:glass_tequila"},
	{"farming:wheat", "wine:glass_wheat_beer"},
	{"farming:rice", "wine:glass_sake"},
	{"farming:corn", "wine:glass_bourbon"},
	{"farming:baked_potato", "wine:glass_vodka"}
}

if mcl then
	ferment[4] = {"mcl_core:apple", "wine:glass_cider"}
	ferment[5] = {"mcl_core:paper", "wine:glass_rum"}
end

if is_uninv then
	for _, f in pairs(ferment) do
		unified_inventory.register_craft({
			type = "barrel",
			items = { f[1] },
			output = f[2],
		})
	end
end

function wine:add_item(list)

	for n = 1, #list do
		table.insert(ferment, list[n])
		if is_uninv then
			unified_inventory.register_craft({
				type = "barrel",
				items = { list[n][1] },
				output = list[n][2],
			})
		end
	end
end

-- glass of wine
minetest.register_node("wine:glass_wine", {
	description = S("Glass of Wine"),
	drawtype = "plantlike",
	visual_scale = 0.8,
	tiles = {"wine_glass.png"},
	inventory_image = "wine_glass.png",
	wield_image = "wine_glass.png",
	paramtype = "light",
	is_ground_content = false,
	sunlight_propagates = true,
	walkable = false,
	selection_box = {
		type = "fixed",
		fixed = {-0.2, -0.5, -0.2, 0.2, 0.3, 0.2}
	},
	groups = {
		food_wine = 1, vessel = 1, dig_immediate = 3, attached_node = 1,
		alcohol = 1
	},
	sounds = wine.snd_g,
	on_use = minetest.item_eat(2),
})

-- bottle of wine
minetest.register_node("wine:bottle_wine", {
	description = S("Bottle of Wine"),
	drawtype = "plantlike",
	tiles = {"wine_bottle.png"},
	inventory_image = "wine_bottle.png",
	paramtype = "light",
	sunlight_propagates = true,
	walkable = false,
	selection_box = {
		type = "fixed",
		fixed = { -0.15, -0.5, -0.15, 0.15, 0.25, 0.15 }
	},
	groups = {dig_immediate = 3, attached_node = 1, vessel = 1},
	sounds = wine.snd_d,
})

minetest.register_craft({
	output = "wine:bottle_wine",
	recipe = {
		{"wine:glass_wine", "wine:glass_wine", "wine:glass_wine"},
		{"wine:glass_wine", "wine:glass_wine", "wine:glass_wine"},
		{"wine:glass_wine", "wine:glass_wine", "wine:glass_wine"},
	},
})

minetest.register_craft({
	type = "shapeless",
	output = "wine:glass_wine 9",
	recipe = {"wine:bottle_wine"},
})

-- glass of rum
minetest.register_node("wine:glass_rum", {
	description = S("Rum"),
	drawtype = "plantlike",
	visual_scale = 0.8,
	tiles = {"wine_rum_glass.png"},
	inventory_image = "wine_rum_glass.png",
	wield_image = "wine_rum_glass.png",
	paramtype = "light",
	is_ground_content = false,
	sunlight_propagates = true,
	walkable = false,
	selection_box = {
		type = "fixed",
		fixed = {-0.2, -0.5, -0.2, 0.2, 0.3, 0.2}
	},
	groups = {
		food_rum = 1, vessel = 1, dig_immediate = 3, attached_node = 1,
		alcohol = 1
	},
	sounds = wine.snd_g,
	on_use = minetest.item_eat(2),
})

-- bottle of rum
minetest.register_node("wine:bottle_rum", {
	description = S("Bottle of Rum"),
	drawtype = "plantlike",
	tiles = {"wine_rum_bottle.png"},
	inventory_image = "wine_rum_bottle.png",
	paramtype = "light",
	sunlight_propagates = true,
	walkable = false,
	selection_box = {
		type = "fixed",
		fixed = { -0.15, -0.5, -0.15, 0.15, 0.25, 0.15 }
	},
	groups = {dig_immediate = 3, attached_node = 1, vessel = 1},
	sounds = wine.snd_d,
})

 minetest.register_craft({
	output = "wine:bottle_rum",
	recipe = {
		{"wine:glass_rum", "wine:glass_rum", "wine:glass_rum"},
		{"wine:glass_rum", "wine:glass_rum", "wine:glass_rum"},
		{"wine:glass_rum", "wine:glass_rum", "wine:glass_rum"},
	},
})

minetest.register_craft({
	type = "shapeless",
	output = "wine:glass_rum 9",
	recipe = {"wine:bottle_rum"},
})

-- glass of weizen, or wheat beer
-- The image is a lighter version of the one from RiverKpocc @ deviantart.com
minetest.register_node("wine:glass_wheat_beer", {
	description = S("Wheat Beer"),
	drawtype = "torchlike", --"plantlike",
	visual_scale = 0.8,
	tiles = {"wine_wheat_beer_glass.png"},
	inventory_image = "wine_wheat_beer_glass.png",
	wield_image = "wine_wheat_beer_glass.png",
	paramtype = "light",
	is_ground_content = false,
	sunlight_propagates = true,
	walkable = false,
	selection_box = {
		type = "fixed",
		fixed = {-0.2, -0.5, -0.2, 0.2, 0.3, 0.2}
	},
	groups = {
		food_beer = 1, vessel = 1, dig_immediate = 3, attached_node = 1,
		alcohol = 1
	},
	sounds = wine.snd_g,
	on_use = minetest.item_eat(2),
})

-- glass of beer (thanks to RiverKpocc @ deviantart.com for image)
minetest.register_node("wine:glass_beer", {
	description = S("Beer"),
	drawtype = "torchlike", --"plantlike",
	visual_scale = 0.8,
	tiles = {"wine_beer_glass.png"},
	inventory_image = "wine_beer_glass.png",
	wield_image = "wine_beer_glass.png",
	paramtype = "light",
	is_ground_content = false,
	sunlight_propagates = true,
	walkable = false,
	selection_box = {
		type = "fixed",
		fixed = {-0.2, -0.5, -0.2, 0.2, 0.3, 0.2}
	},
	groups = {
		food_beer = 1, vessel = 1, dig_immediate = 3, attached_node = 1,
		alcohol = 1
	},
	sounds = wine.snd_g,
	on_use = minetest.item_eat(2),
})

-- glass of honey mead
minetest.register_node("wine:glass_mead", {
	description = S("Honey-Mead"),
	drawtype = "plantlike",
	visual_scale = 0.8,
	tiles = {"wine_mead_glass.png"},
	inventory_image = "wine_mead_glass.png",
	wield_image = "wine_mead_glass.png",
	paramtype = "light",
	is_ground_content = false,
	sunlight_propagates = true,
	walkable = false,
	selection_box = {
		type = "fixed",
		fixed = {-0.2, -0.5, -0.2, 0.2, 0.3, 0.2}
	},
	groups = {
		food_mead = 1, vessel = 1, dig_immediate = 3, attached_node = 1,
		alcohol = 1
	},
	sounds = wine.snd_g,
	on_use = minetest.item_eat(4),
})

-- glass of apple cider
minetest.register_node("wine:glass_cider", {
	description = S("Apple Cider"),
	drawtype = "plantlike",
	visual_scale = 0.8,
	tiles = {"wine_cider_glass.png"},
	inventory_image = "wine_cider_glass.png",
	wield_image = "wine_cider_glass.png",
	paramtype = "light",
	is_ground_content = false,
	sunlight_propagates = true,
	walkable = false,
	selection_box = {
		type = "fixed",
		fixed = {-0.2, -0.5, -0.2, 0.2, 0.3, 0.2}
	},
	groups = {
		food_cider = 1, vessel = 1, dig_immediate = 3, attached_node = 1,
		alcohol = 1
	},
	sounds = wine.snd_g,
	on_use = minetest.item_eat(2),
})

-- glass of tequila
minetest.register_node("wine:glass_tequila", {
	description = S("Tequila"),
	drawtype = "plantlike",
	visual_scale = 0.8,
	tiles = {"wine_tequila.png"},
	inventory_image = "wine_tequila.png",
	wield_image = "wine_tequila.png",
	paramtype = "light",
	is_ground_content = false,
	sunlight_propagates = true,
	walkable = false,
	selection_box = {
		type = "fixed",
		fixed = {-0.2, -0.5, -0.2, 0.2, 0.3, 0.2}
	},
	groups = {
		food_tequila = 1, vessel = 1, dig_immediate = 3, attached_node = 1,
		alcohol = 1
	},
	sounds = wine.snd_g,
	on_use = minetest.item_eat(2),
})

-- bottle of tequila
minetest.register_node("wine:bottle_tequila", {
	description = S("Bottle of Tequila"),
	drawtype = "plantlike",
	tiles = {"wine_tequila_bottle.png"},
	inventory_image = "wine_tequila_bottle.png",
	paramtype = "light",
	sunlight_propagates = true,
	walkable = false,
	selection_box = {
		type = "fixed",
		fixed = { -0.15, -0.5, -0.15, 0.15, 0.25, 0.15 }
	},
	groups = {dig_immediate = 3, attached_node = 1, vessel = 1},
	sounds = wine.snd_d,
})

minetest.register_craft({
	output = "wine:bottle_tequila",
	recipe = {
		{"wine:glass_tequila", "wine:glass_tequila", "wine:glass_tequila"},
		{"wine:glass_tequila", "wine:glass_tequila", "wine:glass_tequila"},
		{"wine:glass_tequila", "wine:glass_tequila", "wine:glass_tequila"},
	},
})

minetest.register_craft({
	type = "shapeless",
	output = "wine:glass_tequila 9",
	recipe = {"wine:bottle_tequila"},
})

-- glass of sake
minetest.register_node("wine:glass_sake", {
	description = S("Sake"),
	drawtype = "plantlike",
	visual_scale = 0.8,
	tiles = {"wine_sake.png"},
	inventory_image = "wine_sake.png",
	wield_image = "wine_sake.png",
	paramtype = "light",
	is_ground_content = false,
	sunlight_propagates = true,
	walkable = false,
	selection_box = {
		type = "fixed",
		fixed = {-0.2, -0.5, -0.2, 0.2, 0.3, 0.2}
	},
	groups = {
		food_sake = 1, vessel = 1, dig_immediate = 3, attached_node = 1,
		alcohol = 1
	},
	sounds = wine.snd_g,
	on_use = minetest.item_eat(2),
})

-- glass of bourbon
minetest.register_node("wine:glass_bourbon", {
	description = S("Glass of Bourbon"),
	drawtype = "plantlike",
	visual_scale = 0.8,
	tiles = {"wine_bourbon_glass.png"},
	inventory_image = "wine_bourbon_glass.png",
	wield_image = "wine_bourbon_glass.png",
	paramtype = "light",
	is_ground_content = false,
	sunlight_propagates = true,
	walkable = false,
	selection_box = {
		type = "fixed",
		fixed = {-0.2, -0.5, -0.2, 0.2, 0.2, 0.2}
	},
	groups = {
		food_wine = 1, vessel = 1, dig_immediate = 3, attached_node = 1,
		alcohol = 1
	},
	sounds = wine.snd_g,
	on_use = minetest.item_eat(2),
})

-- bottle of bourbon
minetest.register_node("wine:bottle_bourbon", {
	description = S("Bottle of Bourbon"),
	drawtype = "plantlike",
	tiles = {"wine_bourbon_bottle.png"},
	inventory_image = "wine_bourbon_bottle.png",
	paramtype = "light",
	sunlight_propagates = true,
	walkable = false,
	selection_box = {
		type = "fixed",
		fixed = { -0.15, -0.5, -0.15, 0.15, 0.25, 0.15 }
	},
	groups = {dig_immediate = 3, attached_node = 1, vessel = 1},
	sounds = wine.snd_d,
})

minetest.register_craft({
	output = "wine:bottle_bourbon",
	recipe = {
		{"wine:glass_bourbon", "wine:glass_bourbon", "wine:glass_bourbon"},
		{"wine:glass_bourbon", "wine:glass_bourbon", "wine:glass_bourbon"},
		{"wine:glass_bourbon", "wine:glass_bourbon", "wine:glass_bourbon"},
	},
})

minetest.register_craft({
	type = "shapeless",
	output = "wine:glass_bourbon 9",
	recipe = {"wine:bottle_bourbon"},
})

-- glass of vodka
minetest.register_node("wine:glass_vodka", {
	description = S("Glass of Vodka"),
	drawtype = "plantlike",
	visual_scale = 0.8,
	tiles = {"wine_vodka_glass.png"},
	inventory_image = "wine_vodka_glass.png",
	wield_image = "wine_vodka_glass.png",
	paramtype = "light",
	is_ground_content = false,
	sunlight_propagates = true,
	walkable = false,
	selection_box = {
		type = "fixed",
		fixed = {-0.2, -0.5, -0.2, 0.2, 0.2, 0.2}
	},
	groups = {
		food_wine = 1, vessel = 1, dig_immediate = 3, attached_node = 1,
		alcohol = 1
	},
	sounds = wine.snd_g,
	on_use = minetest.item_eat(2),
})

-- bottle of vodka
minetest.register_node("wine:bottle_vodka", {
	description = S("Bottle of Vodka"),
	drawtype = "plantlike",
	tiles = {"wine_vodka_bottle.png"},
	inventory_image = "wine_vodka_bottle.png",
	paramtype = "light",
	sunlight_propagates = true,
	walkable = false,
	selection_box = {
		type = "fixed",
		fixed = { -0.15, -0.5, -0.15, 0.15, 0.25, 0.15 }
	},
	groups = {dig_immediate = 3, attached_node = 1, vessel = 1},
	sounds = wine.snd_d,
})

minetest.register_craft({
	output = "wine:bottle_vodka",
	recipe = {
		{"wine:glass_vodka", "wine:glass_vodka", "wine:glass_vodka"},
		{"wine:glass_vodka", "wine:glass_vodka", "wine:glass_vodka"},
		{"wine:glass_vodka", "wine:glass_vodka", "wine:glass_vodka"},
	},
})

minetest.register_craft({
	type = "shapeless",
	output = "wine:glass_vodka 9",
	recipe = {"wine:bottle_vodka"},
})

-- blue agave
minetest.register_node("wine:blue_agave", {
	description = S("Blue Agave"),
	drawtype = "plantlike",
	visual_scale = 0.8,
	tiles = {"wine_blue_agave.png"},
	inventory_image = "wine_blue_agave.png",
	wield_image = "wine_blue_agave.png",
	paramtype = "light",
	is_ground_content = false,
	sunlight_propagates = true,
	walkable = false,
	selection_box = {
		type = "fixed",
		fixed = {-0.2, -0.5, -0.2, 0.2, 0.3, 0.2}
	},
	groups = {snappy = 3, attached_node = 1, plant = 1},
	sounds = wine.snd_l,

	on_construct = function(pos)

		local timer = minetest.get_node_timer(pos)

		timer:start(17)
	end,

	on_timer = function(pos)

		local light = minetest.get_node_light(pos)

		if not light or light < 13 or math.random() > 1/76 then
			return true -- go to next iteration
		end

		local n = minetest.find_nodes_in_area_under_air(
			{x = pos.x + 2, y = pos.y + 1, z = pos.z + 2},
			{x = pos.x - 2, y = pos.y - 1, z = pos.z - 2},
			{"wine:blue_agave"})

		-- too crowded, we'll wait for another iteration
		if #n > 2 then
			return true
		end

		-- find desert sand with air above (grow across and down only)
		n = minetest.find_nodes_in_area_under_air(
			{x = pos.x + 1, y = pos.y - 1, z = pos.z + 1},
			{x = pos.x - 1, y = pos.y - 2, z = pos.z - 1},
			{wine.sand})

		-- place blue agave
		if n and #n > 0 then

			local new_pos = n[math.random(#n)]

			new_pos.y = new_pos.y + 1

			minetest.set_node(new_pos, {name = "wine:blue_agave"})
		end

		return true
	end
})

minetest.register_craft( {
	type = "shapeless",
	output = "dye:cyan 4",
	recipe = {"wine:blue_agave"}
})

minetest.register_decoration({
	deco_type = "simple",
	place_on = {wine.sand},
	sidelen = 16,
	fill_ratio = 0.001,
	biomes = {"desert"},
	decoration = {"wine:blue_agave"},
	y_min = 15,
	y_max = 50,
	spawn_by = wine.sand,
	num_spawn_by = 6,
})

if minetest.get_modpath("bonemeal") then
	bonemeal:add_deco({
		{wine.sand, {}, {"default:dry_shrub", "wine:blue_agave", "", ""} }
	})
end

if minetest.get_modpath("hunger_ng") then
	local hunger = hunger_ng.add_hunger_data

	hunger("wine:glass_wine",       { satiates = 1.5 })
	hunger("wine:glass_rum",        { satiates = 1.5 })
	hunger("wine:glass_wheat_beer", { satiates = 1.5 })
	hunger("wine:glass_beer",       { satiates = 1.5 })
	hunger("wine:glass_mead",       { satiates = 2 })
	hunger("wine:glass_cider",      { satiates = 1.5 })
	hunger("wine:glass_tequila",    { satiates = 1.5 })
	hunger("wine:glass_sake",       { satiates = 1.5 })
	hunger("wine:glass_bourbon",    { satiates = 1.5 })
	hunger("wine:glass_vodka",      { satiates = 1.5 })
end

-- Wine barrel
winebarrel_formspec = "size[8,9]"
	.. "list[current_name;src;2,1;1,1;]"
	.. "list[current_name;dst;5,1;1,1;]"
	.. "list[current_player;main;0,5;8,4;]"
	.. "listring[current_name;dst]"
	.. "listring[current_player;main]"
	.. "listring[current_name;src]"
	.. "listring[current_player;main]"
	.. "image[3.5,1;1,1;gui_furnace_arrow_bg.png^[transformR270]"

minetest.register_node("wine:wine_barrel", {
	description = S("Fermenting Barrel"),
	tiles = {"wine_barrel.png" },
	drawtype = "mesh",
	mesh = "wine_barrel.obj",
	paramtype = "light",
	paramtype2 = "facedir",
	groups = {
		choppy = 2, oddly_breakable_by_hand = 1, flammable = 2,
		tubedevice = 1, tubedevice_receiver = 1
	},
	legacy_facedir_simple = true,

	on_place = minetest.rotate_node,

	on_construct = function(pos)

		local meta = minetest.get_meta(pos)

		meta:set_string("formspec", winebarrel_formspec)
		meta:set_string("infotext", S("Fermenting Barrel"))
		meta:set_float("status", 0.0)

		local inv = meta:get_inventory()

		inv:set_size("src", 1)
		inv:set_size("dst", 1)
	end,

	can_dig = function(pos,player)

		local meta = minetest.get_meta(pos)
		local inv = meta:get_inventory()

		if not inv:is_empty("dst")
		or not inv:is_empty("src") then
			return false
		end

		return true
	end,

	allow_metadata_inventory_take = function(pos, listname, index, stack, player)

		if minetest.is_protected(pos, player:get_player_name()) then
			return 0
		end

		return stack:get_count()
	end,

	allow_metadata_inventory_put = function(pos, listname, index, stack, player)

		if minetest.is_protected(pos, player:get_player_name()) then
			return 0
		end

		local meta = minetest.get_meta(pos)
		local inv = meta:get_inventory()

		if listname == "src" then
			return stack:get_count()
		elseif listname == "dst" then
			return 0
		end
	end,

	allow_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player)

		if minetest.is_protected(pos, player:get_player_name()) then
			return 0
		end

		local meta = minetest.get_meta(pos)
		local inv = meta:get_inventory()
		local stack = inv:get_stack(from_list, from_index)

		if to_list == "src" then
			return count
		elseif to_list == "dst" then
			return 0
		end
	end,

	on_metadata_inventory_put = function(pos)

		local timer = minetest.get_node_timer(pos)

		timer:start(5)
	end,

	tube = (function() if minetest.get_modpath("pipeworks") then return {

		-- using a different stack from defaut when inserting
		insert_object = function(pos, node, stack, direction)

			local meta = minetest.get_meta(pos)
			local inv = meta:get_inventory()
			local timer = minetest.get_node_timer(pos)

			if not timer:is_started() then
				timer:start(5)
			end

			return inv:add_item("src", stack)
		end,

		can_insert = function(pos,node,stack,direction)

			local meta = minetest.get_meta(pos)
			local inv = meta:get_inventory()

			return inv:room_for_item("src", stack)
		end,

		-- the default stack, from which objects will be taken
		input_inventory = "dst",
		connect_sides = {left = 1, right = 1, back = 1, front = 1, bottom = 1, top = 1}
	} end end)(),

	on_timer = function(pos)

		local meta = minetest.get_meta(pos) ; if not meta then return end
		local inv = meta:get_inventory()

		-- is barrel empty?
		if not inv or inv:is_empty("src") then

			meta:set_float("status", 0.0)
			meta:set_string("infotext", S("Fermenting Barrel"))

			return false
		end

		-- does it contain any of the source items on the list?
		local has_item

		for n = 1, #ferment do

			if inv:contains_item("src", ItemStack(ferment[n][1])) then

				has_item = n

				break
			end
		end

		if not has_item then
			return false
		end

		-- is there room for additional fermentation?
		if not inv:room_for_item("dst", ferment[has_item][2]) then

			meta:set_string("infotext", S("Fermenting Barrel (FULL)"))

			return true
		end

		local status = meta:get_float("status")

		-- fermenting (change status)
		if status < 100 then
			meta:set_string("infotext", S("Fermenting Barrel (@1% Done)", status))
			meta:set_float("status", status + 5)
		else
			inv:remove_item("src", ferment[has_item][1])
			inv:add_item("dst", ferment[has_item][2])

			meta:set_float("status", 0,0)
		end

		if inv:is_empty("src") then
			meta:set_float("status", 0.0)
			meta:set_string("infotext", S("Fermenting Barrel"))
		end

		return true
	end,
})

if mcl then

	minetest.register_craft({
		output = "wine:wine_barrel",
		recipe = {
			{"group:wood", "group:wood", "group:wood"},
			{"mcl_core:iron_ingot", "", "mcl_core:iron_ingot"},
			{"group:wood", "group:wood", "group:wood"},
		},
	})
else
	minetest.register_craft({
		output = "wine:wine_barrel",
		recipe = {
			{"group:wood", "group:wood", "group:wood"},
			{"default:steel_ingot", "", "default:steel_ingot"},
			{"group:wood", "group:wood", "group:wood"},
		},
	})
end

-- LBMs to start timers on existing, ABM-driven nodes
minetest.register_lbm({
	name = "wine:barrel_timer_init",
	nodenames = {"wine:wine_barrel"},
	run_at_every_load = false,
	action = function(pos)

		local t = minetest.get_node_timer(pos)

		t:start(5)
	end,
})

minetest.register_lbm({
	name = "wine:agave_timer_init",
	nodenames = {"wine:blue_agave"},
	run_at_every_load = false,
	action = function(pos)

		local t = minetest.get_node_timer(pos)

		t:start(17)
	end,
})

-- add lucky blocks
if minetest.get_modpath("lucky_block") then

	lucky_block:add_blocks({
		{"dro", {"wine:glass_wine"}, 5},
		{"dro", {"wine:glass_beer"}, 5},
		{"dro", {"wine:glass_wheat_beer"}, 5},
		{"dro", {"wine:glass_mead"}, 5},
		{"dro", {"wine:glass_cider"}, 5},
		{"dro", {"wine:glass_rum"}, 5},
		{"dro", {"wine:glass_tequila"}, 5},
		{"dro", {"wine:glass_bourbon"}, 5},
		{"dro", {"wine:glass_vodka"}, 5},
		{"dro", {"wine:wine_barrel"}, 1},
		{"tel", 5, 1},
		{"nod", "default:chest", 0, {
			{name = "wine:bottle_wine", max = 1},
			{name = "wine:bottle_tequila", max = 1},
			{name = "wine:bottle_rum", max = 1},
			{name = "wine:bottle_bourbon", max = 1},
			{name = "wine:bottle_vodka", max = 1},
			{name = "wine:wine_barrel", max = 1},
			{name = "wine:blue_agave", max = 4}}},
	})
end

print (S("[MOD] Wine loaded"))


code:
# Deutsche Übersetzung der wine Mod
# textdomain: wine
# Author: Xanthin
# Author: TheDarkTiger
# last update: 2020/Apr/26

Glass of Wine=Glas Wein
Bottle of Wine=Flasche Wein
Rum=Rum
Bottle of Rum=Flasche Rum
Wheat Beer=Weizenbier
Beer=Bier
Honey-Mead=Honigwein
Apple Cider=Apfelwein
Tequila=Tequila
Bottle of Tequila=Flasche Tequilla
Sake=Sake
Glass of Bourbon=Glas Bourbon
Bottle of Bourbon=Flasche Bourbon
Glass of Vodka=Glas Wodka
Bottle of Vodka=Flasche Wodka
Blue Agave=Agave
Fermenting Barrel=Gärfass
Fermenting Barrel (FULL)=Gärfass (VOLL)
Fermenting Barrel (@1% Done)=Gärfass (@1% erledigt)
[MOD] Wine loaded=[MOD] Wine geladen


code:
# Traducción al español del mod Wine por TenPlus1
# textdomain: wine
# author: Unknown
# author: TenPlus1
# author: TheDarkTiger
# last update: 2020/Apr/26

Glass of Wine=Copa de vino
Bottle of Wine=Botella de vino
Rum=Ron
Bottle of Rum=Botella de Ron
Wheat Beer=Cerveza de trigo
Beer=Cerveza
Honey-Mead=Bebida de miel
Apple Cider=Sidra de manzana
Tequila=Tequíla
Bottle of Tequila=Botella de Tequíla
Sake=Sake
Glass of Bourbon=Copa de Borbón
Bottle of Bourbon=Botella de Borbón
Glass of Vodka=Copa de Vodka
Bottle of Vodka=Botella de Vodka
Blue Agave=Agave Tequilana
Fermenting Barrel=Barril de fermentación
Fermenting Barrel (FULL)=Barril de fermentación (Lleno)
Fermenting Barrel (@1% Done)=Barril de fermentación (@1% completado)
[MOD] Wine loaded=[MOD] Wine cargado


code:
# Traduction Française du mod Wine par TenPlus1
# textdomain: wine
# author: TheDarkTiger
# last update: 2020/Apr/25

Glass of Wine=Verre de Vin
Bottle of Wine=Bouteille de Vin
Rum=Rhum
Bottle of Rum=Bouteille de Rhum
Wheat Beer=Bière de Blé
Beer=Bière
Honey-Mead=Hydromel
Apple Cider=Cidre Brut
Tequila=Tequila
Bottle of Tequila=Bouteille de Tequila
Sake=Saké
Glass of Bourbon=Verre de Bourbon
Bottle of Bourbon=Bouteille de Bourbon
Glass of Vodka=Verre de Vodka
Bottle of Vodka=Bouteille de Vodka
Blue Agave=Agave Bleue
Fermenting Barrel=Baril de fermentation
Fermenting Barrel (FULL)=Baril de fermentation (PLEIN)
Fermenting Barrel (@1% Done)=Baril de fermentation (En cours @1%)
[MOD] Wine loaded=[MOD] Wine chargé


code:
# Template for translations of wine mod
# textdomain: wine
# author: ?
# last update: 2020/Apr/26

Glass of Wine=
Bottle of Wine=
Rum=
Bottle of Rum=
Wheat Beer=
Beer=
Honey-Mead=
Apple Cider=
Tequila=
Bottle of Tequila=
Sake=
Glass of Bourbon=
Bottle of Bourbon=
Glass of Vodka=
Bottle of Vodka=
Blue Agave=
Fermenting Barrel=
Fermenting Barrel (FULL)=
Fermenting Barrel (@1% Done)=
[MOD] Wine loaded=


code:
/.env
/.vscode
/.idea
/.data/*
./app/**
.DS_Store

repo_name: VlaDDoS/xdebug

path: .gitignore


code:
<?php

echo "It's alive";


code:
version: '3'

services:

        app:
            build:
                context: ./docker/php-fpm
                args:
                    - timezone=${TZ}
            volumes:
                - ./app:/app:rw,cached
                - app_log:/app/var/log
            env_file:
                - .env
            depends_on:
                - mysql
            environment:
                XDEBUG_CONFIG: idekey=PHPSTORM remote_host=${XDEBUG_REMOTE_HOST} remote_port=9000
                PHP_IDE_CONFIG: serverName=${NGINX_HOST}
            container_name: app

        nginx:
            build:
                context: ./docker/nginx
                args:
                    - nginx_host=${NGINX_HOST}
            ports:
                - "80:80"
                - "443:443"
            depends_on:
                - app
            volumes:
                - ./app:/app:ro
                - ./docker/nginx/default.template:/etc/nginx/conf.d/default.template
                - nginx_log:/var/log/nginx
            env_file:
                - .env
            command: /bin/bash -c "envsubst '$$NGINX_HOST'
                < /etc/nginx/conf.d/default.template
                > /etc/nginx/conf.d/default.conf
                && exec nginx -g 'daemon off;'"
            container_name: nginx

        mysql:
            build:
                context: ./docker/db
                dockerfile: Dockerfile.mysql
            volumes:
                - ./.data/mysql:/var/lib/mysql:rw
            env_file:
                - .env
            ports:
                - "3306:3306"
            container_name: db

        redis:
            build:
                context: ./docker/redis
            container_name: redis

volumes:
    nginx_log:
    app_log:


code:
FROM mongo:3.4

ARG mongodb_username
ARG mongodb_password
ARG mongodb_initdb_database

COPY mongo-setup.js /docker-entrypoint-initdb.d/

RUN sed -i -e "s/MONGODB_USERNAME/$mongodb_username/g" /docker-entrypoint-initdb.d/mongo-setup.js
RUN sed -i -e "s/MONGODB_PASSWORD/$mongodb_password/g" /docker-entrypoint-initdb.d/mongo-setup.js
RUN sed -i -e "s/MONGO_INITDB_DATABASE/$mongodb_initdb_database/g" /docker-entrypoint-initdb.d/mongo-setup.js


code:
FROM mysql:8

COPY mysql.cnf /etc/mysql/conf.d/custom.cnf


code:
# doctrine/dbal v2.7.0 is required to use entirely postgres v10.1
# https://github.com/doctrine/dbal/pull/2893
# https://github.com/doctrine/dbal/milestone/59
FROM postgres:9.6


code:
db.createUser(
    {
        user: "MONGODB_USERNAME",
        pwd: "MONGODB_PASSWORD",
        roles: [ { role: "dbOwner", db: "MONGO_INITDB_DATABASE" } ]
    }
)


code:
[mysqld]
# Version 5.5.3 introduced "utf8mb4", which is recommended
collation-server     = utf8mb4_unicode_ci
character-set-server = utf8mb4


code:
FROM nginx:1.13

ARG nginx_host

RUN apt-get update && apt-get install --no-install-recommends --no-install-suggests -y \
        openssl \
    && rm -rf /var/lib/apt/lists/*

COPY openssl.cnf /etc/ssl/openssl.cnf
RUN sed -i -e "s/NGINX_HOST/$nginx_host/g" /etc/ssl/openssl.cnf

RUN openssl genrsa -des3 -passout pass:NotSecure -out /etc/ssl/server.pass.key 2048
RUN openssl rsa -passin pass:NotSecure -in /etc/ssl/server.pass.key -out /etc/ssl/server.key
RUN rm /etc/ssl/server.pass.key
RUN openssl req -new -passout pass:NotSecure -key /etc/ssl/server.key -out /etc/ssl/server.csr \
    -subj "/C=MX/ST=Mexico/L=Mexico/O=Symfony/CN=$nginx_host" -config /etc/ssl/openssl.cnf
RUN openssl x509 -req -sha256 -days 365 -in /etc/ssl/server.csr -signkey /etc/ssl/server.key \
    -out /etc/ssl/server.crt -extensions v3_req -extfile /etc/ssl/openssl.cnf

ADD nginx.conf /etc/nginx/

RUN rm /var/log/nginx/access.log /var/log/nginx/error.log

path: docker/nginx/Dockerfile


code:
server {
    listen 80;
    listen 443 ssl;
    server_name ${NGINX_HOST};
    ssl_certificate /etc/ssl/server.crt;
    ssl_certificate_key /etc/ssl/server.key;
    root /app;

    location / {
            # try to serve file directly, fallback to index.php
            try_files $uri /index.php$is_args$args;
    }

    location ~ ^/index\.php(/|$) {
            fastcgi_pass app:9000;
            fastcgi_split_path_info ^(.+\.php)(/.*)$;
            include fastcgi_params;

            # optionally set the value of the environment variables used in the application
            # fastcgi_param APP_ENV prod;
            # fastcgi_param APP_SECRET <app-secret-id>;
            # fastcgi_param DATABASE_URL "mysql://db_user:db_pass@host:3306/db_name";

            # When you are using symlinks to link the document root to the
            # current version of your application, you should pass the real
            # application path instead of the path to the symlink to PHP
            # FPM.
            # Otherwise, PHP's OPcache may not properly detect changes to
            # your PHP files (see https://github.com/zendtech/ZendOptimizerPlus/issues/126
            # for more information).
            fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
            fastcgi_param DOCUMENT_ROOT $realpath_root;

            # Prevents URIs that include the front controller. This will 404:
            # http://domain.tld/index.php/some-path
            # Remove the internal directive to allow URIs like this
            internal;
    }

    # return 404 for all other php files not matching the front controller
    # this prevents access to other php files you don't want to be accessible.
    location ~ \.php$ {
        return 404;
    }

    error_log /var/log/nginx/app_error.log;
    access_log /var/log/nginx/app_access.log;
}


code:
user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}


code:
#
# OpenSSL example configuration file.
# This is mostly being used for generation of certificate requests.
#

# This definition stops the following lines choking if HOME isn't
# defined.
HOME			= .
RANDFILE		= $ENV::HOME/.rnd

# Extra OBJECT IDENTIFIER info:
#oid_file		= $ENV::HOME/.oid
oid_section		= new_oids

# To use this configuration file with the "-extfile" option of the
# "openssl x509" utility, name here the section containing the
# X.509v3 extensions to use:
# extensions		=
# (Alternatively, use a configuration file that has only
# X.509v3 extensions in its main [= default] section.)

[ new_oids ]

# We can add new OIDs in here for use by 'ca', 'req' and 'ts'.
# Add a simple OID like this:
# testoid1=1.2.3.4
# Or use config file substitution like this:
# testoid2=${testoid1}.5.6

# Policies used by the TSA examples.
tsa_policy1 = 1.2.3.4.1
tsa_policy2 = 1.2.3.4.5.6
tsa_policy3 = 1.2.3.4.5.7

####################################################################
[ ca ]
default_ca	= CA_default		# The default ca section

####################################################################
[ CA_default ]

dir		= ./demoCA		# Where everything is kept
certs		= $dir/certs		# Where the issued certs are kept
crl_dir		= $dir/crl		# Where the issued crl are kept
database	= $dir/index.txt	# database index file.
#unique_subject	= no			# Set to 'no' to allow creation of
					# several certs with same subject.
new_certs_dir	= $dir/newcerts		# default place for new certs.

certificate	= $dir/cacert.pem 	# The CA certificate
serial		= $dir/serial 		# The current serial number
crlnumber	= $dir/crlnumber	# the current crl number
					# must be commented out to leave a V1 CRL
crl		= $dir/crl.pem 		# The current CRL
private_key	= $dir/private/cakey.pem# The private key
RANDFILE	= $dir/private/.rand	# private random number file

x509_extensions	= usr_cert		# The extensions to add to the cert

# Comment out the following two lines for the "traditional"
# (and highly broken) format.
name_opt 	= ca_default		# Subject Name options
cert_opt 	= ca_default		# Certificate field options

# Extension copying option: use with caution.
# copy_extensions = copy

# Extensions to add to a CRL. Note: Netscape communicator chokes on V2 CRLs
# so this is commented out by default to leave a V1 CRL.
# crlnumber must also be commented out to leave a V1 CRL.
# crl_extensions	= crl_ext

default_days	= 365			# how long to certify for
default_crl_days= 30			# how long before next CRL
default_md	= default		# use public key default MD
preserve	= no			# keep passed DN ordering

# A few difference way of specifying how similar the request should look
# For type CA, the listed attributes must be the same, and the optional
# and supplied fields are just that :-)
policy		= policy_match

# For the CA policy
[ policy_match ]
countryName		= match
stateOrProvinceName	= match
organizationName	= match
organizationalUnitName	= optional
commonName		= supplied
emailAddress		= optional

# For the 'anything' policy
# At this point in time, you must list all acceptable 'object'
# types.
[ policy_anything ]
countryName		= optional
stateOrProvinceName	= optional
localityName		= optional
organizationName	= optional
organizationalUnitName	= optional
commonName		= supplied
emailAddress		= optional

####################################################################
[ req ]
default_bits		= 2048
default_keyfile 	= privkey.pem
distinguished_name	= req_distinguished_name
attributes		= req_attributes
x509_extensions	= v3_ca	# The extensions to add to the self signed cert

# Passwords for private keys if not present they will be prompted for
# input_password = secret
# output_password = secret

# This sets a mask for permitted string types. There are several options.
# default: PrintableString, T61String, BMPString.
# pkix	 : PrintableString, BMPString (PKIX recommendation before 2004)
# utf8only: only UTF8Strings (PKIX recommendation after 2004).
# nombstr : PrintableString, T61String (no BMPStrings or UTF8Strings).
# MASK:XXXX a literal mask value.
# WARNING: ancient versions of Netscape crash on BMPStrings or UTF8Strings.
string_mask = utf8only

# req_extensions = v3_req # The extensions to add to a certificate request

[ req_distinguished_name ]
countryName			= Country Name (2 letter code)
countryName_default		= AU
countryName_min			= 2
countryName_max			= 2

stateOrProvinceName		= State or Province Name (full name)
stateOrProvinceName_default	= Some-State

localityName			= Locality Name (eg, city)

0.organizationName		= Organization Name (eg, company)
0.organizationName_default	= Internet Widgits Pty Ltd

# we can do this but it is not needed normally :-)
#1.organizationName		= Second Organization Name (eg, company)
#1.organizationName_default	= World Wide Web Pty Ltd

organizationalUnitName		= Organizational Unit Name (eg, section)
#organizationalUnitName_default	=

commonName			= Common Name (e.g. server FQDN or YOUR name)
commonName_max			= 64

emailAddress			= Email Address
emailAddress_max		= 64

# SET-ex3			= SET extension number 3

[ req_attributes ]
challengePassword		= A challenge password
challengePassword_min		= 4
challengePassword_max		= 20

unstructuredName		= An optional company name

[ usr_cert ]

# These extensions are added when 'ca' signs a request.

# This goes against PKIX guidelines but some CAs do it and some software
# requires this to avoid interpreting an end user certificate as a CA.

basicConstraints=CA:FALSE

# Here are some examples of the usage of nsCertType. If it is omitted
# the certificate can be used for anything *except* object signing.

# This is OK for an SSL server.
# nsCertType			= server

# For an object signing certificate this would be used.
# nsCertType = objsign

# For normal client use this is typical
# nsCertType = client, email

# and for everything including object signing:
# nsCertType = client, email, objsign

# This is typical in keyUsage for a client certificate.
# keyUsage = nonRepudiation, digitalSignature, keyEncipherment

# This will be displayed in Netscape's comment listbox.
nsComment			= "OpenSSL Generated Certificate"

# PKIX recommendations harmless if included in all certificates.
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer

# This stuff is for subjectAltName and issuerAltname.
# Import the email address.
# subjectAltName=email:copy
# An alternative to produce certificates that aren't
# deprecated according to PKIX.
# subjectAltName=email:move

# Copy subject details
# issuerAltName=issuer:copy

#nsCaRevocationUrl		= http://www.domain.dom/ca-crl.pem
#nsBaseUrl
#nsRevocationUrl
#nsRenewalUrl
#nsCaPolicyUrl
#nsSslServerName

# This is required for TSA certificates.
# extendedKeyUsage = critical,timeStamping

[ v3_req ]

# Extensions to add to a certificate request

basicConstraints = CA:TRUE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment

subjectAltName = @alt_names
[alt_names]
DNS.1 = NGINX_HOST

[ v3_ca ]

# Extensions for a typical CA

# PKIX recommendation.

subjectKeyIdentifier=hash

authorityKeyIdentifier=keyid:always,issuer

basicConstraints = critical,CA:true

# Key usage: this is typical for a CA certificate. However since it will
# prevent it being used as an test self-signed certificate it is best
# left out by default.
# keyUsage = cRLSign, keyCertSign

# Some might want this also
# nsCertType = sslCA, emailCA

# Include email address in subject alt name: another PKIX recommendation
# subjectAltName=email:copy
# Copy issuer details
# issuerAltName=issuer:copy

# DER hex encoding of an extension: beware experts only!
# obj=DER:02:03
# Where 'obj' is a standard or added object
# You can even override a supported extension:
# basicConstraints= critical, DER:30:03:01:01:FF

[ crl_ext ]

# CRL extensions.
# Only issuerAltName and authorityKeyIdentifier make any sense in a CRL.

# issuerAltName=issuer:copy
authorityKeyIdentifier=keyid:always

[ proxy_cert_ext ]
# These extensions should be added when creating a proxy certificate

# This goes against PKIX guidelines but some CAs do it and some software
# requires this to avoid interpreting an end user certificate as a CA.

basicConstraints=CA:FALSE

# Here are some examples of the usage of nsCertType. If it is omitted
# the certificate can be used for anything *except* object signing.

# This is OK for an SSL server.
# nsCertType			= server

# For an object signing certificate this would be used.
# nsCertType = objsign

# For normal client use this is typical
# nsCertType = client, email

# and for everything including object signing:
# nsCertType = client, email, objsign

# This is typical in keyUsage for a client certificate.
# keyUsage = nonRepudiation, digitalSignature, keyEncipherment

# This will be displayed in Netscape's comment listbox.
nsComment			= "OpenSSL Generated Certificate"

# PKIX recommendations harmless if included in all certificates.
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer

# This stuff is for subjectAltName and issuerAltname.
# Import the email address.
# subjectAltName=email:copy
# An alternative to produce certificates that aren't
# deprecated according to PKIX.
# subjectAltName=email:move

# Copy subject details
# issuerAltName=issuer:copy

#nsCaRevocationUrl		= http://www.domain.dom/ca-crl.pem
#nsBaseUrl
#nsRevocationUrl
#nsRenewalUrl
#nsCaPolicyUrl
#nsSslServerName

# This really needs to be in place for it to be a proxy certificate.
proxyCertInfo=critical,language:id-ppl-anyLanguage,pathlen:3,policy:foo

####################################################################
[ tsa ]

default_tsa = tsa_config1	# the default TSA section

[ tsa_config1 ]

# These are used by the TSA reply generation only.
dir		= ./demoCA		# TSA root directory
serial		= $dir/tsaserial	# The current serial number (mandatory)
crypto_device	= builtin		# OpenSSL engine to use for signing
signer_cert	= $dir/tsacert.pem 	# The TSA signing certificate
					# (optional)
certs		= $dir/cacert.pem	# Certificate chain to include in reply
					# (optional)
signer_key	= $dir/private/tsakey.pem # The TSA private key (optional)
signer_digest  = sha256			# Signing digest to use. (Optional)
default_policy	= tsa_policy1		# Policy if request did not specify it
					# (optional)
other_policies	= tsa_policy2, tsa_policy3	# acceptable policies (optional)
digests     = sha1, sha256, sha384, sha512  # Acceptable message digests (mandatory)
accuracy	= secs:1, millisecs:500, microsecs:100	# (optional)
clock_precision_digits  = 0	# number of digits after dot. (optional)
ordering		= yes	# Is ordering defined for timestamps?
				# (optional, default: no)
tsa_name		= yes	# Must the TSA name be included in the reply?
				# (optional, default: no)
ess_cert_id_chain	= no	# Must the ESS cert id chain be included?
				# (optional, default: no)


code:
FROM php:8.1-fpm

ARG timezone

RUN apt-get update && apt-get install --no-install-recommends --no-install-suggests -y \
		git \
        cron\
        unzip \
        vim \
        libicu-dev \
        zlib1g-dev \
        libssl-dev \
        pkg-config \
        libzip-dev \
        libpq-dev \
    && rm -rf /var/lib/apt/lists/*

RUN set -xe \
    && docker-php-ext-configure \
        intl \
    && docker-php-ext-install \
        intl \
        opcache \
        zip \
        pdo \
        pdo_mysql \
    && pecl install \
        apcu \
        xdebug \
        redis \
    && docker-php-ext-enable \
        apcu \
        xdebug \
        redis

COPY php.ini /usr/local/etc/php/php.ini
RUN sed -i -e "s#TIMEZONE#$timezone#g" /usr/local/etc/php/php.ini

COPY xdebug.ini /tmp/xdebug.ini
RUN cat /tmp/xdebug.ini >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
RUN rm /tmp/xdebug.ini

COPY --from=composer:1.6 /usr/bin/composer /usr/bin/composer
ENV COMPOSER_ALLOW_SUPERUSER 1

RUN mkdir -p /var/www/.composer && chown -R www-data /var/www/.composer

RUN chmod -R 777 ./

WORKDIR /app

path: docker/php-fpm/Dockerfile


code:
apc.enable_cli = 1
date.timezone = TIMEZONE
session.auto_start = Off
short_open_tag = Off
# http://symfony.com/doc/current/performance.html
opcache.max_accelerated_files = 20000
realpath_cache_size = 4096K
realpath_cache_ttl = 600


code:
zend_extension=xdebug.so
xdebug.mode=debug
xdebug.client_host=172.17.0.1
xdebug.client_port=9003
xdebug.start_with_request=yes
xdebug.idekey = PHPSTORM
xdebug.discover_client_host=false


code: FROM redis:4.0

path: docker/redis/Dockerfile


code:
# Nginx
NGINX_HOST=app

# TIMEZONE
TZ=Europe/MOSCOW

# MySQL
MYSQL_ROOT_PASSWORD=secret
MYSQL_DATABASE=myDB
MYSQL_USER=docker
MYSQL_PASSWORD=docker

# Redis
REDIS_DSN=redis://redis:6379

# Xdebug
# get containers IP address: echo $(docker network inspect bridge | grep Gateway | grep -o -E '[0-9\.]+')
XDEBUG_REMOTE_HOST=172.17.0.1


code:
;;; immortal-scratch.el --- respawn the scratch buffer when it's killed -*- lexical-binding: t -*-

;; Copyright (C) 2016 Jonathan Kotta

;; Author: Jonathan Kotta <jpkotta@gmail.com>
;; Maintainer: Jonathan Kotta <jpkotta@gmail.com>
;; Version: 0.1

;; This file is not part of GNU Emacs.

;; This file is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.

;; This file is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; For a full copy of the GNU General Public License
;; see <http://www.gnu.org/licenses/>.

;;; Commentary:

;; This package provides a global minor mode `immortal-scratch-mode'
;; that causes the scratch buffer to respawn after it's killed.  To
;; kill it without respawning, use `immortal-scratch-kill' with a
;; non-nil argument.

;;; Code:

(defgroup immortal-scratch nil
  "Respawn scratch buffer when it's killed."
  :group 'convenience)

(defcustom immortal-scratch-switch-to-respawned-scratch nil
  "If non-nil, switch to the new scratch buffer when it is respawned."
  :group 'immortal-scratch)

(defun immortal-scratch-respawn ()
  "Create *scratch* buffer if it doesn't exist.

If `immortal-scratch-switch-to-respawned-scratch' is not nil,
switch to the newly created *scratch* buffer."
  (interactive)
  (with-current-buffer (get-buffer-create "*scratch*")
    (with-temp-message ""
      (when (zerop (buffer-size))
        (when initial-scratch-message
          (insert initial-scratch-message)
          (set-buffer-modified-p nil))
        (funcall initial-major-mode))
      (when immortal-scratch-switch-to-respawned-scratch
        (switch-to-buffer "*scratch*")))))

(defun immortal-scratch-kill (&optional with-fire)
  "Add this to `kill-buffer-query-functions' to respawn scratch when it is killed.

When WITH-FIRE is not nil, kill the scratch buffer but do not respawn it."
  (interactive "P")
  ;; kill-buffer-query-functions are called with no arg, so with-fire
  ;; will always be nil in that case.
  (if (or (string= (buffer-name (current-buffer)) "*scratch*")
          with-fire)
      (let ((kill-buffer-query-functions kill-buffer-query-functions))
        (remove-hook 'kill-buffer-query-functions
                     #'immortal-scratch-kill)
        (kill-buffer "*scratch*")
        (unless with-fire
          (immortal-scratch-respawn))
        nil)
    t ;; not scratch
    ))

;;;###autoload
(define-minor-mode immortal-scratch-mode
  "When the scratch buffer is killed, immediately respawn it."

  :group 'immortal-scratch
  :global t
  :lighter ""

  (if immortal-scratch-mode
      (add-hook 'kill-buffer-query-functions #'immortal-scratch-kill)
    (remove-hook 'kill-buffer-query-functions #'immortal-scratch-kill)))

(provide 'immortal-scratch)

;;; immortal-scratch.el ends here

repo_name: pluc/immortal


code:
antenna.sqlite
__pycache__
blocklist.txt
antenna.log
customfilters/*
antenna.conf

repo_name: zertbert/gemini


code:
# Antenna - Receiving Transmissions from Geminispace

```
   |\
   \ \ @
   /\_\/
  _|_
_|___|___
 ANTENNA
```

This is a feed aggregator with a twist. It doesn't have a list of feeds that it repeatedly checks. Instead it takes feed URLs as user input, and checks newly submitted feeds every few minutes. No more useless hammering of dead feed files.

* You write a post on your gemlog.
* Your atom/RSS/gemsub feed updates.
* You call gemini://[domain and path to submission script]?[URL to your feed]
* A few minutes later Antenna fetches your feed and lists your entries.

## Background

Most gemlogs live only a brief life, or post seldom and irregularly. A common feed aggregator relies on the consumer to curate a list of feeds, all of which will be fetched again and again and again at some interval. Few of them (most of the time none of them) have any new entries since last check. Some disappear, causing timeouts. I find this incessant blind polling a waste of resources.

This became very apparent when Solderpunk decided that the central CAPCOM installation should no longer poll every feed it knew of, but only a random subset of 100 of them each month. At the time of this writing, CAPCOM looks like a ghost town.

I believe that a better way to aid discoverability in any community is to let publishers push their content to where people are looking for it. And the gemini community is not yet too large for a central hub of information.

## Preparation

Antenna runs on python3 and mostly uses modules available in core. Two exceptions I remember are `feedparser` and `sqlite3`. Please tell me if you try to run this and run into any undocumented requirements.

The current code base makes a few assumptions that may or may not be true for your system:

* That there are two folders in the same directory named `antenna` and `public_gemini`, respectively.
* That the user which runs the `queuefeeds.py` script has both read and write access to the SQLite3 database and the folder `antenna`, which the database file will be in.
* That there are files `about.gmi`, `log`, and `submit` in the `public_gemini` folder, because the generated page will link to them.

My setup is a useful referense. It looks like this:

```
~antenna/
    |
    +--- antenna/
    |       |
    |       +--- README.md
    |       +--- LICENSE
    |       +--- antennaDB.py
    |       +--- ingestfeeds-wrapper.sh
    |       +--- queuefeed.py
    |       +--- ingestfeeds.py
    |       +--- antenna.log
    |       +--- antenna.sqlite
    |       +--- blocklist.txt
    |
    +--- public_gemini/
            |
            +--- index.gmi
            +--- about.gmi
            +--- submit
            +--- log
```

Nothing outside of `~antenna/public_gemini/` is publicly reachable. The file `about.gmi` is a handwritten file about my instance. The `index.gmi` file is generated by Antenna. The two scripts `log` and `submit` change the working directory to ~antenna/antenna/ and then runs `tail -n 50 antenna.log` and `./queuefeed.py` respectively.

## Installation

Clone this repo:

```
git clone https://notabug.org/tinyrabbit/gemini-antenna.git antenna
```

Enter the catalogue and create a database:

```
cd antenna
python3
> import antennaDB
> antennaDB.AntennaDB.createDB()
```

Make sure that the user that executes the `queuefeeds.py` script has read and write permissions to the directory `antenna` as well as `antenna/antenna.sqlite`.

Create a cron job that runs the ingestfeeds.py via the wrapper (substitute for whichever user should run the ingest job, and which directory the `ingestfeeds-wrapper.sh` is in):

```
sudo echo "*/10 * * * * antenna /home/antenna/antenna/ingestfeeds-wrapper.sh" > /etc/cron.d/antenna-ingestion
```

If there are any specific domains you'd like to block from publishing to your Antenna, please fill them in (one on each line) in a file named `blocklist.txt`, one URL per line and all starting with `gemini://` or other scheme and separator, depending on what you'd like to block.

## Contributing

* Be kind, humble and open-minded in discussions.
* Send pull requests or submit issues here, or contact me directly with suggestions/feedback/thoughts/bug reports: bjorn.warmedal@gmail.com or ew0k@tilde.team.


code:
#!/usr/bin/env python3
# vim: tabstop=4 shiftwidth=4 expandtab

import re
import urllib.parse
from pathlib import Path, PosixPath

class URLHelper():

    def __init__(self, blocklist: str = "blocklist.txt"):
        self.blockrules: set = set()
        if not Path(blocklist).exists():
            return

        with open(blocklist) as blockfile:
            self.blockrules = set(blockfile.read().split("\n")) - {""}

    def isBlocked(self, url) -> bool:
        """
        Check whether a URL is blocked by the rules.
        This method calls :meth:`~URLHelper.resolve`.
        """
        url = self.resolve(url)
        for rule in self.blockrules:
            if url.startswith(rule):
                return True
        return False

    @classmethod
    def mightBeAURL(cls, url: str) -> bool:
        """
        Naive URL validation.

        >>> URLHelper.mightBeAURL("gemini://example.com/feed")
        True
        >>> URLHelper.mightBeAURL("my feed")
        False
        """
        pattern = r'^[\w]+://[^/]+\.[^/]+.*'
        return bool(re.match(pattern, url))

    @classmethod
    def correct(cls, url: str) -> str:
        """
        Unquote a URL and add gemini:// scheme if needed.

        >>> URLHelper.correct("example.com/my%20feed")
        'gemini://example.com/my feed'
        """
        url = urllib.parse.unquote(url)

        if not re.findall(r'^[\w:]*//', url):
            url = "gemini://" + url
        elif not urllib.parse.urlparse(url).netloc:
            url = "gemini:" + url

        return url

    @classmethod
    def resolve(cls, url: str) -> str:
        """
        Resolve relative paths in URLs.
        This method calls :meth:`~URLHelper.correct` beforehand.

        >>> URLHelper.resolve("gemini://example.com/1/../2")
        'gemini://example.com/2'
        """
        url = urllib.parse.urlparse(cls.correct(url))

        if not url.path:
            path = ""
        elif not url.path.startswith("/"):
            raise ValueError("Not an absoulute URL")
        else:
            path = str(PosixPath(url.path).resolve())
            # restore lost trailing slash
            if url.path.endswith("/") and path != "/":
                path += "/"
        return urllib.parse.urlunparse(url._replace(path=path))


code:
#!/usr/bin/env python3
# vim: tabstop=4 shiftwidth=4 expandtab

import sqlite3
import os
from multiFeedParsing import FeedEntry,TwtxtEntry

# There's a lot of opening and closing going on here,
# because several processes will be sharing one sqlite3
# db, which is just a single file. We want to hog it
# as little as possible to minimize the risk of
# collisions. Some errors are tolerable; this is a
# good enough effort.
class AntennaDB():

    def __init__(self, dbPath="antenna.sqlite"):
        self.dbPath = dbPath

    def createDB(self):
        connection = sqlite3.connect(self.dbPath)
        cursor = connection.cursor()
        cursor.execute("CREATE TABLE IF NOT EXISTS entries (feedurl text, author text, updated datetime, title text, link text primary key)")
        cursor.execute("CREATE TABLE IF NOT EXISTS twtxt (feedurl text, author text, posted datetime, twt text)")
        connection.close()

    def getEntries(self):
        connection = sqlite3.connect(self.dbPath)
        cursor = connection.cursor()
        cursor.execute("SELECT feedurl, author, updated, title, link FROM entries ORDER BY updated DESC")
        results = []
        for result in cursor.fetchall():
            results.append(FeedEntry(feedurl = result[0], author = result[1], updated = result[2], title = result[3], link = result[4]))
        connection.close()
        return results

    def getTwts(self):
        connection = sqlite3.connect(self.dbPath)
        cursor = connection.cursor()
        cursor.execute("SELECT feedurl, author, posted, twt FROM twtxt ORDER BY posted DESC")
        results = []
        for result in cursor.fetchall():
            results.append(TwtxtEntry(feedurl = result[0], author = result[1], posted = result[2], twt = result[3]))
        connection.close()
        return results

    def deleteFeeds(self, urls):
        urlTuples = []
        for url in urls:
            urlTuples.append((url,))
        connection = sqlite3.connect(self.dbPath)
        cursor = connection.cursor()
        cursor.executemany("DELETE FROM entries WHERE feedurl LIKE ?", urlTuples)
        cursor.executemany("DELETE FROM twtxt WHERE feedurl LIKE ?", urlTuples)
        connection.commit()
        connection.close()

    # UPSERTs entries into the DB, if they're not too old. Returns how many entries were upserted.
    def insertFeedEntries(self, entries, limit=0):
        entries = [e for e in entries if e.updated > limit]
        entrytuples = []
        for entry in entries:
            entrytuples.append((entry.feedurl, entry.author, entry.updated, entry.title, entry.link))
        connection = sqlite3.connect(self.dbPath)
        cursor = connection.cursor()
        cursor.executemany("INSERT INTO entries (feedurl, author, updated, title, link) VALUES (?,?,?,?,?) ON CONFLICT (link) DO UPDATE SET author = excluded.author, updated = excluded.updated, title = excluded.title", entrytuples)
        connection.commit()
        connection.close()
        return len(entries)

    def insertTwtxtEntries(self, entries, limit=0):
        entries = [e for e in entries if e.posted > limit]
        entrytuples = []
        for entry in entries:
            entrytuples.append((entry.feedurl, entry.author, entry.posted, entry.twt))
        connection = sqlite3.connect(self.dbPath)
        cursor = connection.cursor()
        cursor.executemany("INSERT INTO twtxt (feedurl, author, posted, twt) VALUES (?,?,?,?)", entrytuples)
        connection.commit()
        connection.close()
        return len(entries)

    def pruneDB(self, limit):
        connection = sqlite3.connect(self.dbPath)
        cursor = connection.cursor()
        cursor.execute("DELETE FROM entries WHERE updated < ?", (limit,))
        cursor.execute("DELETE FROM twtxt WHERE posted < ?", (limit,))
        connection.commit()
        connection.close()


code:
#!/usr/bin/env python3
# vim: tabstop=4 expandtab

import re
from os import getenv
import antennaDB
import signoffs
import datetime
import hashlib

def getHashes(query = ""):
    hashes = []
    p = re.compile('^[a-zA-Z\d]{10}$')
    if query:
        parts = query.split('&')
        for part in parts:
            if p.match(part):
                hashes.append(part)
    return hashes

def urlHash(url = ""):
    hashObject = hashlib.md5(url.encode())
    return hashObject.hexdigest()[0:10]

def filteredEntries(hashes = [], entries = []):
    filtered = []
    for entry in entries:
        if not urlHash(entry.feedurl) in hashes:
            filtered.append(entry)
    return filtered

def generatePage(hashes = [], entries = [], pathInfo = ""):
    fullPath = f"gemini://{getenv('SERVER_NAME')}{getenv('SCRIPT_NAME')}"
    print("20 text/gemini\r\n")

    if pathInfo == "config":
        print("# Configure Your Filter\n")

        print(f"=> {fullPath}?{'&'.join(hashes)} Your current filter.\n")
        feedurls= []
        for entry in entries:
            if entry.feedurl in feedurls:
                continue
            feedurls.append(entry.feedurl)
            feedurlHash = urlHash(entry.feedurl)
            if feedurlHash in hashes:
                tmphashes = hashes.copy()
                tmphashes.remove(feedurlHash)
                print(f"=> {fullPath}/config?{'&'.join(tmphashes)} Remove '{entry.feedurl}' from filter.")
            else:
                print(f"=> {fullPath}/config?{'&'.join(hashes + [feedurlHash])} Add '{entry.feedurl}' to filter.")

    else: # We're not configuring. Just reading.
        print("# Your Antenna View\n")
        print(f"=> {fullPath}/config?{'&'.join(hashes)} Configure your filter.")
        datestamp = "0000-00-00"
        for entry in filteredEntries(hashes, entries):
            timestamp = datetime.datetime.utcfromtimestamp(entry.updated).strftime('%Y-%m-%d')
            if not datestamp == timestamp:
                datestamp = timestamp
                print("")
            print(f"=> {entry.link} {timestamp} {entry.author}: {entry.title}")

    print(f"\n> {signoffs.getsig()}\n")

## MAIN ##

db = antennaDB.AntennaDB()
pathInfo = getenv('PATH_INFO')
queryString = getenv('QUERY_STRING')

if not pathInfo and not queryString:
    print("10 Would you like to create a filter? (y/yes or turn back)")
elif not pathInfo and queryString in ["y","yes"]:
    generatePage([], db.getEntries(), "config")
else:
    hashes = getHashes(queryString)
    generatePage(hashes, db.getEntries(), pathInfo)


code:
#!/usr/bin/env python3
# vim: tabstop=4 shiftwidth=4 expandtab

import antennaDB
from os import getenv
import datetime
import time
import configparser
import argparse
import gemcall
import URLHelper
from multiFeedParsing import parsetwtxt,parsegemsub,parsexml,FeedEntry,TwtxtEntry
from pageGeneration import updateStatFile,generateFeedPage,generateAtomFeed,generateTwtxtPage,generateTwtxtFile

# Uniform log messages and output
def log(msg: str = "", logfile: str = "", response:int = None) -> None:
    log = open(logfile, "a")
    log.write(datetime.datetime.utcnow().isoformat() + " " + msg + "\n")
    log.close()
    if response:
        print(f"{str(response)} {msg}\r\n")

def getFeed(uh: URLHelper = None,feedurl: str = None, redirect: int = 0, redirectLimit: int = 1) -> { "response": gemcall.Response, "url": str } :
    response = None
    url = None
    try:
        url = uh.resolve(feedurl)
    except:
        log(msg = f"ERROR: '{url}' is not a valid URL",logfile = logfile, response = 40)

    # Have we already redirected too many times?
    if url and redirect <= redirectLimit:
        if not uh.mightBeAURL(url):
            log(msg = f"ERROR: pretty sure '{url}' is not a real URL...",logfile = logfile, response = 40)
        elif uh.isBlocked(url):
            log(msg = f"ERROR: feed URL '{url}' is blocked by rules.",logfile = logfile, response = 40)
            db.deleteFeeds([url])
        else:
            try:
                response = gemcall.request(url)
            except:
                log(msg = f"ERROR: failed to fetch feed from '{url}'",logfile = logfile, response = 40)
                response = None

        if response and (response.responsecode == 30 or response.responsecode == 31):
            log(msg = f"INFO: following redirect from '{url}' to '{response.meta}'.",logfile = logfile)
            return getFeed(uh = uh, feedurl = response.meta, redirect = redirect + 1, redirectLimit = redirectLimit)

        # If it's neither a redirect nor a successful response
        elif response and response.responsecode != 20:
            log(msg = f"ERROR: bad response for feed '{url}': '{str(response.responsecode)} {response.meta}'",logfile = logfile, response = 40)
            response = None
    elif url:
        log(msg = f"ERROR: Will not follow a redirect from '{url}' to '{response.meta}'",logfile = logfile, response = 40)

    # If we received a proper response then return it
    return { "response":response, "url":url }

feedurl = getenv('QUERY_STRING')
if not feedurl:
    print("10 Feed URL:\r\n")
    exit()

argparser = argparse.ArgumentParser(description="Ingest feed $QUERY_STRING to Antenna, according to settings in --config file.")
argparser.add_argument("--config", help="Path to config file.")

args = argparser.parse_args()
if not args.config:
    argparser.print_help()
    exit()

config = configparser.ConfigParser()
config.read(args.config)

nonpublic = config["nonpublic"]
public = config["public"]
rules = config["rules"]
rootdir = nonpublic.get("rootdir","")
outputdir = public.get("outputdir","")

if not rootdir:
    print("ERROR: The value 'rootdir' is missing in the [nonpublic] section of config file.")
    exit(1)
if not outputdir:
    print("ERROR: The value 'outputdir' is missing in the [public] section of config file.")
    exit(1)

db = antennaDB.AntennaDB(f"{rootdir}/{nonpublic.get('db','antenna.sqlite')}")
blocklist = f"{rootdir}/{nonpublic.get('blocklist','blocklist.txt')}"
logfile = f"{rootdir}/{nonpublic.get('logfile','antenna.log')}"

uh = URLHelper.URLHelper(blocklist = blocklist)
agelimit = int(time.mktime(datetime.datetime.utcnow().utctimetuple())) - (3600*24*int(rules.get('agelimit','7')))

feedResponse = getFeed(uh, feedurl)
response = feedResponse["response"]
correctedfeedurl = feedResponse["url"]
if not response:
    exit()

try: # 300kb should be enough for most feeds
    feed = response.read(300*1024).decode('UTF-8')
except:
    log(msg = f"ERROR: failed to properly read content from '{correctedfeedurl}'",logfile = logfile, response = 40)
    exit()

# Since we received an updated feed we'll start by removing existing entries
log(msg = f"INFO: fetched feed from '{correctedfeedurl}', removing from DB",logfile = logfile)
db.deleteFeeds([correctedfeedurl])

log(msg = f"INFO: attempting to parse feed '{correctedfeedurl}' as gemlog feed",logfile = logfile)
preliminaryEntries = parsegemsub(feed, correctedfeedurl) or parsexml(feed, correctedfeedurl)

entries = []
while len(preliminaryEntries) > 0:
    entry = preliminaryEntries.pop()
    if not uh.isBlocked(entry.link):
        entries.append(entry)
    else:
        log(msg = f"ERROR: entry URL '{entry.link}' is blocked by rules.",logfile = logfile)
if entries:
    db.insertFeedEntries(entries, agelimit)
else:
    log(msg = f"INFO: attempting to parse feed '{correctedfeedurl}' as twtxt",logfile = logfile)
    db.insertTwtxtEntries(parsetwtxt(feed, correctedfeedurl), agelimit)

db.pruneDB(agelimit)
# Short of getting all entries and comparing them fully to each other there's really no way to tell whether anything needs regeneration.
twts = db.getTwts()
feedEntries = db.getEntries()
feedURLs = set()

for entry in feedEntries:
    feedURLs.add(entry.feedurl)
        # twtgmi        = twtxt.gmi
        # twtxt         = twtxt.txt
        # atom          = atom.xml
        # stats         = stats.tsv
        # index         = index.gmi

updateStatFile(len(feedURLs), len(feedEntries), f"{outputdir}/{public.get('stats','stats.tsv')}")
generateFeedPage(feedEntries, f"{outputdir}/{public.get('index', 'index.gmi')}")
generateAtomFeed(feedEntries, f"{outputdir}/{public.get('atom', 'atom.xml')}")
generateTwtxtPage(twts, f"{outputdir}/{public.get('twtgmi', 'twtxt.gmi')}")
generateTwtxtPage(twts, f"{outputdir}/{public.get('twtxt', 'twtxt.txt')}")

print("20 text/gemini\r\nThank you for your submission! Antenna has now been updated.\n")


code:
# Copy this file to "antenna.conf" to make git ignore it
# Adapt values to your installation.
# Remember to write an "about.gmi" file!

[nonpublic]
# Where non-public data is located
	rootdir		= /home/antenna/data

	# Paths are relative to the rootdir.
	# db		= antenna.sqlite
	# filterdir	= customfilters
	# blocklist	= blocklist.txt
	# logfile	= antenna.log

[public]
# Where output data will be placed
	outputdir	= /home/antenna/public_gemini

	# Paths are relative to the outputdir.
	# twtgmi	= twtxt.gmi
	# twtxt		= twtxt.txt
	# atom		= atom.xml
	# stats		= stats.tsv
	# index		= index.gmi

	## Link on the index page point here.
	# about		= about.gmi

[scripts]
# Where CGI scripts are located
	cgidir		= /home/antenna/public_gemini/cgi-bin

	## Links on the index page point here.
	# submit	= submit
	# logtail	= log
	# filter	= filter

[rules]
# Rules around ingestion/publishing

	# Tha maximum age of posts in days
	# agelimit	= 7


code:
#!/usr/bin/env python3
# vim: tabstop=4 shiftwidth=4 expandtab

import urllib.parse
import re
import feedparser
import time
from datetime import datetime
urllib.parse.uses_relative.append("gemini")
urllib.parse.uses_netloc.append("gemini")

# collapse whitespace
def _cw(text):
    return re.sub(r'\s', ' ', text)

def parsegemsub(feed, baseurl):
    entries = []
    authorpattern = r'^#\s*([^#\r\n]+)'
    entriespattern = r'^=>\s*(\S+)\s+(\d{4}-\d{2}-\d{2})[^\r\n\S]*([^\r\n]*)'
    entriespatternmatches = re.findall(entriespattern, feed, re.MULTILINE)
    authorpatternmatch = re.findall(authorpattern, feed, re.MULTILINE)
    if authorpatternmatch:
        author = authorpatternmatch[0]
    else:
        return None
    for entrypatternmatch in entriespatternmatches:
        # Get our YYYY-MM-DD string, add time of day, parse to datetime.datetime, convert to unix timestamp and cast to int
        try:
            updated = int(datetime.timestamp(datetime.strptime(entrypatternmatch[1] + " 12:00:00", "%Y-%m-%d %H:%M:%S")))
        except:
            continue
        # A gemsub feed can often have relative links, we'll have to absolutize them
        link = urllib.parse.urljoin(baseurl, entrypatternmatch[0]).replace('/..','').replace('/.','')
        title = entrypatternmatch[2] if entrypatternmatch[2] else entrypatternmatch[1]
        entries.append(FeedEntry(baseurl, author, updated, title, link))
    return entries

def parsetwtxt(feed, baseurl):
    entries = []
    authorpattern = r'^#\s*nick\s*=\s*(\S+)'
    # This is a naive match, but we'll only keep those that validate eventually
    entriespattern = r'^(\S+)\t([^\r\n]+)'
    entriespatternmatches = re.findall(entriespattern, feed, re.MULTILINE)
    authorpatternmatch = re.findall(authorpattern, feed, re.MULTILINE)
    if authorpatternmatch:
        author = authorpatternmatch[0]
    else:
        author = baseurl
    for entrypatternmatch in entriespatternmatches:
        # Get our datetime string, parse to datetime.datetime, convert to unix timestamp and cast to int
        try:
            posted = int(datetime.timestamp(datetime.strptime(entrypatternmatch[0], "%Y-%m-%dT%H:%M:%S%z")))
        except:
            continue
        entries.append(TwtxtEntry(feedurl = baseurl, author = author, posted = posted, twt = entrypatternmatch[1]))
    return entries

def parsexml(feed, baseurl):
    scheme = baseurl.split("://")[0]
    entries = []
    parsedfeed = feedparser.parse(feed)

    # Let's set author name, or lacking that use the feed title.
    feedauthor = _cw(parsedfeed['feed']['author_detail']['name']) if parsedfeed['feed'].has_key('author_detail') and parsedfeed['feed']['author_detail'].has_key('name') else None
    feedtitle = _cw(parsedfeed['feed']['title']) if parsedfeed['feed'].has_key('title') else None
    if not feedauthor and feedtitle:
        feedauthor = feedtitle
    if not parsedfeed.has_key('entries'):
        return None
    for entry in parsedfeed['entries']:
        try: # The feed could miss all sorts of fields...
            if entry.has_key('author_detail') and entry['author_detail'].has_key('name'):
                author = _cw(entry['author_detail']['name'])
            elif feedauthor:
                author = feedauthor
            else:
                continue
            updated = int(time.mktime(entry['updated_parsed'])) # Seconds since epoch
            title = _cw(entry['title'])
            if len(entry['links']) > 1:
                link = [l for l in entry['links'] if l['href'].startswith(scheme)][0]['href']
            else:
                link = _cw(entry['link'])
            if not link:
                continue
            link = urllib.parse.urljoin(baseurl, link).replace('/..','').replace('/.','')
        except:
            continue
        entries.append(FeedEntry(baseurl, author, updated, title, link))
    return entries

class FeedEntry():

    def __init__(self, feedurl, author, updated, title, link):
        self.feedurl = feedurl
        self.author = author
        self.updated = updated
        self.title = title
        self.link = link

class TwtxtEntry():

    def __init__(self, feedurl, author, posted, twt):
        self.feedurl = feedurl
        self.author = author
        self.posted = posted
        self.twt = twt


code:
#!/usr/bin/env python3
# vim: tabstop=4 shiftwidth=4 expandtab

import antennaDB
import argparse
import datetime
import signoffs
import html

db = antennaDB.AntennaDB()

def printPage(pagetext, output=None):
    if output:
        outputfile = open(output, "w")
        outputfile.write(pagetext)
        outputfile.close()
    else:
        print(pagetext)

# Update statsfile
def updateStatFile(urlNr, entryNr, output=None):
    outputString = f"{datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')}\t{urlNr}\t{entryNr}\t%.2f"%(entryNr/urlNr)
    if output:
        outputfile = open(output, "a")
        outputfile.write(f"{outputString}\n")
        outputfile.close()
    else:
        print(outputString)

# Generate index page
def generateFeedPage(entries, output=None):
    pagetext='''# Antenna
## Receiving Transmissions From Geminispace
=> about.gmi What is this?
=> submit Send transmission!
'''
    datestamp = "0000-00-00"
    for entry in entries:
        timestamp = datetime.datetime.utcfromtimestamp(entry.updated).strftime('%Y-%m-%d')
        if not datestamp == timestamp:
            datestamp = timestamp
            pagetext += "\n"
        pagetext += "=> " + entry.link + " " + timestamp + " " + entry.author + ": " + entry.title + "\n"

    pagetext += f"\n> {signoffs.getsig()}\n"

    pagetext += '''
=> log Tail the log
=> twtxt.gmi Antenna's twtxt page.
=> atom.xml Antenna's Atom feed.
=> filter Customize your Antenna view.
=> stats.tsv Check out the latest statistics in tsv format.
'''
    printPage(pagetext, output)

def generateAtomFeed(entries, output=None):
    pagetext=f'''<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom">
  <title>Antenna</title>
  <id>gemini://warmedal.se/~antenna/</id>
  <updated>{datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')}</updated>
  <subtitle>Receiving transmissions from geminispace</subtitle>
  <link href="gemini://warmedal.se/~antenna/" rel="alternate"></link>
  <link href="gemini://warmedal.se/~antenna/atom.xml" rel="self"></link>
'''
    for entry in entries:
        timestamp = datetime.datetime.utcfromtimestamp(entry.updated).strftime('%Y-%m-%dT%H:%M:%SZ')
        pagetext += f'''  <entry>
    <id>{html.escape(entry.link)}</id>
    <title>{html.escape(entry.title)}</title>
    <updated>{timestamp}</updated>
    <link href="{html.escape(entry.link)}" rel="alternate"></link>
    <author>
      <name>{html.escape(entry.author)}</name>
    </author>
  </entry>
'''
    pagetext += "</feed>"
    printPage(pagetext, output)

def generateTwtxtPage(entries, output=None):
    pagetext='''# Antenna Twtxt
=> twtxt.txt Plain text version

'''
    for entry in entries:
        pagetext += f"{entry.author} {entry.feedurl}\n> {datetime.datetime.utcfromtimestamp(entry.posted).strftime('%Y-%m-%dT%H:%M:%SZ')} {entry.twt}\n\n"

    pagetext += f"\n=> log Tail the log\n\n> {signoffs.getsig()}\n"

    printPage(pagetext, output)

def generateTwtxtFile(entries, output=None):
    pagetext = ""

    for entry in entries:
        pagetext += f"{entry.author}\t{entry.feedurl}\t{datetime.datetime.utcfromtimestamp(entry.posted).strftime('%Y-%m-%dT%H:%M:%SZ')}\t{entry.twt}\n"

    printPage(pagetext, output)


code:
#!/bin/bash

LIMIT="$(date "--date=3 months ago" +%s)"

for filter in customfilters/*; do
	LASTREAD=$(grep '^Last Read' "${filter}" | cut -d : -f 2)
	if [[ $LASTREAD -lt $LIMIT ]]; then
		rm "${filter}"
	fi
done


code:
#!/bin/bash

cd "$(dirname ${0})"

SAVE="$(tail -n 50 antenna.log)"

echo "${SAVE}" > antenna.log


code:
#!/usr/bin/env python3
# vim: tabstop=4 shiftwidth=4 expandtab

import random

def getsig():
    epilogues = [
    "That's all for now, folks.",
    "Thank your friendly geminaut neighbour.",
    "Honour to you and your house!",
    "No camels were harmed when generating this page.",
    "'Be like water.' -- Bruce Lee",
    "Have you written a gemlog post today?",
    "If a warp reactor explodes and there's no one there to survive it, is still Spock?",
    "If I had a penny for every link here I'd have... coins!",
    "Nobody expects the Spanish inquisition!",
    "Zen take a nap. Zen fire ze missiles!",
    "🚀 FWOOOOOOOSH!",
    "Will it blend?",
    "You're not paranoid if they're really after you.",
    "Take me to your leader!",
    "Hail Hydra!",
    "I love the smell of gemtext in the morning. It smells like... UTF-8.",
    "You're as beautiful as the first time you visited.",
    "Have you noticed that the Antenna page is a gemsub feed? Neat, right?",
    "Don't worry. You'll be alright.",
    "Is it a bird? Is it plane? No, it's...",
    "Did you watch the game last night?",
    "Heeere, kitty, kitty, kitty...",
    "IT'S COMING RIGHT FOR US!",
    "Never underestimate the power of coffee.",
    "The pen is mightier than the sword, but a big ol' mechanical keyboard is hard to beat.",
    "Take a step towards realizing your dream today.",
    "Beep boop. Pling plong.",
    "ERROR: Everything is fine. Seriously. Totally okay.",
    "Geminispace is bigger than you thought, isn't it?",
    "If these words could talk!",
    "I'm really glad you popped by ❤",
    "Which of the above posts made you happier?",
    "Remember to water your plant!",
    "Powered by tea and chocolate.",
    "Making a list of random strings to add here was the most fun part of writing Antenna.",
    "Where's my sonic screwdriver?",
    "Soon may the Wellerman come!",
    "Please like and subscribe!",
    "Don't postpone something you can avoid entirely.",
    "Use the Vorpal sword to kill the Jabberwocky!",
    "What about second breakfast?",
    "Never attribute to malice that which is obviously caused by a crappy shell script and a forgotten cron job.",
    "I'm pretty sure nobody reads this.",
    "Life was a box of chocolate. I ate it.",
    "A rose by any other name is still not as hardy as a dandelion.",
    "I salute you, friend!",
    "The Tea-Rex is my favourite dinosaur.",
    "I feel like dancing!",
    "Frankie say relax.",
    "It's okay to feed me after midnight.",
    "So many single points of failure...",
    "A priest, a rabbi, and an imam went to an internet café. They all read smolZINE and said \"This is awesome!\".",
    "Hasta la vista, baby.",
    "Antenna is independent from political parties. And gravity.",
    "If it looks like a duck, walks like a duck, and quacks like a duck then it's a really good imitation.",
    "This weather, aye?",
    "There is no spoon.",
    "What's the carbon footprint of the first Death Star?",
    "Forged in the fires of Mount Doom!",
    "A right by the Moon, a left at Saturn, then a right again by the first black hole.",
    "No added sugar!",
    "Your sunshine on a rainy day.",
    "Off with her head!",
    "The hills are alive with a sound of EDM, or as I like to call it: music.",
    "It was like that when I got here.",
    "Are we saving the world AGAIN?",
    "Daleks, Uruk-Hais, Stormtroopers, Borg. Who'd win?",
    "Sent from my NASA Mars Rover.",
    "Check out #gemini on irc.tilde.chat",
    "I am invincible!",
    "The Infantile Vampire Paradox: centuries old vampires going through coming-of-age drama.",
    "DEBUG: This string was inserted here.",
    "It's always Friday somewhere in the galaxy.",
    "A short time ago in a house very very near you...",
    "They floated in the sky just like bricks never do.",
    "Romeo, Romeo. Why art though, dude?",
    "Are werewolves on other planets still affected by our moon's cycle?",
    "Was it good for you too?",
    "BANZAIIII!",
    "Badger, badger, badger, badger, mushroom MUSHROOM!",
    "Welcome to the Hunger Games!",
    "Load up the gemlog cannon. Prepare to post!",
    "On a long enough time scale the web will eventually die.",
    "Beware of the velociraptors.",
    "EXTREMITIES!",
    ":q!",
    "Eight Megabytes And Constantly Swapping.",
    "I ♊ U",
    "Hey, Geminispace! Where are all the cats!?",
    "I aim to misbehave.",
    "Heads or tails?",
    "He shoots! He scoooooores!!",
    "Bacon is good for me!",
    "Apple pie is everybody's second favourite pie.",
    "GOOOOOOOOD MOOOOOOORNING GEMINIIIII!",
    "GAME OVER, MAN!",
    "Beam me up, Scotty.",
    "Running diagnostics.",
    "Keep your luggage secured in the overhead compartment or in front of your legs.",
    "Run, Forrest! Run!",
    "Loading...",
    "Puny god.",
    "What star sign are you? Gemini?",
    "Wow! You look great!",
    "Shaken, not stirred.",
    "We're not in Kansas anymore.",
    "Geminaut, noun: a person visiting geminispace. Plural: geminauts; collective: a crew of.",
    "Limited Edition!",
    "You know what else has layers? Cakes!",
    "Never gonna give you up. Never gonna let you down.",
    "Nobody puts baby in a corner.",
    "I just lost the game.",
    "Waaaaaasssssuuuuup!",
    "Version 8 coming soon!",
    "They killed Kenny!",
    "Do NOT microwave your dog!",
    "(V)(;,,;)(V) WOOB WOOB WOOB",
    "'64 trilobites is enough for everyone' -- Charles Darwin",
    "It ain't over 'til it's over.",
    "Buffer overflow!",
    "Who let the logs out!?",
    "Yo, dog! Who put Antenna in Antenna? 😂",
    "It's never too late to give up.",
    "Don't forget the cover sheet on the TPS report.",
    "PC LOAD LETTER",
    "We'll soon have flying cars.",
    "Escape From New York took place in 1997.",
    "Parental Advisory: Exquisite Content",
    "The best things in life are free (as in beer).",
    "How could Curiosity kill the cat? There are no cats on Mars.",
    "Backup your data!",
    "Don't be Evil inc.",
    "No paine, no grain.",
    "When the going gets tough, I rest for a bit.",
    "You actually catch more flies with vinegar.",
    "The cloud is not someone else's computer. It's actually water vapour.",
    "If you want something done right, you have to micromanage.",
    "The enemy of my enemy is my frenemy?",
    "There's no place like $HOME",
    "If time is money, is a financial transaction time travel?",
    "Two heads are better than one. Ask Zaphod Beeblebrox.",
    "Donate to charity!",
    "Support your favourite FOSS projects ❤",
    "Winter is coming.",
    "Hold the door! Hold the door!",
    "Scream and shout, and let it all out.",
    "Are we there yet?",
    ]

    return epilogues[random.randint(0,len(epilogues)-1)]


code:
``` text
English:
A simple plugin to import your music collection into DeaDBeeF. It was made to automatically create a playlist
for every artist.
Every selected folder will be saved as a playlist.

User manual:
The plugin can be used by clicking on "File -> Import folder(s) as playlist(s)"

Example structure (select every ARTIST directory in MUSIC_DIR you want to import as a playlist):
	MUSIC_DIR
		ARTIST_A
			ALBUM_A
			SINGLE_A
		ARTIST_B
			ALBUM_A
			track.flac
		ARTIST_C
			EP_A

For every artist, a playlist will be created, containing the audio files from the sub folders.

Compile this plugin with:
gcc -std=c99 -shared -O2 -o auto_playlist_by_artist_generator.so auto_playlist_by_artist_generator.c `pkg-config gtk+-2.0 --cflags --libs`

Tested under Arch Linux.

Deutsch:
Ein einfaches Plugin, um eine vorhandene Musiksammlung in DeaDBeeF zu importieren. Es wurde entwickelt, um
automatisch für jeden Künstler eine Wiedergabeliste zu erstellen. Für jeden ausgewählten Ordner wird eine
Wiedergabeliste angelegt.

Benutzeranleitung:
Nachdem das Plugin geladen wurde, kann es im Menü unter "Datei -> Import folder(s) as playlist(s)" aufgerufen
werden.

Beispielhafte Struktur einer Musiksammlung (die gewünschten KÜNSTLER-Ordner auswählen, die als
Wiedergabeliste gespeichert werden sollen):
        MUSIC_DIR
                KÜNSTLER_A
                        ALBUM_A
                        SINGLE_A
                KÜNSTLER_B
                        ALBUM_A
                        track.flac
                KÜNSTLER_C
                        EP_A

Für jeden Künstler wird eine Wiedergabeliste erstellt, die alle Audiodateien aus den jeweiligen Unterordnern
enthält.

Plugin kompilieren:
gcc -std=c99 -shared -O2 -o auto_playlist_by_artist_generator.so auto_playlist_by_artist_generator.c `pkg-config gtk+-2.0 --cflags --libs`

Unter Arch Linux getestet.
```


code:
/*
 * Automatic playlist by artist generator.
 * Copyright (C) 2020 positiv_

 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include <gtk/gtk.h>
#include <gmodule.h>

#include <deadbeef/deadbeef.h>
#include <deadbeef/gtkui_api.h>

static ddb_gtkui_t *gtkui_plugin;
static DB_functions_t *deadbeef;

static GtkWidget *filechooser;
static GSList *file_paths_in_selected_folder;

static int
auto_playlist_by_artist_generator_start()
{
    return 0;
}

static int
auto_playlist_by_artist_generator_stop()
{
    return 0;
}

static int
auto_playlist_by_artist_generator_connect()
{
	gtkui_plugin = (ddb_gtkui_t *)deadbeef->plug_get_for_id(DDB_GTKUI_PLUGIN_ID);

	if(!gtkui_plugin) {
		return -1;
	}

	return 0;
}

static void
add_files_from_glist(gpointer data, gpointer user_data)
{
	char *folder = strrchr((char*)data, G_DIR_SEPARATOR);

	int current_plt = deadbeef->plt_add(deadbeef->plt_get_count(), folder + 1);
	deadbeef->plt_set_curr_idx(current_plt);
	deadbeef->log("auto_playlist_by_artist_generator: Adding folder \"%s\".\n", data);

	deadbeef->plt_add_dir2(-1, deadbeef->plt_get_for_idx(current_plt), data, NULL, NULL);
	deadbeef->pl_save_current();
}

static int
auto_playlist_by_artist_generator_callback(DB_plugin_action_t *action, int ctx)
{
	filechooser = gtk_file_chooser_dialog_new("Choose folders", GTK_WINDOW (gtkui_plugin->get_mainwin()), GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER, GTK_STOCK_OK, GTK_RESPONSE_OK, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, NULL);

	gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(filechooser), TRUE);
	gtk_widget_show_all(filechooser);

	gint resp = gtk_dialog_run(GTK_DIALOG(filechooser));

	if (resp == GTK_RESPONSE_OK) {
		file_paths_in_selected_folder = gtk_file_chooser_get_filenames(GTK_FILE_CHOOSER(filechooser));

		g_slist_foreach(file_paths_in_selected_folder, add_files_from_glist, NULL);
		g_slist_free(file_paths_in_selected_folder);
	}

	gtk_widget_destroy(filechooser);

	return 0;
}

static DB_plugin_action_t auto_playlist_by_artist_generator_action = {
    .title = "File/Import folder(s) as playlist(s)",
    .name = "auto_playlist_by_artist_generator",
    .flags = DB_ACTION_COMMON | DB_ACTION_ADD_MENU,
    .callback2 = auto_playlist_by_artist_generator_callback,
    .next = NULL,
};

static DB_plugin_action_t *
auto_playlist_by_artist_generator_getactions(DB_playItem_t *it)
{
    return &auto_playlist_by_artist_generator_action;
}

static DB_misc_t plugin = {
	.plugin.api_vmajor = DB_API_VERSION_MAJOR,
	.plugin.api_vminor = 0,
	.plugin.type = DB_PLUGIN_MISC,
	.plugin.version_major = 0,
	.plugin.version_minor = 1,
	.plugin.id = "apg",
	.plugin.name = "Automatic playlist by artist generator",
	.plugin.descr = "Generate playlists for your artists, by selecting the respective directories.",
	.plugin.copyright = "Copyright (C) 2020 positiv_\n"
        "\n"
        "This program is free software; you can redistribute it and/or\n"
        "modify it under the terms of the GNU General Public License\n"
        "as published by the Free Software Foundation; either version 2\n"
        "of the License, or (at your option) any later version.\n"
        "\n"
        "This program is distributed in the hope that it will be useful,\n"
        "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
        "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
        "GNU General Public License for more details.\n"
        "\n"
        "You should have received a copy of the GNU General Public License\n"
        "along with this program; if not, write to the Free Software\n"
        "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.\n",
	.plugin.website = "https://notabug.org/positiv_/Automatic-playlist-by-artist-generator",
	.plugin.start = auto_playlist_by_artist_generator_start,
	.plugin.stop = auto_playlist_by_artist_generator_stop,
	.plugin.get_actions = auto_playlist_by_artist_generator_getactions,
	.plugin.connect = auto_playlist_by_artist_generator_connect,
};

DB_plugin_t *
auto_playlist_by_artist_generator_load(DB_functions_t *ddb)
{
    deadbeef = ddb;
    return DB_PLUGIN(&plugin);
}


code:
/build/
/install/
/release/
/sources/
/libreboot.conf
.version
.revision
.tarfiles
.epoch
push
*.vim
/TODO/
/docs/version
/bucts/
/coreboot/
/crossgcc/
/flashrom/
/grub/
/memtest86plus/
/seabios/
/bin/
/resources/utilities/ich9utils/*.rom
/resources/utilities/ich9utils/*.bin
/resources/utilities/ich9utils/ich9utils
/resources/utilities/ich9utils/ich9gen
/resources/utilities/ich9utils/demefactory
/resources/utilities/ich9utils/ich9show
/resources/utilities/ich9utils/obj/*.o
/resources/utilities/ich9utils/obj/*/*.o
/resources/utilities/ich9utils/mkdescriptor*.[ch]
/resources/utilities/ich9utils/mkgbe*.[ch]
/resources/utilities/grub-assemble/grub_*.elf
/mkgbe.[ch]
/*.bin
/resources/utilities/i945-pwm/i945-pwm
/push
/ChangeLog
/NEWS
/version
/versiondate
/gm45macaddress
tocheck*
*.html
!www/template.html
/www/news/index.md
/www/feed.xml
/www/news/feed.xml