Repository navigation
Expand file tree
/
Copy pathprocess.py
More file actions
1345 lines (1181 loc) · 45.3 KB
/
Copy pathprocess.py
File metadata and controls
1345 lines (1181 loc) · 45.3 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import base64
import concurrent.futures
import csv
import html
import json
import math
import os
import random
import re
import threading
import time
import unicodedata
from collections import defaultdict
from datetime import datetime, timedelta, timezone
from urllib.parse import parse_qsl, unquote, urlencode, urlparse, urlunparse
from config import Config
from curl_compat import load_curl_requests
from marketplace_queries import (
QueryDiscoveryError,
client_asset_urls,
query_definitions_from_bundle,
)
curl_requests = load_curl_requests()
TASKS_STATUS = {}
SUPPORTED_DISCOGS_HOSTS = {"discogs.com", "www.discogs.com"}
SUPPORTED_MARKETPLACE_PATHS = {"/sell/list", "/shop/list"}
RETRYABLE_STATUS_CODES = {403, 408, 425, 429, 500, 502, 503, 504, 520, 522, 524}
MARKETPLACE_SEARCH_HASH = (
"7ce2bd7801f216b0999648d626c935fc86c8fd85e562529bd87b690c974f08c2"
)
STYLES_HASH = (
"4c514376b334ff2363ebf0c1b137de12d315ea16f6d492d20e46c89e7116843d"
)
SELLER_SUGGESTIONS_HASH = (
"f262cab8b59b4022e8e061eacc9a8c95fec1ba6dc5dd3874cfafaa0774cdaf1d"
)
RELEASE_DETAILS_HASH = (
"ee9d48441023ebd1e6ca169e550581b45de216e88b40711acb6617e49e1bb0cb"
)
RELEASE_DETAILS_QUERY = """query Releases($discogsIds: [Int], $first: Int) {
releases(discogsIds: $discogsIds) {
inWantlistCount
inCollectionCount
images(first: $first) {
edges {
node {
thumbnail {
webpUrl
}
}
}
}
ratings(first: 1) {
averageRating
}
discogsId
}
}"""
_LEGACY_FILTER_KEY_MAP = {
"format": "formatName",
"format_desc": "formatDescription",
"condition": "mediaCondition",
"sleeve_condition": "sleeveCondition",
"ships_from": "shipsFrom",
"price_min": "priceMin",
"price_max": "priceMax",
"year_min": "yearRangeLow",
"year_max": "yearRangeHigh",
"artist_id": "artist",
"release_id": "release",
"label_id": "label",
"master_id": "master",
}
_IGNORED_URL_KEYS = {
"after",
"attempt",
"header_type",
"layout",
"limit",
"listing_type",
"more",
"page",
"size",
"sort",
"sortorder",
}
_SUPPORTED_FILTER_KEYS = {
"allowsOffers",
"artist",
"currency",
"formatDescription",
"formatName",
"genre",
"goodDeals",
"hasItemPhotos",
"hideGenericSleeves",
"hideSleevelessMedia",
"label",
"master",
"mediaCondition",
"price",
"priceMax",
"priceMin",
"q",
"release",
"seller",
"shipsFrom",
"shipsFromRegions",
"showUnavailable",
"sleeveCondition",
"style",
"styleId",
"year",
"yearRangeHigh",
"yearRangeLow",
}
_ARRAY_AND_FILTERS = {
"formatName": "formatNameAnd",
"formatDescription": "formatDescriptionAnd",
"genre": "genreAnd",
"styleId": "styleIdAnd",
}
_STRING_ARRAY_FILTERS = {
"currency": "currency",
"formatDescription": "formatDescription",
"formatName": "formatName",
"genre": "genre",
"mediaCondition": "mediaCondition",
"shipsFrom": "shipsFrom",
# Discogs uses a plural URL parameter but a singular GraphQL field.
"shipsFromRegions": "shipsFromRegion",
"sleeveCondition": "sleeveCondition",
}
_INTEGER_ARRAY_FILTERS = {"artist", "label", "master", "release", "seller"}
_BOOLEAN_FILTERS = {
"allowsOffers": "allowsOffers",
"goodDeals": "isDeal",
"hasItemPhotos": "hasInventoryImages",
"hideGenericSleeves": "hideGenericSleeves",
"hideSleevelessMedia": "hideSleevelessMedia",
"showUnavailable": "showUnavailable",
}
_CONDITION_ABBREVIATIONS = {
"MINT": "M",
"NEAR_MINT": "NM or M-",
"VERY_GOOD_PLUS": "VG+",
"VERY_GOOD": "VG",
"GOOD_PLUS": "G+",
"GOOD": "G",
"FAIR": "F",
"POOR": "P",
"NOT_GRADED": "Not Graded",
"GENERIC": "Generic",
"NO_COVER": "No Cover",
}
_thread_local = threading.local()
_styles_lock = threading.Lock()
_style_ids_by_name = None
_persisted_queries_lock = threading.Lock()
_persisted_queries = {}
_persisted_refresh_failure = None
_request_gate = threading.BoundedSemaphore(
max(1, int(Config.MARKETPLACE_MAX_IN_FLIGHT_REQUESTS))
)
_task_gate = threading.BoundedSemaphore(
max(1, int(Config.MAX_CONCURRENT_MARKETPLACE_TASKS))
)
class DiscogsError(RuntimeError):
"""A failure that is safe and useful to show to the user."""
class DiscogsTemporaryError(DiscogsError):
pass
class DiscogsNotFoundError(DiscogsError):
pass
class DiscogsNoResultsError(DiscogsError):
pass
class DiscogsUnsupportedUrlError(DiscogsError, ValueError):
pass
class DiscogsProtocolError(DiscogsError):
pass
class DiscogsPersistedQueryError(DiscogsProtocolError):
pass
def format_count(value):
return f"{int(value):,}"
def save_uuid_to_file(unique_id):
os.makedirs("data", exist_ok=True)
with open("data/uuids.txt", "a", encoding="utf-8") as file:
file.write(unique_id + "\n")
def is_valid_uuid(unique_id):
try:
with open("data/uuids.txt", "r", encoding="utf-8") as file:
return unique_id + "\n" in file.readlines()
except FileNotFoundError:
return False
def normalize_seller_input(raw_seller):
seller = unicodedata.normalize("NFKC", str(raw_seller or ""))
seller = re.sub(r"[\u200b-\u200d\u2060\ufeff]", "", seller).strip()
if not seller:
raise DiscogsNotFoundError("Please provide a Discogs seller name.")
if seller.startswith(("http://", "https://")):
parsed = urlparse(seller)
if (parsed.hostname or "").lower() not in SUPPORTED_DISCOGS_HOSTS:
raise DiscogsNotFoundError(
"Only Discogs seller names or profile URLs are supported."
)
match = re.fullmatch(r"/seller/([^/]+)/profile/?", parsed.path)
if not match:
raise DiscogsNotFoundError(
"Paste only a seller name here, or use the filtered URL field."
)
seller = unquote(match.group(1)).strip()
if not seller or "/" in seller or len(seller) > 100:
raise DiscogsNotFoundError(
"That does not look like a valid Discogs seller name."
)
return seller
def _normalize_legacy_query(query_params):
normalized = []
for key, value in query_params:
lower_key = key.lower()
if lower_key in {"more", "header_type", "listing_type", "attempt"}:
continue
if lower_key in {"limit", "page"}:
normalized.append((lower_key, value))
continue
if lower_key == "sort":
sort_name, _, sort_direction = value.partition(",")
normalized.append(
("sort", "date-listed" if sort_name == "listed" else sort_name)
)
if sort_direction:
normalized.append(
(
"sortOrder",
"ascending" if sort_direction == "asc" else "descending",
)
)
continue
if lower_key == "year":
normalized.extend(
[("yearRangeLow", value), ("yearRangeHigh", value)]
)
continue
normalized.append((_LEGACY_FILTER_KEY_MAP.get(lower_key, key), value))
return normalized
def parse_and_validate_sell_list_url(raw_url):
if not raw_url:
raise DiscogsUnsupportedUrlError("Please provide a Discogs filtered URL.")
parsed = urlparse(raw_url.strip())
if parsed.scheme not in {"http", "https"}:
raise DiscogsUnsupportedUrlError(
"Use a complete Discogs URL beginning with https://."
)
if (parsed.hostname or "").lower() not in SUPPORTED_DISCOGS_HOSTS:
raise DiscogsUnsupportedUrlError("Only discogs.com URLs are supported.")
path = parsed.path.rstrip("/")
profile_match = re.fullmatch(r"/seller/([^/]+)/profile", path)
if path not in SUPPORTED_MARKETPLACE_PATHS and profile_match is None:
raise DiscogsUnsupportedUrlError(
"Use a Discogs /shop/list/, legacy /sell/list, or seller profile URL."
)
query_params = [
(key, value)
for key, value in parse_qsl(parsed.query, keep_blank_values=True)
if key.lower() not in {"page", "after"}
]
numeric_seller_is_username = False
if profile_match is not None:
seller_name = normalize_seller_input(unquote(profile_match.group(1)))
# /seller/123/profile names user "123". /shop/list/?seller=123 uses ID 123.
numeric_seller_is_username = seller_name.isdigit()
query_params = [
(key, value) for key, value in query_params if key.lower() != "seller"
]
query_params.insert(0, ("seller", seller_name))
path = "/sell/list"
if path == "/sell/list":
query_params = _normalize_legacy_query(query_params)
marketplace_url = urlunparse(
(
"https",
"www.discogs.com",
"/shop/list/",
"",
urlencode(query_params, doseq=True),
"",
)
)
return {
"marketplace_url": marketplace_url,
"base_query_params": query_params,
"numeric_seller_is_username": numeric_seller_is_username,
}
def _safe_int(value, default=0):
try:
return int(value)
except (TypeError, ValueError):
return default
def _safe_float(value, default=0.0):
try:
return float(value)
except (TypeError, ValueError):
return default
def _slugged_entity_id(value):
"""Return the numeric prefix used by Discogs entity-filter slugs."""
match = re.match(r"^(\d+)(?:-|$)", str(value or "").strip())
return int(match.group(1)) if match else None
def _is_true(value):
return str(value).strip().lower() in {"1", "true", "yes", "on"}
def _condition_abbreviation(value):
if not value:
return ""
value = str(value)
if value in _CONDITION_ABBREVIATIONS:
return _CONDITION_ABBREVIATIONS[value]
match = re.search(r"\(([^()]*)\)\s*$", value)
return match.group(1) if match else value.replace("_", " ").title()
def _session():
session = getattr(_thread_local, "discogs_session", None)
if session is None:
session = curl_requests.Session(impersonate=Config.CURL_IMPERSONATE)
session.headers.update(
{
"Accept-Language": "en-US,en;q=0.9",
"User-Agent": Config.DISCOGS_API_USER_AGENT,
}
)
_thread_local.discogs_session = session
return session
def _response_detail(response):
try:
payload = response.json()
except Exception:
return ""
if not isinstance(payload, dict):
return ""
message = payload.get("detail") or payload.get("message")
return f": {message}" if message else ""
def _request_discogs(
method, url, *, params=None, json_body=None, headers=None, context, text=False
):
last_error = None
attempts = max(1, int(Config.REQUEST_RETRIES))
for attempt in range(1, attempts + 1):
response = None
try:
with _request_gate:
response = _session().request(
method,
url,
params=params,
json=json_body,
headers=headers,
timeout=float(Config.REQUEST_TIMEOUT_SECONDS),
allow_redirects=not text,
)
except Exception as exc:
last_error = exc
else:
if response.status_code == 200:
if text:
if len(response.content) > 4 * 1024 * 1024:
raise DiscogsProtocolError(
"Discogs returned an unexpectedly large Marketplace client."
)
return response.text
try:
return response.json()
except Exception as exc:
last_error = exc
elif response.status_code == 404:
raise DiscogsProtocolError(
f"Discogs no longer exposes {context} at the expected address. "
"Please update the sorter."
)
elif response.status_code not in RETRYABLE_STATUS_CODES:
raise DiscogsProtocolError(
f"Discogs rejected {context} (HTTP {response.status_code})"
f"{_response_detail(response)}."
)
else:
last_error = RuntimeError(
f"HTTP {response.status_code}{_response_detail(response)}"
)
print(
f"Discogs {context}: HTTP {response.status_code}; "
f"retry {attempt}/{attempts}"
)
if attempt < attempts:
retry_after = 0.0
if response is not None:
try:
retry_after = float(response.headers.get("Retry-After", 0))
except (TypeError, ValueError):
retry_after = 0.0
backoff = float(Config.RETRY_BACKOFF_SECONDS) * (2 ** (attempt - 1))
delay = max(retry_after, backoff)
time.sleep(delay + random.uniform(0.0, 0.75))
raise DiscogsTemporaryError(
"Discogs temporarily blocked or rate-limited a Marketplace request. "
"Please wait a moment and press search again."
) from last_error
def _request_json(method, url, **kwargs):
return _request_discogs(method, url, **kwargs)
def _request_client_text(url):
return _request_discogs(
"GET", url, text=True, context="Marketplace query definitions"
)
def _graphql_headers(referer):
return {
"Accept": "application/graphql-response+json,application/json;q=0.9",
"Content-Type": "application/json",
"Origin": Config.DISCOGS_WEB_BASE,
"Referer": referer,
}
def _graphql_post(body, referer, context):
attempts = max(1, int(Config.REQUEST_RETRIES))
for attempt in range(1, attempts + 1):
payload = _request_json(
"POST",
f"{Config.DISCOGS_WEB_BASE}/graphql",
json_body=body,
headers=_graphql_headers(referer),
context=context,
)
errors = payload.get("errors") if isinstance(payload, dict) else None
if not errors:
return payload
if any(
error.get("message") == "PersistedQueryNotFound"
or (error.get("extensions") or {}).get("code")
== "PERSISTED_QUERY_NOT_FOUND"
for error in errors
):
raise DiscogsPersistedQueryError(
"Discogs changed its Marketplace query definitions. "
"Please update the sorter."
)
messages = [str(error.get("message") or "") for error in errors]
combined = " ".join(messages).casefold()
transient = any(
marker in combined
for marker in (
"subgraph error",
"internal server error",
"service unavailable",
"temporarily unavailable",
"timeout",
)
)
if transient:
if attempt < attempts:
print(
f"Discogs {context}: transient GraphQL error; "
f"retry {attempt}/{attempts}"
)
backoff = float(Config.RETRY_BACKOFF_SECONDS) * (2 ** (attempt - 1))
time.sleep(backoff + random.uniform(0.0, 0.75))
continue
raise DiscogsTemporaryError(
"Discogs temporarily failed a Marketplace request. "
"Please press search again."
)
message = messages[0] or "GraphQL query failed"
raise DiscogsProtocolError(f"Discogs Marketplace error: {message}.")
raise DiscogsTemporaryError(
"Discogs temporarily failed a Marketplace request. Please press search again."
)
def _refresh_persisted_query(operation_name, previous):
global _persisted_refresh_failure
with _persisted_queries_lock:
current = _persisted_queries.get(operation_name)
# Another worker may already have refreshed this generation while we
# waited. Reuse its document even if only the server's APQ cache reset.
if current is not None and current is not previous:
return current
if _persisted_refresh_failure is not None:
failed_at, failure = _persisted_refresh_failure
if time.monotonic() - failed_at < 30:
raise failure
try:
page_url = f"{Config.DISCOGS_WEB_BASE}/shop/list"
assets = client_asset_urls(_request_client_text(page_url), page_url)
definitions = {}
for url in assets:
found = query_definitions_from_bundle(_request_client_text(url))
for name, definition in found.items():
if name in definitions and definitions[name] != definition:
raise QueryDiscoveryError(f"Ambiguous {name} query definitions.")
definitions[name] = definition
if operation_name not in definitions:
raise QueryDiscoveryError(f"Missing registered {operation_name} query.")
except (DiscogsError, QueryDiscoveryError) as exc:
failure = (
exc
if isinstance(exc, DiscogsError)
else DiscogsProtocolError(
"Discogs changed its Marketplace client and the sorter could not "
"refresh its query definitions. Please update the sorter."
)
)
_persisted_refresh_failure = (time.monotonic(), failure)
if failure is exc:
raise
raise failure from exc
_persisted_queries.update(definitions)
_persisted_refresh_failure = None
return definitions[operation_name]
def _persisted_query(operation_name, variables, sha256_hash, referer):
definition = _persisted_queries.get(operation_name)
body = {
"operationName": operation_name,
"variables": variables,
"extensions": {
"clientLibrary": {"name": "@apollo/client", "version": "4.2.9"},
"persistedQuery": {
"version": 1,
"sha256Hash": definition.sha256_hash if definition else sha256_hash,
},
},
}
try:
return _graphql_post(body, referer, f"{operation_name} query")
except DiscogsPersistedQueryError:
print(f"Discogs {operation_name}: refreshing expired query definition")
definition = _refresh_persisted_query(operation_name, definition)
# Include the approved document on recovery, as Apollo does on an APQ
# miss. Subsequent requests use its cached hash without extra fetches.
body = {
**body,
"query": definition.document,
"extensions": {
**body["extensions"],
"persistedQuery": {
"version": 1,
"sha256Hash": definition.sha256_hash,
},
},
}
return _graphql_post(body, referer, f"{operation_name} query")
def _resolve_seller_id(username):
username = normalize_seller_input(username)
payload = _persisted_query(
"SellerSuggestions",
{"term": username, "wantlist": False},
SELLER_SUGGESTIONS_HASH,
f"{Config.DISCOGS_WEB_BASE}/shop/list/",
)
data = payload.get("data") if isinstance(payload, dict) else None
suggestions = data.get("sellerSuggestions") if isinstance(data, dict) else None
invalid_response = (
"Discogs returned an unexpected seller search response. Please update the sorter."
)
if not isinstance(suggestions, list):
raise DiscogsProtocolError(invalid_response)
seller_ids = set()
for seller in suggestions:
if not isinstance(seller, dict) or not isinstance(seller.get("name"), str):
raise DiscogsProtocolError(invalid_response)
if seller["name"].casefold() == username.casefold():
seller_id = seller.get("uid")
if type(seller_id) is not int or seller_id <= 0:
raise DiscogsProtocolError(invalid_response)
seller_ids.add(seller_id)
if len(seller_ids) != 1:
raise DiscogsNotFoundError(
f'Discogs Marketplace could not match the seller name "{username}" exactly. '
"Check the spelling, or select the seller on Discogs Marketplace and "
"paste the resulting link in the Filtered Discogs URL field."
)
return seller_ids.pop()
def _get_style_ids_by_name(referer):
global _style_ids_by_name
if _style_ids_by_name is not None:
return _style_ids_by_name
with _styles_lock:
if _style_ids_by_name is not None:
return _style_ids_by_name
payload = _persisted_query("Styles", {}, STYLES_HASH, referer)
styles = (payload.get("data") or {}).get("styles") or []
mapping = defaultdict(list)
for style in styles:
name = str(style.get("name") or "").strip()
style_id = style.get("discogsId")
if name and style_id is not None:
mapping[name.casefold()].append(str(style_id))
if not mapping:
raise DiscogsProtocolError(
"Discogs changed its style data unexpectedly. Please update the sorter."
)
_style_ids_by_name = dict(mapping)
return _style_ids_by_name
def _parse_price_range(value):
text = str(value or "").strip()
numbers = re.findall(r"\d+(?:\.\d+)?", text)
if not numbers:
return None, None
if text.startswith("-") or text.lower().startswith("under"):
return None, round(float(numbers[0]) - 0.01, 2)
if (
text.endswith("-")
or text.lower().endswith("-up")
or "and up" in text.lower()
or text.endswith("+")
):
return float(numbers[0]), None
if len(numbers) == 1:
value = float(numbers[0])
return value, value
return float(numbers[0]), round(float(numbers[1]) + 0.99, 2)
def _year_bounds(values):
years = []
for value in values:
text = str(value).strip()
decade = re.fullmatch(r"(\d{4})s", text)
if decade:
start = int(decade.group(1))
years.extend([start, start + 9])
elif re.fullmatch(r"\d{1,4}", text):
years.append(int(text))
if not years:
return None, None
return min(years), max(years)
def _group_url_params(raw_url):
parsed = urlparse(raw_url)
grouped = defaultdict(list)
unknown = []
for key, value in parse_qsl(parsed.query, keep_blank_values=True):
if key.lower().startswith("utm_") or key.lower() in _IGNORED_URL_KEYS:
continue
if key not in _SUPPORTED_FILTER_KEYS:
unknown.append(key)
continue
if value != "":
grouped[key].append(value)
if unknown:
names = ", ".join(sorted(set(unknown)))
raise DiscogsUnsupportedUrlError(
f"This Discogs URL uses an unsupported filter: {names}."
)
return grouped
def marketplace_query_from_url(raw_url, *, numeric_seller_is_username=False):
grouped = _group_url_params(raw_url)
referer = raw_url
graph_filter = {}
for url_key, filter_key in _STRING_ARRAY_FILTERS.items():
values = grouped.get(url_key)
if values:
graph_filter[filter_key] = values
and_key = _ARRAY_AND_FILTERS.get(filter_key)
if and_key:
graph_filter[and_key] = True
style_ids = list(grouped.get("styleId") or [])
style_names = grouped.get("style") or []
require_all_styles = True
if style_names:
mapping = _get_style_ids_by_name(referer)
for style_name in style_names:
matches = mapping.get(style_name.casefold())
if not matches:
raise DiscogsUnsupportedUrlError(
f'Discogs does not recognize the style "{style_name}".'
)
# Discogs uses alternative IDs for labels shared by multiple genres.
if len(matches) > 1:
require_all_styles = False
style_ids.extend(matches)
if style_ids:
graph_filter["styleId"] = list(dict.fromkeys(map(str, style_ids)))
graph_filter["styleIdAnd"] = require_all_styles
for key in _INTEGER_ARRAY_FILTERS:
values = grouped.get(key) or []
converted = []
for value in values:
if key == "seller" and (numeric_seller_is_username or not value.isdigit()):
converted.append(_resolve_seller_id(value))
else:
entity_id = _slugged_entity_id(value)
if entity_id is None:
raise DiscogsUnsupportedUrlError(
f'The {key} filter value "{value}" is not valid.'
)
converted.append(entity_id)
if converted:
graph_filter[key] = converted
low = grouped.get("priceMin", [None])[-1]
high = grouped.get("priceMax", [None])[-1]
if grouped.get("price") and low is None and high is None:
low, high = _parse_price_range(grouped["price"][-1])
if low not in (None, ""):
graph_filter["priceRangeLow"] = _safe_float(low)
if high not in (None, ""):
graph_filter["priceRangeHigh"] = _safe_float(high)
year_low = grouped.get("yearRangeLow", [None])[-1]
year_high = grouped.get("yearRangeHigh", [None])[-1]
if grouped.get("year") and year_low is None and year_high is None:
year_low, year_high = _year_bounds(grouped["year"])
if year_low not in (None, ""):
graph_filter["yearRangeLow"] = _safe_int(year_low)
if year_high not in (None, ""):
graph_filter["yearRangeHigh"] = _safe_int(year_high)
for url_key, filter_key in _BOOLEAN_FILTERS.items():
values = grouped.get(url_key)
if values and _is_true(values[-1]):
graph_filter[filter_key] = True
query = (grouped.get("q") or [None])[-1]
return {"filter": graph_filter, "query": query, "referer": referer}
def marketplace_query_for_seller(username):
seller_id = _resolve_seller_id(username)
referer = f"{Config.DISCOGS_WEB_BASE}/shop/list/?seller={seller_id}"
return {"filter": {"seller": [seller_id]}, "query": None, "referer": referer}
def _marketplace_search(search_query, *, first=250, after=None, direction="DESCENDING"):
variables = {
"first": int(first),
"sort": {"dimension": "LISTED_DATE", "direction": direction},
}
if search_query.get("filter"):
variables["filter"] = search_query["filter"]
if search_query.get("query"):
variables["query"] = search_query["query"]
if after:
variables["after"] = after
payload = _persisted_query(
"MarketplaceSearch",
variables,
MARKETPLACE_SEARCH_HASH,
search_query["referer"],
)
search = (payload.get("data") or {}).get("marketplaceSearch")
if not isinstance(search, dict):
raise DiscogsProtocolError(
"Discogs changed its Marketplace response unexpectedly. Please update the sorter."
)
return search
def _release_details(release_ids, referer):
unique_ids = list(dict.fromkeys(_safe_int(value) for value in release_ids if value))
if not unique_ids:
return {}
payload = {
"query": RELEASE_DETAILS_QUERY,
"variables": {"discogsIds": unique_ids, "first": 1},
"extensions": {
"persistedQuery": {"version": 1, "sha256Hash": RELEASE_DETAILS_HASH}
},
}
response = _graphql_post(payload, referer, "release community-count query")
details = {}
for release in (response.get("data") or {}).get("releases") or []:
if not release or release.get("discogsId") is None:
continue
details[_safe_int(release["discogsId"])] = {
"want": _safe_int(release.get("inWantlistCount")),
"have": _safe_int(release.get("inCollectionCount")),
}
return details
def _calculate_scores(want, have, price):
want = max(0, _safe_int(want))
have = max(0, _safe_int(have))
price = max(0.0, _safe_float(price))
desire_gap = want - have
rarity_score = round(desire_gap / (have + 1), 5)
hot_buy = round(
((want + (100 * rarity_score)) / (price + 1)) * (1 + (1 / (have + 1))),
5,
)
return hot_buy, rarity_score, desire_gap
def marketplace_node_to_record(node, detail):
release = node.get("release") or {}
artists = [
artist.get("displayName")
for artist in (release.get("primaryArtists") or [])
if artist.get("displayName")
]
format_summary = release.get("formatSummary") or {}
format_parts = [format_summary.get("primaryFormat")]
format_parts.extend(format_summary.get("recordingTypes") or [])
format_value = ", ".join(str(value) for value in format_parts if value)
price = node.get("price") or {}
price_value = _safe_float(price.get("amount"))
currency = price.get("currency") or ""
want = detail.get("want", 0)
have = detail.get("have", 0)
hot_buy, rarity_score, desire_gap = _calculate_scores(want, have, price_value)
listing_id = node.get("id")
return {
"hot_buy": hot_buy,
"rarity_score": rarity_score,
"desire_gap": desire_gap,
"have": have,
"want": want,
"artist": html.escape(", ".join(artists) or "Unknown Artist"),
"title": html.escape(str(release.get("title") or "Untitled")),
"format": format_value,
"condition": _condition_abbreviation(node.get("mediaCondition")),
"price": f"{price_value:,.2f} {currency}".strip(),
"href": f"/sell/item/{listing_id}",
}
def _parse_listed_date(value):
try:
return datetime.fromisoformat(str(value).replace("Z", "+00:00")).astimezone(
timezone.utc
)
except (TypeError, ValueError) as exc:
raise DiscogsProtocolError(
"Discogs returned a listing with an invalid listed date."
) from exc
def _cursor_before(moment):
return _cursor_for_key((int(moment.timestamp() * 1000), 9223372036854775807))
def _cursor_for_key(key):
raw = json.dumps([int(key[0]), int(key[1])], separators=(",", ":")).encode(
"utf-8"
)
return base64.b64encode(raw).decode("ascii")
def _cursor_key(cursor):
try:
value = json.loads(base64.b64decode(cursor))
return int(value[0]), int(value[1])
except (TypeError, ValueError, IndexError, json.JSONDecodeError) as exc:
raise DiscogsProtocolError(
"Discogs returned an invalid Marketplace cursor. Please retry."
) from exc
def _listing_key(node):
listed_at = _parse_listed_date(node.get("listedDate"))
return int(listed_at.timestamp() * 1000), _safe_int(node.get("id"))
def _records_for_nodes(nodes, referer):
release_ids = [
(node.get("release") or {}).get("discogsId")
for node in nodes
if node.get("release")
]
details = _release_details(release_ids, referer)
return [
marketplace_node_to_record(
node,
details.get(_safe_int((node.get("release") or {}).get("discogsId")), {}),
)
for node in nodes
]
def _dense_id_segments(
lower_key,
upper_key,
timestamp_ms,
current_after=None,
observed_max_id=None,
):
min_id = lower_key[1] if lower_key[0] == timestamp_ms else 0
max_id = upper_key[1] if upper_key[0] == timestamp_ms else None
if current_after:
after_key = _cursor_key(current_after)
if after_key[0] == timestamp_ms:
max_id = after_key[1] if max_id is None else min(max_id, after_key[1])
if max_id is None and observed_max_id is not None:
# The cursor bound is exclusive. Starting one above the largest ID on
# the detected page covers current IDs of any width without creating
# enormous, badly balanced 64-bit ranges.
max_id = int(observed_max_id) + 1
if max_id is None:
max_id = 9223372036854775807
if max_id <= min_id:
raise DiscogsProtocolError(
"Discogs returned an invalid dense Marketplace cursor range."
)
requested = max(1, int(Config.MARKETPLACE_DENSE_ID_SLICES))
step = max(1, math.ceil((max_id - min_id) / requested))
boundaries = list(range(max_id, min_id, -step))
if not boundaries or boundaries[-1] != min_id:
boundaries.append(min_id)