Debian Codegraph @

gallery_dl/server.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License version 2 as
5 # published by the Free Software Foundation.
6
7 """Background IPC Server"""
8
9 import struct
10 import socket
11 import threading
12 import logging
13 import queue
14 from . import util, config
15
16 log = logging.getLogger("server")
17
18 HOST = config.get(("server",), "host", "127.0.0.1")
19 PORT = config.get(("server",), "port", 64696)
20 KEY = config.get(("server",), "key", "gallery_dl").encode()
21 TIMEOUT = config.get(("server",), "timeout")
22 stop_event = threading.Event()
23 klen = len(KEY)
24
25 if TIMEOUT and TIMEOUT < 0:
26 TIMEOUT = None
27
28
29 def listen(queueObj):
30 # Background thread in master process
31 # that accepts data from subsequent gallery-dl processes
32 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
33 try:
34 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
35 s.bind((HOST, PORT))
36 s.listen()
37 s.settimeout(1.0) # Check stop_event periodically
38 except Exception as exc:
39 log.error("%s: %s", exc.__class__.__name__, exc)
40 queueObj.put(util.SENTINEL)
41 return False
42 log.info("Listening on %s:%s", HOST, PORT)
43
44 while not stop_event.is_set():
45 try:
46 conn, _ = s.accept()
47 with conn:
48 header = conn.recv(4+klen)
49 if not header[:klen] == KEY:
50 continue
51 data_len = struct.unpack(">I", header[klen:])[0]
52 chunks = []
53 bytes_received = 0
54 while bytes_received < data_len:
55 chunk = conn.recv(min(data_len - bytes_received, 4096))
56 if not chunk:
57 break
58 chunks.append(chunk)
59 bytes_received += len(chunk)
60 full_payload = b"".join(chunks)
61 data = util.json_loads(full_payload.decode())
62 if not data:
63 continue
64
65 if isinstance(data, list):
66 cnt = len(data)
67 if cnt != 1:
68 urls = "\n ".join(data)
69 log.info(f"Received {cnt} URLs:\n {urls}")
70 for url in data:
71 queueObj.put(url)
72 else:
73 data = data[0]
74 log.info("Received URL: " + data)
75 queueObj.put(data)
76 else:
77 log.info("Received URL: " + data)
78 queueObj.put(data)
79 except socket.timeout:
80 continue
81 log.info("Shutting down IPC Server")
82 queueObj.put(util.SENTINEL)
83
84
85 def send(data):
86 # send data to master process
87 cnt = len(data) if isinstance(data, list) else 1
88 if cnt == 1:
89 log.info("Sending URL to Server")
90 else:
91 log.info("Sending %s URLs to Server", cnt)
92
93 payload = util.json_dumps(data).encode()
94 header = struct.pack(">I", len(payload))
95 try:
96 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
97 s.settimeout(0.5)
98 s.connect((HOST, PORT))
99 s.sendall(KEY + header + payload)
100 return True
101 except Exception as exc:
102 log.error("%s: %s", exc.__class__.__name__, exc)
103 return False
104
105
106 def start():
107 log.info("Starting IPC Server")
108
109 queueObj = InputManager()
110 listener = threading.Thread(
111 target=listen, args=(queueObj,), daemon=True)
112 listener.start()
113 return queueObj
114
115
116 def stop():
117 stop_event.set()
118
119
120 class InputManager(queue.Queue):
121
122 def __init__(self):
123 queue.Queue.__init__(self)
124 self.files = self.urls = ()
125 self.log = self.err = None
126
127 self._index = 0
128 self._pformat = None
129
130 def add_url(self, url):
131 self.put(url)
132
133 def add_list(self, urls):
134 for url in urls:
135 self.put(url)
136
137 def progress(self, pformat=True):
138 if pformat is True:
139 pformat = "[{current}/{total}] {url}"
140 self._pformat = pformat.format_map
141
142 def next(self):
143 self._index += 1
144
145 def success(self):
146 pass
147
148 error = success
149
150 def close(self):
151 self.put(util.SENTINEL)
152
153 def __iter__(self):
154 self._index = 0
155 return self
156
157 def __next__(self):
158 try:
159 url = self.get(timeout=TIMEOUT)
160 except queue.Empty:
161 raise StopIteration
162 if url is util.SENTINEL:
163 raise StopIteration
164
165 log.info(self._pformat({
166 "total" : self._index + self.qsize() + 1,
167 "current": self._index + 1,
168 "url" : url,
169 }))
170 return url