aboutsummaryrefslogtreecommitdiff
path: root/services/pamphlet/views.py
blob: 8e992b75fb6a68beda92046afe5908b95da7d613 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from django.http import HttpResponse
import os
import random
from collections import deque
import threading


class ImageRotator:
    def __init__(self):
        self.image_queues = {}
        self.lock = threading.Lock()

    def get_random_image(self, style):
        with self.lock:
            # Initialize or refresh queue if empty
            if style not in self.image_queues or not self.image_queues[style]:
                path = f"static/images/fakeads/{style}"
                files = [f for f in os.listdir(path) if f.endswith(".gif")]
                random.shuffle(files)
                self.image_queues[style] = deque(files)

            # Get next image and rotate to end of queue
            image = self.image_queues[style].popleft()
            self.image_queues[style].append(image)
            return image


rotator = ImageRotator()


def pamphlet(request):
    style = request.GET.get("style", "banner")
    seed = request.GET.get("seed", "")

    if style not in ["banner", "big", "button"]:
        style = "banner"

    if style == "button":
        style = "buttons"

    path = f"static/images/fakeads/{style}"

    try:
        files = [f for f in os.listdir(path) if f.endswith(".gif")]
        if not files:
            return HttpResponse(status=404)

        random.seed(seed)
        chosen_file = random.choice(files)
        random.seed()

        file_path = os.path.join(path, chosen_file)

        with open(file_path, "rb") as f:
            response = HttpResponse(f.read(), content_type="image/gif")
            response["Cache-Control"] = "no-cache, no-store, must-revalidate"
            response["Pragma"] = "no-cache"
            response["Expires"] = "0"
            return response

    except Exception as e:
        print(f"Error while serving pamphlet: {str(e)}")
        return HttpResponse(status=404)