-
Notifications
You must be signed in to change notification settings - Fork 44
/
digitalreleases.py
952 lines (840 loc) · 36.5 KB
/
digitalreleases.py
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
### DAYS — за сколько последних дней загружать цифровые релизы. По умолчанию 60.
### SOCKS_IP и SOCKS_PORT — IP-адрес и порт SOCKS Proxy. Если они указаны, то будет импортирована библиотека (PySocks), а в функции rutorLinks запросы будет обрабатываться через указанный прокси-сервер. В digitalReleases и filmDetail запросы всегда идут без прокси.
### SORT_TYPE — тип финальной сортировки. rating — сортировка по рейтингу, releaseDate — сортировка по дате цифрового релиза, torrentsDate — сортировка по дате появления торрента, comboDate — сортировка по комбинированное дате (наибольшая из releaseDate и torrentsDate).
### USE_MAGNET — использование Magnet-ссылок вместо ссылок на торрент-файлы.
### digitalReleases(days) возвращает массив со словарями {filmID, releaseDate}, цифровые релизы за количество дней days.
### filmDetail(filmID) возвращает словарь с информацией по фильму, соответствующему filmID.
### rutorLinks(filmID) возвращает словарь с раздачами, соответствующими filmID.
### saveHTML(movies, filePath) формирует HTML-файл по пути filePath из массива movies.
### main объединяет всё вместе digitalReleases > rutorLinks + filmDetail > saveHTML.
DAYS = 60
USE_MAGNET = False
SORT_TYPE = "rating"
SOCKS_IP = ""
SOCKS_PORT = 0
HTML_SAVE_PATH = "/opt/share/www/releases.html"
#HTML_SAVE_PATH = r"C:\Users\Yuri\releases.html"
KINOPOISK_UUID = "6730382b7a236cd964264b49413ed00f" ### Генерируется автоматически в main, но можно в случае необходимости использовать константные значения.
KINOPOISK_CLIENTID = "56decdcf6d4ad1bcaa1b3856" ### Генерируется автоматически в main, но можно в случае необходимости использовать константные значения.
KINOPOISK_API_SALT = "IDATevHDS7"
KINOPOISK_BASE_URL = "https://ma.kinopoisk.ru"
KINOPOISK_API_RELEAESES = "/k/v1/films/releases/digital?digitalReleaseMonth={}&limit=1000&offset=0&uuid={}"
KINOPOISK_BASE_URL2 = "https://ma.kinopoisk.ru/ios/5.0.0/"
KINOPOISK_API_FILMDETAIL = "getKPFilmDetailView?still_limit=9&filmID={}&uuid={}"
POSTER_URL = "https://st.kp.yandex.net/images/{}{}width=360"
RUTOR_BASE_URL = "http://rutor.info/search/0/0/010/0/film%20"
import hashlib
import datetime
import urllib.request
from urllib.parse import urljoin
import time
import gzip
import json
import html
import re
import operator
import os
import binascii
if SOCKS_IP:
import socks
import socket
def digitalReleases(days):
rDict = {}
result = []
currentDateReal = datetime.date.today()
currentDate = currentDateReal + datetime.timedelta(days=7)
print("Текущая дата (с запасом 7 дней): " + currentDate.strftime("%d.%m.%Y"))
downloadDates =[currentDate]
targetDate = datetime.date.today() - datetime.timedelta(days=days)
print("Целевая дата: " + targetDate.strftime("%d.%m.%Y"))
iterationDate = datetime.date.today() + datetime.timedelta(days=7)
while (targetDate.year != iterationDate.year) or (targetDate.month != iterationDate.month):
iterationDate = iterationDate.replace(day=1) - datetime.timedelta(days=1)
downloadDates.append(iterationDate)
print("Количество месяцев для загрузки: " + str(len(downloadDates)))
for downloadDate in downloadDates:
print("Загрузка релизов за " + downloadDate.strftime("%m.%Y") + ".")
requestMethod = KINOPOISK_API_RELEAESES.format(downloadDate.strftime("%m.%Y"), KINOPOISK_UUID)
timestamp = str(int(round(time.time() * 1000)))
hashString = requestMethod + timestamp + KINOPOISK_API_SALT
request = urllib.request.Request(KINOPOISK_BASE_URL + requestMethod)
request.add_header("Accept-encoding", "gzip")
request.add_header("Accept", "application/json")
request.add_header("User-Agent", "Android client (6.0.1 / api23), ru.kinopoisk/4.6.5 (86)")
request.add_header("Image-Scale", "3")
request.add_header("device", "android")
request.add_header("ClientId", KINOPOISK_CLIENTID)
request.add_header("countryID", "2")
request.add_header("cityID", "1")
request.add_header("Android-Api-Version", "23")
request.add_header("clientDate", datetime.date.today().strftime("%H:%M %d.%m.%Y"))
request.add_header("X-TIMESTAMP", timestamp)
request.add_header("X-SIGNATURE", hashlib.md5(hashString.encode('utf-8')).hexdigest())
try:
response = urllib.request.urlopen(request)
except Exception:
print("Ошибка соединения при загрузке релизов за " + downloadDate.strftime("%m.%Y") + ". Даём второй шанс.")
response = urllib.request.urlopen(request)
if response.info().get('Content-Encoding') == 'gzip':
gzipFile = gzip.GzipFile(fileobj=response)
content = gzipFile.read().decode("utf-8")
else:
content = response.read().decode("utf-8")
if content:
tmpDict = json.loads(content)
if not tmpDict:
raise ValueError("Ошибка загрузки релизов за " + downloadDate.strftime("%m.%Y") + ". Ответ не соответствует JSON.")
if tmpDict.get("success") != True:
raise ValueError("Ошибка загрузки релизов за " + downloadDate.strftime("%m.%Y") + ". В ответе нет значения success или оно равно False.")
items = tmpDict.get("data")
if items == None or not isinstance(items, dict):
raise ValueError("Ошибка загрузки релизов за " + downloadDate.strftime("%m.%Y") + ". Проблемы со значением data.")
items = items.get("items")
if items == None or not isinstance(items, list):
raise ValueError("Ошибка загрузки релизов за " + downloadDate.strftime("%m.%Y") + ". Проблемы со значением items.")
for item in items:
if not isinstance(item, dict):
raise ValueError("Ошибка загрузки релизов за " + downloadDate.strftime("%m.%Y") + ". Проблемы с одним из элементов items.")
filmID = item.get("id")
if not isinstance(filmID, int):
raise ValueError("Ошибка загрузки релизов за " + downloadDate.strftime("%m.%Y") + ". Проблемы с id в одном из элементов items.")
contextData = item.get("contextData")
if not isinstance(contextData, dict):
raise ValueError("Ошибка загрузки релизов за " + downloadDate.strftime("%m.%Y") + ". Проблемы с contextData в одном из элементов items.")
releaseDateStr = contextData.get("releaseDate")
if not isinstance(releaseDateStr, str):
raise ValueError("Ошибка загрузки релизов за " + downloadDate.strftime("%m.%Y") + ". Проблемы с releaseDate в одном из элементов items.")
releaseDate = datetime.datetime.strptime(releaseDateStr, "%Y-%m-%d").date()
if (targetDate <= releaseDate) and (releaseDate <= currentDate):
rDict[str(filmID)] = releaseDate
else:
raise ValueError("Ошибка загрузки релизов за " + downloadDate.strftime("%m.%Y") + ".")
print("Загружены ID от {} релизов.".format(len(rDict)))
for key, value in rDict.items():
temp = {"filmID": key, "releaseDate":value}
result.append(temp)
return result
def filmDetail(filmID):
print("Загрузка данных для filmID " + filmID + ".")
result = {}
requestMethod = KINOPOISK_API_FILMDETAIL.format(filmID, KINOPOISK_UUID)
timestamp = str(int(round(time.time() * 1000)))
hashString = requestMethod + timestamp + KINOPOISK_API_SALT
request = urllib.request.Request(KINOPOISK_BASE_URL2 + requestMethod)
request.add_header("Accept-encoding", "gzip")
request.add_header("Accept", "application/json")
request.add_header("User-Agent", "Android client (6.0.1 / api23), ru.kinopoisk/4.6.5 (86)")
request.add_header("Image-Scale", "3")
request.add_header("device", "android")
request.add_header("ClientId", KINOPOISK_CLIENTID)
request.add_header("countryID", "2")
request.add_header("cityID", "1")
request.add_header("Android-Api-Version", "23")
request.add_header("clientDate", datetime.date.today().strftime("%H:%M %d.%m.%Y"))
request.add_header("X-TIMESTAMP", timestamp)
request.add_header("X-SIGNATURE", hashlib.md5(hashString.encode('utf-8')).hexdigest())
try:
response = urllib.request.urlopen(request)
except Exception:
print("Ошибка соединения при загрузке данных для filmID " + filmID + ". Даём второй шанс.")
response = urllib.request.urlopen(request)
if response.info().get('Content-Encoding') == 'gzip':
gzipFile = gzip.GzipFile(fileobj=response)
content = gzipFile.read().decode("utf-8")
else:
content = response.read().decode("utf-8")
if content:
tmpDict = json.loads(content)
#print(tmpDict)
if not tmpDict:
raise ValueError("Ошибка загрузки данных для filmID " + filmID + ". Ответ не соответствует JSON.")
if tmpDict.get("resultCode") != 0:
raise ValueError("Ошибка загрузки данных для filmID " + filmID + ". В ответе нет значения resultCode или оно не равно 0.")
itemData = tmpDict.get("data")
if itemData == None or not isinstance(itemData, dict):
raise ValueError("Ошибка загрузки данных для filmID " + filmID + ". Проблемы со значением data.")
nameRU = itemData.get("nameRU")
if nameRU == None or not isinstance(nameRU, str):
raise ValueError("Ошибка загрузки данных для filmID " + filmID + ". Проблемы со значением nameRU.")
nameEN = itemData.get("nameEN")
if nameEN == None or not isinstance(nameEN, str):
nameEN = ""
year = itemData.get("year")
if year == None or not isinstance(year, str):
raise ValueError("Ошибка загрузки данных для filmID " + filmID + ". Проблемы со значением year.")
country = itemData.get("country")
if country == None or not isinstance(country, str):
raise ValueError("Ошибка загрузки данных для filmID " + filmID + ". Проблемы со значением country.")
genre = itemData.get("genre")
if genre == None or not isinstance(genre, str):
raise ValueError("Ошибка загрузки данных для filmID " + filmID + ". Проблемы со значением genre.")
description = itemData.get("description")
if description == None or not isinstance(description, str):
raise ValueError("Ошибка загрузки данных для filmID " + filmID + ". Проблемы со значением description.")
ratingAgeLimits = itemData.get("ratingAgeLimits")
if ratingAgeLimits == None or not isinstance(ratingAgeLimits, str):
ratingAgeLimits = ""
posterURL = itemData.get("posterURL")
if posterURL == None or not isinstance(posterURL, str):
raise ValueError("Ошибка загрузки данных для filmID " + filmID + ". Проблемы со значением posterURL.")
if "?" in posterURL:
posterURL = POSTER_URL.format(posterURL, "&")
else:
posterURL = POSTER_URL.format(posterURL, "?")
filmLength = itemData.get("filmLength")
if filmLength == None or not isinstance(filmLength, str):
raise ValueError("Ошибка загрузки данных для filmID " + filmID + ". Проблемы со значением filmLength.")
ratingData = itemData.get("ratingData")
if ratingData == None or not isinstance(ratingData, dict):
raise ValueError("Ошибка загрузки данных для filmID " + filmID + ". Проблемы со значением ratingData.")
ratingKP = ratingData.get("rating")
if ratingKP == None or not isinstance(ratingKP, str):
ratingKP = ""
ratingIMDb = ratingData.get("ratingIMDb")
if ratingIMDb == None or not isinstance(ratingIMDb, str):
ratingIMDb = ""
webURL = itemData.get("webURL")
if webURL == None or not isinstance(webURL, str):
raise ValueError("Ошибка загрузки данных для filmID " + filmID + ". Проблемы со значением webURL.")
directors = []
actors = []
creators = itemData.get("creators")
if creators == None or not isinstance(creators, list):
raise ValueError("Ошибка загрузки данных для filmID " + filmID + ". Проблемы со значением creators.")
for personsGroup in creators:
if not isinstance(personsGroup, list):
raise ValueError("Ошибка загрузки данных для filmID " + filmID + ". Проблемы со значением creators > personsGroup.")
for person in personsGroup:
if not isinstance(person, dict):
raise ValueError("Ошибка загрузки данных для filmID " + filmID + ". Проблемы со значением creators > personsGroup > person.")
if person.get("professionKey") == "director":
if person.get("nameRU"):
directors.append(person.get("nameRU"))
if person.get("professionKey") == "actor":
if person.get("nameRU"):
actors.append(person.get("nameRU"))
else:
raise ValueError("Ошибка загрузки данных для filmID " + filmID + ".")
if ratingIMDb and ratingKP:
rating = "{0:.1f}".format((float(ratingKP) + float(ratingIMDb)) / 2.0 + 0.001)
elif ratingKP:
rating = ratingKP
elif ratingIMDb:
rating = ratingIMDb
else:
rating = "0"
directorsResult = ""
if len(directors) > 0:
for director in directors:
directorsResult += director
directorsResult += ", "
if directorsResult.endswith(", "):
directorsResult = directorsResult[:-2]
actorsResult = ""
if len(actors) > 0:
for actor in actors:
actorsResult += actor
actorsResult += ", "
if actorsResult.endswith(", "):
actorsResult = actorsResult[:-2]
result["filmID"] = filmID
result["nameRU"] = nameRU
result["nameOriginal"] = nameEN
result["description"] = description
result["year"] = year
result["country"] = country
result["genre"] = genre
result["ratingAgeLimits"] = ratingAgeLimits
result["posterURL"] = posterURL
result["filmLength"] = filmLength
result["ratingKP"] = ratingKP
result["ratingIMDb"] = ratingIMDb
result["rating"] = rating
result["ratingFloat"] = float(rating)
result["directors"] = directorsResult
result["actors"] = actorsResult
result["webURL"] = webURL
#print(result)
return result
def rutorLinks(filmID):
print("Загрузка торрент-ссылок для filmID " + filmID + ".")
if SOCKS_IP:
default_socket = socket.socket
socks.set_default_proxy(socks.SOCKS5, SOCKS_IP, SOCKS_PORT)
socket.socket = socks.socksocket
request = urllib.request.Request(RUTOR_BASE_URL + filmID)
request.add_header("Accept-encoding", "gzip")
request.add_header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0")
try:
response = urllib.request.urlopen(request)
except Exception:
print("Ошибка соединения при загрузке торрент-ссылок для filmID " + filmID + ". Даём второй шанс.")
response = urllib.request.urlopen(request)
if response.info().get('Content-Encoding') == 'gzip':
gzipFile = gzip.GzipFile(fileobj=response)
content = gzipFile.read().decode("utf-8")
else:
content = response.read().decode("utf-8")
if SOCKS_IP:
socket.socket = default_socket
strIndex = content.find("<div id=\"index\">")
if strIndex != -1:
content = content[strIndex:]
else:
raise IndexError("Ошибка загрузки торрент-ссылок для filmID " + filmID + ". Не найден блок с торрентами. Возможно, сайт rutor заблокирован.")
strIndex = content.find("</div>")
if strIndex != -1:
content = content[:-(len(content) - strIndex)]
else:
raise IndexError("Ошибка загрузки торрент-ссылок для filmID " + filmID + ". Не найден блок с торрентами. Возможно, сайт rutor заблокирован.")
patternLink = re.compile("<a class=\"downgif\" href=\"(.*?)\">")
matches1 = re.findall(patternLink, content)
patternName = re.compile("<a href=\"/torrent/(.*?)\">(.*?)</a>")
matches2 = re.findall(patternName, content)
patternSeeders = re.compile("alt=\"S\" />(.*?)</span>")
matches3 = re.findall(patternSeeders, content)
patternMagnet = re.compile("<a href=\"magnet:(.*?)\">")
matches4 = re.findall(patternMagnet, content)
patternDate = re.compile("<td>(.*?)</td><td ") #09 Мар 19
matches5 = re.findall(patternDate, content)
#print(str(len(matches1)) + " " + str(len(matches2)) + " " +str(len(matches3)) + " " + str(len(matches4)) + " " + str(len(matches5)))
if (len(matches1) != len(matches2)) or (len(matches1) != len(matches3)) or (len(matches1) != len(matches4)) or (len(matches1) != len(matches4)) or (len(matches1) != len(matches5)):
raise IndexError("Ошибка загрузки торрент-ссылок для filmID " + filmID + ". Неверный формат блока с торрентами.")
months = {"Янв": 1, "Фев": 2, "Мар": 3, "Апр": 4, "Май": 5, "Июн": 6, "Июл": 7, "Авг": 8, "Сен": 9, "Окт": 10, "Ноя": 11, "Дек": 12}
allTorrents = []
for i in range(len(matches1)):
link = matches1[i].strip()
if not link.startswith("http"):
link = urljoin("http://rutor.info", link)
dateStr = matches5[i].strip()
components = dateStr.split(" ")
if (len(components) != 3):
raise ValueError("Ошибка загрузки торрент-ссылок для filmID " + filmID + ". Неверный формат даты.")
torrentDate = datetime.date((int(components[2]) + 2000) if int(components[2]) < 2000 else int(components[2]), months[components[1]], int(components[0]))
#print(torrentDate)
tmpDict = {"link": link, "name": html.unescape(matches2[i][1]).strip(), "seeders": int(html.unescape(matches3[i]).strip()), "magnet": "magnet:" + (matches4[i]).strip(), "date": torrentDate}
allTorrents.append(tmpDict)
result = {}
for item in allTorrents:
tmpParts = item["name"].split("|")
if len(tmpParts) == 1:
continue
realName = tmpParts[0].strip().upper()
tags = set()
for i in range(1, len(tmpParts)):
tmpParts2 = tmpParts[i].split(",")
for tmpPart in tmpParts2:
tags.add(tmpPart.strip().upper())
if ("LINE" in tags) or ("UKR" in tags) or ("3D-VIDEO" in tags) or ("60 FPS" in tags):
continue
if not (("ЛИЦЕНЗИЯ" in tags) or ("ITUNES" in tags) or ("D" in tags) or ("D2" in tags)):
continue
if "UHD BDREMUX" in realName:
if "HDR" in tags:
if result.get("UHD BDRemux HDR") != None:
if item["seeders"] > result["UHD BDRemux HDR"]["seeders"]:
result["UHD BDRemux HDR"] = item #{"link": item["link"], "magnet": item["magnet"], "seeders": item["seeders"]}
else:
result["UHD BDRemux HDR"] = item
#print("!UHD BDRemux HDR: " + tmpParts[0])
else:
if result.get("UHD BDRemux SDR") != None:
if item["seeders"] > result["UHD BDRemux SDR"]["seeders"]:
result["UHD BDRemux SDR"] = item
else:
result["UHD BDRemux SDR"] = item
#print("!UHD BDRemux SDR: " + tmpParts[0])
elif "BDREMUX" in realName:
if result.get("BDRemux") != None:
if item["seeders"] > result["BDRemux"]["seeders"]:
result["BDRemux"] = item
else:
result["BDRemux"] = item
#print("!BDRemux: " + tmpParts[0])
elif "BDRIP-HEVC 1080" in realName:
if result.get("BDRip-HEVC 1080p") != None:
if item["seeders"] > result["BDRip-HEVC 1080p"]["seeders"]:
result["BDRip-HEVC 1080p"] = item
else:
result["BDRip-HEVC 1080p"] = item
#print("!BDRip-HEVC 1080p: " + tmpParts[0])
elif "BDRIP 1080" in realName:
if result.get("BDRip 1080p") != None:
if item["seeders"] > result["BDRip 1080p"]["seeders"]:
result["BDRip 1080p"] = item
else:
result["BDRip 1080p"] = item
#print("!BDRip 1080p: " + tmpParts[0])
elif "WEB-DL 2160" in realName:
if "HDR" in tags:
if result.get("WEB-DL 2160p HDR") != None:
if item["seeders"] > result["WEB-DL 2160p HDR"]["seeders"]:
result["WEB-DL 2160p HDR"] = item
else:
result["WEB-DL 2160p HDR"] = item
#print("!WEB-DL 2160p HDR: " + tmpParts[0])
else:
if result.get("WEB-DL 2160p SDR") != None:
if item["seeders"] > result["WEB-DL 2160p SDR"]["seeders"]:
result["WEB-DL 2160p SDR"] = item
else:
result["WEB-DL 2160p SDR"] = item
#print("!WEB-DL 2160p SDR: " + tmpParts[0])
elif "WEB-DL 1080" in realName:
if result.get("WEB-DL 1080p") != None:
if item["seeders"] > result["WEB-DL 1080p"]["seeders"]:
result["WEB-DL 1080p"] = item
else:
result["WEB-DL 1080p"] = item
#print("!WEB-DL 1080p: " + tmpParts[0])
if result.get("UHD BDRemux HDR") or result.get("UHD BDRemux SDR") or result.get("BDRip-HEVC 1080p") or result.get("BDRip 1080p"):
result.pop("WEB-DL 2160p HDR", None)
result.pop("WEB-DL 2160p SDR", None)
result.pop("WEB-DL 1080p", None)
finalResult = []
if result.get("WEB-DL 1080p"):
finalResult.append({"link": result["WEB-DL 1080p"]["link"], "magnet": result["WEB-DL 1080p"]["magnet"], "date": result["WEB-DL 1080p"]["date"], "type": "WEB-DL 1080p"})
if result.get("WEB-DL 2160p HDR"):
finalResult.append({"link": result["WEB-DL 2160p HDR"]["link"], "magnet": result["WEB-DL 2160p HDR"]["magnet"], "date": result["WEB-DL 2160p HDR"]["date"], "type": "WEB-DL 2160p HDR"})
elif result.get("WEB-DL 2160p SDR"):
finalResult.append({"link": result["WEB-DL 2160p SDR"]["link"], "magnet": result["WEB-DL 2160p SDR"]["magnet"], "date": result["WEB-DL 2160p SDR"]["date"], "type": "WEB-DL 2160p SDR"})
if result.get("BDRip 1080p"):
finalResult.append({"link": result["BDRip 1080p"]["link"], "magnet": result["BDRip 1080p"]["magnet"], "date": result["BDRip 1080p"]["date"], "type": "BDRip 1080p"})
if result.get("BDRip-HEVC 1080p"):
finalResult.append({"link": result["BDRip-HEVC 1080p"]["link"], "magnet": result["BDRip-HEVC 1080p"]["magnet"], "date": result["BDRip-HEVC 1080p"]["date"], "type": "BDRip-HEVC 1080p"})
if result.get("BDRemux"):
finalResult.append({"link": result["BDRemux"]["link"], "magnet": result["BDRemux"]["magnet"], "date": result["BDRemux"]["date"], "type": "BDRemux"})
if result.get("UHD BDRemux HDR"):
finalResult.append({"link": result["UHD BDRemux HDR"]["link"], "magnet": result["UHD BDRemux HDR"]["magnet"], "date": result["UHD BDRemux HDR"]["date"], "type": "UHD BDRemux HDR"})
elif result.get("UHD BDRemux SDR"):
finalResult.append({"link": result["UHD BDRemux SDR"]["link"], "magnet": result["UHD BDRemux SDR"]["magnet"], "date": result["UHD BDRemux SDR"]["date"], "type": "UHD BDRemux SDR"})
#print(finalResult)
return finalResult
def saveHTML(movies, filePath):
f = open(filePath,'w', encoding='utf-8')
html = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ru-RU">
<head>
<meta charset="utf-8">
<meta content="width=960" name="viewport">
<title>Новые цифровые релизы</title>
<style type="text/css">
html {
background-color: #e6e6e6;
min-width: 1024px;
width: 100%;
position: relative;
}
body {
background: #e6e6e6;
color: #333;
font-family: tahoma,verdana,arial;
margin: 0;
padding: 0 0 22px 0;
}
* {
outline: 0;
}
.shadow {
box-shadow: 0px 10px 20px 0px rgba(0, 0, 0, 0.2);
width: 850px;
margin: 0 auto;
position: relative;
z-index: 1;
}
.block1 {
width: 850px;
position: relative;
margin: 0 auto;
}
.sbb {
background-color: #f2f2f2;
text-align: right;
padding-right:10px;
}
.sButton {
display: inline-block;
background:none;
border:none;
margin-left: 10px;
margin-right: 10px;
padding:0;
cursor: pointer;
text-decoration: dashed underline;
font-family: tahoma,verdana,arial;
font-size: 13px;
}
"""
if (SORT_TYPE == "releaseDate"):
html += """ #sortButton1 {
}
#sortButton2 {
color: #f60;
}
#sortButton4 {
}
#sortButton3 {
}"""
elif (SORT_TYPE == "torrentsDate"):
html += """ #sortButton1 {
}
#sortButton2 {
}
#sortButton4 {
}
#sortButton3 {
color: #f60;
}"""
elif (SORT_TYPE == "comboDate"):
html += """ #sortButton1 {
}
#sortButton2 {
}
#sortButton4 {
color: #f60;
}
#sortButton3 {
}"""
else:
html += """ #sortButton1 {
color: #f60;
}
#sortButton2 {
}
#sortButton4 {
}
#sortButton3 {
}"""
html += """
.block2 {
position: relative;
background-color: #f2f2f2;
width: 100%;
}
.block2::before, .block2::after {
content: "";
display: table;
}
.block2::after, .photoInfoTable::after {
clear: both;
}
.photoInfoTable::before, .photoInfoTable::after {
content: "";
display: table;
}
.photoInfoTable {
width: 850px;
float: left;
}
.headerFilm h1 {
margin: 0;
padding: 0;
}
.headerFilm {
width: 620px;
padding: 20px 20px 20px 15px;
position: relative;
}
H1.moviename {
vertical-align: middle;
padding-left: 0px;
margin: 5px 0;
font-size: 25px;
font-weight: normal;
}
H1 {
font-size: 25px;
font-weight: normal;
color: #000;
}
.headerFilm > span {
color: #666;
font-size: 13px;
}
.film-img-box {
margin-left: 0;
position: relative;
left: -12px;
min-height: 205px;
margin-bottom: 15px;
}
.film-img-box img {
border: 0;
}
.photoBlock {
width: 210px;
padding: 0 0 0 0;
float: left;
position: relative;
font-size: 11px;
}
.movie-buttons-container {
margin-bottom: 20px;
}
.torrentbutton {
cursor: pointer;
border: none;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-color: #f60;
border-radius: 3px;
color: #fff;
display: block;
font: 12px Arial, sans-serif;
font-weight: normal;
line-height: normal;
font-weight: bold;
height: 35px;
line-height: 36px;
-webkit-transition: background-color 0.1s, color 0.1s, border-color 0.1s;
-moz-transition: background-color 0.1s, color 0.1s, border-color 0.1s;
transition: background-color 0.1s, color 0.1s, border-color 0.1s;
text-align: center;
text-decoration: none;
width: 160px;
margin: 10px 0 10px 15px;
display:inline-block;
}
.infoTable {
float: left;
display: block;
}
.infoTable .info {
width: 465px;
}
.info, .info * {
border-collapse: collapse;
margin: 0;
padding: 0;
}
.info tr {
border-bottom: #DFDFDF solid 1px;
}
.info .type {
color: #f60;
width: 119px;
padding-left: 23px;
}
.info td {
min-height: 14px;
vertical-align: top;
padding-bottom: 9px;
padding: 6px 0 6px 20px;
}
td {
font-family: tahoma,verdana,arial;
font-size: 11px;
color: #000;
}
.film-rating {
border-radius: 1px;
position: absolute;
left: 5px;
top: 5px;
z-index: 5;
box-shadow: none;
color: #fff;
width: 32px;
font-size: 11px;
font-weight: 600;
line-height: 13px;
padding: 3px 0 2px;
text-align: center;
font-family: Arial,Tahoma,Verdana,sans-serif;
}
</style>
<script>
function sortElements(sortType){
var container = document.getElementsByClassName('block1')[0];
var newContainer = container.cloneNode(false);
var items = [];
for(var i = container.childNodes.length; i--;){
if(container.childNodes[i].nodeName === 'DIV')
items.push(container.childNodes[i]);
}
if(sortType === "torrentDate") {
items.sort(function(a, b){
var aDate = new Date(a.getAttribute('data-torrentDate'));
var bDate = new Date(b.getAttribute('data-torrentDate'));
return (Number(bDate) - Number(aDate));
});
} else if(sortType === "releaseDate") {
items.sort(function(a, b){
var aDate = new Date(a.getAttribute('data-releaseDate'));
var bDate = new Date(b.getAttribute('data-releaseDate'));
return (Number(bDate) - Number(aDate));
});
} else if(sortType === "comboDate") {
items.sort(function(a, b){
var aDate = new Date(a.getAttribute('data-comboDate'));
var bDate = new Date(b.getAttribute('data-comboDate'));
return (Number(bDate) - Number(aDate));
});
} else {
items.sort(function(a, b){
return (Math.round(parseFloat(b.getAttribute('data-rating'))*10) - Math.round(parseFloat(a.getAttribute('data-rating'))*10));
});
}
for(var i = 0; i < items.length; i++)
newContainer.appendChild(items[i]);
container.parentNode.replaceChild(newContainer, container);
}
function sortRating(){
sortElements("rating");
document.getElementById("sortButton2").style.color = "black";
document.getElementById("sortButton3").style.color = "black";
document.getElementById("sortButton4").style.color = "black";
document.getElementById("sortButton1").style.color = "#f60";
}
function sortTorrentsDate(){
sortElements("torrentDate");
document.getElementById("sortButton1").style.color = "black";
document.getElementById("sortButton2").style.color = "black";
document.getElementById("sortButton4").style.color = "black";
document.getElementById("sortButton3").style.color = "#f60";
}
function sortReleaseDate(){
sortElements("releaseDate");
document.getElementById("sortButton1").style.color = "black";
document.getElementById("sortButton3").style.color = "black";
document.getElementById("sortButton4").style.color = "black";
document.getElementById("sortButton2").style.color = "#f60";
}
function sortComboDate(){
sortElements("comboDate");
document.getElementById("sortButton1").style.color = "black";
document.getElementById("sortButton3").style.color = "black";
document.getElementById("sortButton2").style.color = "black";
document.getElementById("sortButton4").style.color = "#f60";
}
</script>
</head>
<body>
<div class="shadow">
<div class="sbb">
<button id="sortButton1" class="sButton" onclick="sortRating()">по рейтингу</button>
<button id="sortButton2" class="sButton" onclick="sortReleaseDate()">по дате цифрового релиза</button>
<button id="sortButton3" class="sButton" onclick="sortTorrentsDate()">по дате торрент-релиза</button>
<button id="sortButton4" class="sButton" onclick="sortComboDate()">по комбинированной дате</button>
</div>
<div class="block1" style="background-color: #f2f2f2;">"""
descriptionTemplate = """
<tr>
<td class="type">{}</td>
<td>
<div style="position: relative">
{}
</div>
</td>
</tr>"""
buttonsTemplate = """ <button class="torrentbutton" style="" onclick="location.href='{}'">{}</button>"""
movieTemplate = """ <div class="block2" data-releaseDate="{}" data-torrentDate="{}" data-rating="{}" data-comboDate="{}">
<div class="photoInfoTable">
<div class="headerFilm">
<h1 class="moviename" itemprop="name">{}</h1>
<span itemprop="alternativeHeadline" style="{}">{}</span>
</div>
<div class="photoBlock">
<div class="film-img-box">
<div class="film-rating" style="background-color: {};">{}</div> <!-- #3bb33b > 7 #aaa; -->
<img src="{}" alt="{}" itemprop="image" width="205"></img>
</div>
</div>
<div class="infoTable">
<table class="info">
<tbody>
{}
</tbody>
</table>
</div>
</div>
<div class="movie-buttons-container">
{}
</div>
</div>
"""
for movie in movies:
#print(movie["nameRU"])
#print(movie["torrentsDate"])
#print(movie["releaseDate"])
descriptionBlock = ""
descriptionBlock += descriptionTemplate.format("год", movie["year"])
descriptionBlock += descriptionTemplate.format("страна", movie["country"])
descriptionBlock += descriptionTemplate.format("режиссёр", movie["directors"])
descriptionBlock += descriptionTemplate.format("актёры", movie["actors"])
descriptionBlock += descriptionTemplate.format("жанр", movie["genre"])
if len(movie["ratingAgeLimits"]) > 0:
if int(movie["ratingAgeLimits"]) <= 6:
descriptionBlock += descriptionTemplate.format("возраст", "от 6 лет")
elif int(movie["ratingAgeLimits"]) <= 12:
descriptionBlock += descriptionTemplate.format("возраст", "от 12 лет")
elif int(movie["ratingAgeLimits"]) <= 16:
descriptionBlock += descriptionTemplate.format("возраст", "от 16 лет")
elif int(movie["ratingAgeLimits"]) <= 18:
descriptionBlock += descriptionTemplate.format("возраст", "от 18 лет")
#descriptionBlock += descriptionTemplate.format("возраст", movie["ratingAgeLimits"] + " и старше")
descriptionBlock += descriptionTemplate.format("продолжительность", movie["filmLength"])
if len(movie["ratingKP"]) > 0:
rKP = movie["ratingKP"]
else:
rKP = "отсутствует"
descriptionBlock += descriptionTemplate.format("рейтинг КиноПоиск", "<a href=\"{}\" style=\"text-decoration: underline; color:black\">{}</a>".format(movie["webURL"], rKP))
if len(movie["ratingIMDb"]) > 0:
descriptionBlock += descriptionTemplate.format("рейтинг IMDb", movie["ratingIMDb"])
descriptionBlock += descriptionTemplate.format("цифровой релиз", movie["releaseDate"].strftime("%d.%m.%Y"))
descriptionBlock += descriptionTemplate.format("торрент-релиз", "<a href=\"{}\" style=\"text-decoration: underline; color:black\">{}</a>".format(RUTOR_BASE_URL + movie["filmID"], movie["torrentsDate"].strftime("%d.%m.%Y")))
descriptionBlock += descriptionTemplate.format("описание", movie["description"])
torrents = movie["torrents"]
buttonsBlock = ""
for torrent in torrents:
if USE_MAGNET:
buttonsBlock += buttonsTemplate.format(torrent["magnet"], torrent["type"])
else:
buttonsBlock += buttonsTemplate.format(torrent["link"], torrent["type"])
displayOrigName = "display: none;"
if len(movie["nameOriginal"]) > 0:
displayOrigName = ""
ratingColor = "#aaa"
if movie["ratingFloat"] >= 7:
ratingColor = "#3bb33b"
elif movie["ratingFloat"] < 5.5:
ratingColor = "#b43c3c"
html += movieTemplate.format(movie["releaseDate"].strftime("%Y-%m-%d"), movie["torrentsDate"].strftime("%Y-%m-%d"), movie["rating"], movie["comboDate"].strftime("%Y-%m-%d"), movie["nameRU"], displayOrigName, movie["nameOriginal"], ratingColor, movie["rating"], movie["posterURL"], movie["nameRU"], descriptionBlock, buttonsBlock)
html += """ </div>
</div>
</body>
</html>"""
f.write(html)
f.close()
return
def main():
KINOPOISK_UUID = binascii.b2a_hex(os.urandom(16))
KINOPOISK_CLIENTID = binascii.b2a_hex(os.urandom(12))
releases = digitalReleases(DAYS)
movies = []
for release in releases:
torrents = rutorLinks(release["filmID"])
if len(torrents) == 0:
continue
dates = []
for torrent in torrents:
dates.append(torrent["date"])
dates.sort()
detail = filmDetail(release["filmID"])
detail["releaseDate"] = release["releaseDate"]
detail["torrents"] = torrents
detail["torrentsDate"] = dates[0]
detail["comboDate"] = max(release["releaseDate"], dates[0])
#print(detail["comboDate"])
movies.append(detail)
if (SORT_TYPE == "releaseDate"):
movies.sort(key = operator.itemgetter("releaseDate"), reverse = True)
elif (SORT_TYPE == "torrentsDate"):
movies.sort(key = operator.itemgetter("torrentsDate"), reverse = True)
elif (SORT_TYPE == "comboDate"):
movies.sort(key = operator.itemgetter("comboDate"), reverse = True)
else:
movies.sort(key = operator.itemgetter("ratingFloat"), reverse = True)
saveHTML(movies, HTML_SAVE_PATH)
main()