# for a 20 Mbits/s stream, we want to keep maybe 10s of video, 40 streams means 1 GB
proxy_cache_path /tmp levels=1:2 keys_zone=livecache:10m max_size=2g inactive=30s;

geo $msuser_whitelist {
	default 0;
	127.0.0.1 1;
	{{ worker_ip }} 1;
}
map $msuser_whitelist $msuser_allowed {
	0 $secure_link;
	1 1;
}

server {
	listen 80;
	server_name {{ server_name }};

	rewrite ^ https://$host$request_uri? permanent;
}

server {
	listen 443 ssl;
	server_name {{ server_name }};
	root /var/www/msuser;

	access_log /var/log/nginx/access_msuser.log;
	error_log /var/log/nginx/error_msuser.log;

	location /public {
		expires 30d;
		add_header Pragma public;
		add_header Cache-Control "public";
	}
	location /resources {
		location ~ \.ts$ {
		}
		location ~ \.xml$ {
		}
		secure_link $arg_st,$arg_e;
		secure_link_md5 "{{ secret }}$uri$arg_e$remote_addr";
		# link expired
		if ($msuser_allowed = "0") {
			return 410;
		}
		# bad hash
		if ($msuser_allowed = "") {
			return 403;
		}
	}
	location /static {
		expires 30d;
		add_header Pragma public;
		add_header Cache-Control "public";
	}
	location /crossdomain {
		expires 30d;
		add_header Pragma public;
		add_header Cache-Control "public";
	}
	location ~ ^/streaming/.*\.m3u8.*$ {
			rewrite ^/streaming/(.*)$ /live/$1 break;
			proxy_pass http://localhost:1935;
			proxy_cache livecache;
			proxy_cache_lock on;
			expires -1;
			proxy_cache_min_uses 1;
			proxy_cache_valid 200 1s;
			add_header X-Cache $upstream_cache_status;
			add_header Access-Control-Allow-Origin "*";
			proxy_cache_key $scheme$proxy_host$uri;
			proxy_cache_use_stale updating;
	}
	location ~ /streaming/.*\.(ts).*$ {
			rewrite ^/streaming/(.*)$ /live/$1 break;
			proxy_pass http://localhost:1935;
			proxy_cache livecache;
			proxy_cache_lock on;
			expires 2s;
			proxy_cache_min_uses 1;
			proxy_cache_valid 200 10s;
			add_header X-Cache $upstream_cache_status;
			add_header Access-Control-Allow-Origin "*";
			proxy_cache_key $scheme$proxy_host$uri;
	}
	location / {
		uwsgi_pass unix:///home/msuser/mstmp/uwsgi.sock;
		include /etc/nginx/uwsgi_params;
	}
}
