forked from Twoure/KissNetwork.bundle
-
Notifications
You must be signed in to change notification settings - Fork 2
/
__init__.py
1938 lines (1666 loc) · 73.2 KB
/
__init__.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
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
####################################################################################################
# #
# KissNetwork Plex Channel #
# #
####################################################################################################
# import Shared Service Code
Domain = SharedCodeService.domain
Headers = SharedCodeService.kissheaders.Headers
Common = SharedCodeService.common
Metadata = SharedCodeService.metadata
KData = SharedCodeService.data.Data
kissanimesolver = SharedCodeService.kissanimesolver
# set global variables needed for imported packages
TITLE = Common.TITLE
PREFIX = Common.PREFIX
TIMEOUT = Common.TIMEOUT
GIT_REPO = 'Twoure/{}.bundle'.format(TITLE)
URL_CACHE_DIR = 'DataHTTP'
THUMB_CACHE_DIR = 'DataCovers'
BOOKMARK_CACHE_DIR = 'DataBookmarks'
# setup Updater and update headers if Dict['init_run'] updates
from pluginupdateservice import PluginUpdateService
Updater = PluginUpdateService()
if not Updater.initial_run:
Log("* Sending request to initialize headers")
Thread.Create(Headers.init_headers, init=True)
# import local and remote packages
import messages
import requests
import time, re
from io import open
import rhtml as RHTML
from AuthTools import CheckAdmin
from DumbTools import DumbKeyboard, DumbPrefs
from DevTools import add_dev_tools, SaveCoverImage, SetUpCFTest, ClearCache, BookmarkTools
# more global variables
SORT_OPT = {'Alphabetical': '', 'Popularity': '/MostPopular', 'Latest Update': '/LatestUpdate', 'Newest': '/Newest'}
ADULT_LIST = set(['Adult', 'Smut', 'Ecchi', 'Lolicon', 'Mature', 'Yaoi', 'Yuri'])
CP_DATE = ['Plex for Android', 'Plex for iOS', 'Plex Home Theater', 'OpenPHT']
CFTest_KEY = 'Manga'
RE_TITLE_CLEAN = Regex(r'[^a-zA-Z0-9 \n]')
RE_TITLE_CLEAN_DOT = Regex(r'[^a-zA-Z0-9 \n\.]')
# Set background art and icon defaults
# KissAnime
ANIME_ART = 'art-anime.jpg'
ANIME_ICON = 'icon-anime.png'
# KissAsian
ASIAN_ART = 'art-drama.jpg'
ASIAN_ICON = 'icon-drama.png'
# KissCartoon
CARTOON_ART = 'art-cartoon.jpg'
CARTOON_ICON = 'icon-cartoon.png'
# KissManga
MANGA_ART = 'art-manga.jpg'
MANGA_ICON = 'icon-manga.png'
# ReadComincOnline
COMIC_ART = 'art-comic.jpg'
COMIC_ICON = 'icon-comic.png'
# General
MAIN_ART = 'art-main.jpg'
MAIN_ICON = 'icon-default.png'
NEXT_ICON = 'icon-next.png'
CATEGORY_VIDEO_ICON = 'icon-video.png'
CATEGORY_PICTURE_ICON = 'icon-pictures.png'
BOOKMARK_ICON = 'icon-bookmark.png'
BOOKMARK_ADD_ICON = 'icon-add-bookmark.png'
BOOKMARK_REMOVE_ICON = 'icon-remove-bookmark.png'
BOOKMARK_CLEAR_ICON = 'icon-clear-bookmarks.png'
SEARCH_ICON = 'icon-search.png'
PREFS_ICON = 'icon-prefs.png'
CACHE_COVER_ICON = 'icon-cache-cover.png'
ABOUT_ICON = 'icon-about.png'
MC = messages.NewMessageContainer(PREFIX, TITLE)
####################################################################################################
def Start():
ObjectContainer.art = R(MAIN_ART)
ObjectContainer.title1 = TITLE
DirectoryObject.thumb = R(MAIN_ICON)
DirectoryObject.art = R(MAIN_ART)
PopupDirectoryObject.art = R(MAIN_ART)
InputDirectoryObject.art = R(MAIN_ART)
HTTP.CacheTime = 0
HTTP.Headers['User-Agent'] = Common.USER_AGENT
version = get_channel_version()
Log.Debug('*' * 80)
Log.Debug('* Platform.OS = {}'.format(Platform.OS))
Log.Debug('* Platform.OSVersion = {}'.format(Platform.OSVersion))
Log.Debug('* Platform.CPU = {}'.format(Platform.CPU))
Log.Debug('* Platform.ServerVersion = {}'.format(Platform.ServerVersion))
Log.Debug('* Channel.Version = {}'.format(version))
Log.Debug('*' * 80)
# setup test for cfscrape
SetUpCFTest(CFTest_KEY)
# setup auto-managed bookmark backups
BookmarkTools.auto_backup()
# Clear Old Cached URLs & Cover Thumbs
Thread.Create(ClearCache, itemname=URL_CACHE_DIR, timeout=TIMEOUT)
Thread.Create(ClearCache, itemname=THUMB_CACHE_DIR, timeout=Datetime.Delta(weeks=4))
# remove/clear old style of caching prior to v1.2.7
if Dict['current_ch_version']:
if Common.ParseVersion(Dict['current_ch_version']) < (1, 2, 7):
Log(u"* Channel updated from {} to {}. Clearing old cache and moving Bookmark backups.".format(Dict['current_ch_version'], version))
from DevTools import ClearOldCache, MoveOldBookmarks
Thread.Create(MoveOldBookmarks)
Thread.Create(ClearOldCache, itempath=Core.storage.join_path(Core.bundle_path, 'Contents', 'Resources'))
Thread.Create(ClearOldCache, itempath=Core.storage.join_path(Core.storage.data_path, 'DataItems'))
elif Common.ParseVersion(Dict['current_ch_version']) < Common.ParseVersion(version):
Log(u"* Channel updated from {} to {}".format(Dict['current_ch_version'], version))
# setup current channel version
Dict['current_ch_version'] = version
####################################################################################################
@handler(PREFIX, TITLE, MAIN_ICON, MAIN_ART)
def MainMenu():
"""Create the Main Menu"""
#Thread.Create(kissanimesolver.test)
Log.Debug('*' * 80)
Log.Debug('* Client.Product = {}'.format(Client.Product))
Log.Debug('* Client.Platform = {}'.format(Client.Platform))
Log.Debug('* Client.Version = {}'.format(Client.Version))
# if cfscrape failed then stop the channel, and return error message.
SetUpCFTest(CFTest_KEY)
if not Dict['cfscrape_test']:
return MC.message_container('Error',
'CloudFlare bypass failed. Please report Error to Twoure with channel Log files.')
elif not Headers.init_headers():
return MC.message_container('Warning', 'Please wait while channel caches headers. Exit channel and try again later.')
admin = CheckAdmin()
oc = ObjectContainer(title2=TITLE, no_cache=Client.Product in ['Plex Web'])
cp_match = True if Client.Platform in Common.LIST_VIEW_CLIENTS else False
data = list()
for t, u in Common.BaseURLListTuple():
thumb = 'icon-{}.png'.format(t.lower())
rthumb = None if cp_match else R(thumb)
art = 'art-{}.jpg'.format(t.lower())
rart = R(art)
prefs_name = 'kissasian' if t == 'Drama' else 'kiss{}'.format(t.lower())
data.append({
'prefs_name': prefs_name, 'title': t, 'art': art,
'rart': rart, 'thumb': thumb, 'rthumb': rthumb, 'url': u
})
# set thumbs based on client
if cp_match:
bookmark_thumb = None
prefs_thumb = None
search_thumb = None
about_thumb = None
else:
bookmark_thumb = R(BOOKMARK_ICON)
prefs_thumb = R(PREFS_ICON)
search_thumb = R(SEARCH_ICON)
about_thumb = R(ABOUT_ICON)
# set status for bookmark sub menu
if Dict['Bookmark_Deleted']:
if Dict['Bookmark_Deleted']['bool']:
Dict['Bookmark_Deleted'].update({'bool': False, 'type_title': None})
Dict.Save()
else:
Dict['Bookmark_Deleted'] = {'bool': False, 'type_title': None}
Dict.Save()
status = Dict['Bookmark_Deleted']
Dict.Save()
if admin:
if Prefs['update_channel'] == 'Stable':
# Setup Updater to track latest release
Updater.gui_update(
PREFIX + '/updater', oc, GIT_REPO,
tag='latest', list_view_clients=Common.LIST_VIEW_CLIENTS
)
else:
# Setup Updater to track branch commits
Updater.gui_update(
PREFIX + '/updater', oc, GIT_REPO,
branch='dev', list_view_clients=Common.LIST_VIEW_CLIENTS
)
# set up Main Menu depending on what sites are picked in the Prefs menu
prefs_names = ['kissanime', 'kissasian', 'kisscartoon', 'kissmanga', 'kisscomic']
b_prefs_names = [p for p in prefs_names if Prefs[p]]
# present KissMain directly if no other sites selected
if len(b_prefs_names) == 1:
b_prefs_name = b_prefs_names[0]
p_data = [d for d in data if d['prefs_name'] == b_prefs_name][0]
if Prefs['simple']:
oc.add(DirectoryObject(
key=Callback(KissMain, url=p_data['url'], title=p_data['title'], art=p_data['art']),
title=p_data['title'], thumb=p_data['rthumb'], art=p_data['rart']
))
else:
KissMain(url=p_data['url'], title=p_data['title'], art=p_data['art'], ob=False, oc=oc)
else:
for d in Util.ListSortedByKey(data, 'title'):
if Prefs[d['prefs_name']]:
oc.add(DirectoryObject(
key=Callback(KissMain, url=d['url'], title=d['title'], art=d['art']),
title=d['title'], thumb=d['rthumb'], art=d['rart']
))
oc.add(DirectoryObject(
key=Callback(BookmarksMain, title='My Bookmarks', status=status), title='My Bookmarks',
thumb=bookmark_thumb
))
if Client.Product in DumbPrefs.clients:
DumbPrefs(PREFIX, oc, title='Preferences', thumb=prefs_thumb)
elif admin:
oc.add(PrefsObject(title='Preferences', thumb=prefs_thumb))
oc.add(DirectoryObject(key=Callback(About), title='About / Help', thumb=about_thumb))
if Client.Product in DumbKeyboard.clients:
DumbKeyboard(PREFIX, oc, Search, dktitle='Search', dkthumb=R(SEARCH_ICON))
else:
oc.add(InputDirectoryObject(
key=Callback(Search), title='Search', prompt='Search for...', thumb=search_thumb
))
return oc
####################################################################################################
@route(PREFIX + '/kissmain', ob=bool)
def KissMain(url, title, art, ob=True, oc=None):
"""Create All Kiss Site Menu"""
if ob:
oc = ObjectContainer(title2=title, art=R(art))
if Prefs['simple']:
return DirectoryList(page=1, pname='All', category='All', base_url=url, type_title=title, art=art)
newest_c_title = 'New {}'.format(title)
oc.add(DirectoryObject(
key=Callback(DirectoryList,
page=1, pname='All', category='All', base_url=url, type_title=title, art=art),
title='All'))
oc.add(DirectoryObject(
key=Callback(AlphabetList, url=url, title=title, art=art), title='Alphabets'))
oc.add(DirectoryObject(
key=Callback(GenreList, url=url, title=title, art=art), title='Genres'))
if title == 'Drama':
oc.add(DirectoryObject(
key=Callback(CountryList, url=url, title=title, art=art), title='Countries'))
if (title == 'Anime') or (title == 'Cartoon') or (title == 'Drama'):
oc.add(DirectoryObject(
key=Callback(DirectoryList,
page=1, pname='/Genre/Movie', category='Movie', base_url=url, type_title=title, art=art),
title='Movies'))
oc.add(DirectoryObject(key=Callback(StatusList, url=url, type_title=title, art=art),
title='Status'))
if (title == 'Drama') or (title == 'Cartoon') or (title == 'Comic'):
oc.add(DirectoryObject(key=Callback(TopList, url=url, type_title=title, art=art),
title='Top'))
oc.add(DirectoryObject(
key=Callback(DirectoryList,
page=1, pname='/LatestUpdate', category='Latest Update', base_url=url, type_title=title, art=art),
title='Latest Update'))
if title == 'Anime':
newest_c_title = 'Recent Additions'
oc.add(DirectoryObject(
key=Callback(DirectoryList,
page=1, pname='/NewAndHot', category='New & Hot', base_url=url, type_title=title, art=art),
title='New & Hot'))
oc.add(DirectoryObject(
key=Callback(DirectoryList,
page=1, pname='/Newest', category=newest_c_title, base_url=url, type_title=title, art=art),
title=newest_c_title))
oc.add(DirectoryObject(
key=Callback(DirectoryList,
page=1, pname='/MostPopular', category='Most Popular', base_url=url, type_title=title, art=art),
title='Most Popular'))
if ob:
return oc
####################################################################################################
@route(PREFIX + '/status-list')
def StatusList(type_title, url, art):
"""
Setup Status List for each site
Ongoing and Completed list
"""
oc = ObjectContainer(title2=type_title, art=R(art))
for s in ['Ongoing', 'Completed']:
oc.add(DirectoryObject(
key=Callback(DirectoryList,
page=1, pname='/Status/{}'.format(s), category=s, base_url=url, type_title=type_title, art=art),
title=s))
return oc
####################################################################################################
@route(PREFIX + '/top-list')
def TopList(type_title, url, art):
"""
Setup Top list for Cartoon and Drama
Top Today, Week, Month
"""
oc = ObjectContainer(title2=type_title, art=R(art))
for t in ['Top Day', 'Top Week', 'Top Month']:
tab = t.split('Top')[1].strip().lower()
oc.add(DirectoryObject(
key=Callback(HomePageList,
tab=tab, category=t, base_url=url, type_title=type_title, art=art),
title=t))
return oc
####################################################################################################
@route(PREFIX + '/about')
def About():
"""
Return Resource Directory Size, and KissNetwork's Current Channel Version
Includes Developer Tools Menu if enabled within prefs and current user is admin
"""
oc = ObjectContainer(title2='About / Help')
# Get Resources Directory Size
d = GetDirSize(Core.storage.data_item_path(THUMB_CACHE_DIR))
if Prefs['devtools'] and CheckAdmin():
add_dev_tools(oc)
oc.add(DirectoryObject(key=Callback(About),
title='Version {}'.format(get_channel_version()), summary='Current Channel Version'))
oc.add(DirectoryObject(key=Callback(About),
title='N/A | Still Removing Files' if d == 'Error' else d,
summary='Number of Images Cached | Total Images Cached Size'))
return oc
####################################################################################################
def get_channel_version():
plist = Plist.ObjectFromString(Core.storage.load(Core.plist_path))
return plist['CFBundleVersion'] if 'CFBundleVersion' in plist.keys() else 'Current'
####################################################################################################
@route(PREFIX + '/validateprefs')
def ValidatePrefs():
"""check prefs, placeholder for now"""
####################################################################################################
@route(PREFIX + '/bookmarks', status=dict)
def BookmarksMain(title, status):
"""Create Bookmark Main Menu"""
if (status['bool']) and (Client.Platform not in ['Plex Home Theater', 'OpenPHT']):
oc = ObjectContainer(title2=title, header="My Bookmarks",
message='{} bookmarks have been cleared.'.format(status['type_title']), no_cache=True)
else:
oc = ObjectContainer(title2=title, no_cache=True)
# check for 'Bookmarks' section in Dict
if not Dict['Bookmarks']:
# if no 'Bookmarks' section the return pop up
return MC.message_container(title,
'No Bookmarks yet. Get out there and start adding some!!!')
# create boomark directory based on category
else:
key_list = sorted(Dict['Bookmarks'].keys())
# return bookmark list directly if only one kiss site selected in prefs
bm_prefs_names = [('kissasian' if m == 'Drama' else 'kiss{}'.format(m.lower())) for m in key_list]
bool_prefs_names = [p for p in bm_prefs_names if Prefs[p]]
if len(bool_prefs_names) == 1:
b_prefs_name = bool_prefs_names[0].split('kiss')[1].title()
b_prefs_name = 'Drama' if b_prefs_name == 'Asian' else b_prefs_name
if b_prefs_name in key_list:
art = 'art-{}.jpg'.format(b_prefs_name.lower())
return BookmarksSub(b_prefs_name, art)
# list categories in bookmarks dictionary that are selected in prefs
for key in key_list:
prefs_name = 'kissasian' if key == 'Drama' else 'kiss{}'.format(key.lower())
art = 'art-{}.jpg'.format(key.lower())
thumb = 'icon-{}.png'.format(key.lower())
# if site in Prefs then add its bookmark section
if Prefs[prefs_name]:
# Create sub Categories for Anime, Cartoon, Drama, and Manga
oc.add(DirectoryObject(
key=Callback(BookmarksSub, type_title=key, art=art),
title=key, thumb=R(thumb), summary='Display {} Bookmarks'.format(key), art=R(art)))
# test if no sites are picked in the Prefs
if len(oc) > 0:
# hide/unhide clear bookmarks option, from DevTools
if not Prefs['hide_clear_bookmarks']:
# add a way to clear the entire bookmarks list, i.e. start fresh
oc.add(DirectoryObject(
key=Callback(ClearBookmarks, type_title='All'),
title='Clear All Bookmarks?',
thumb=R(BOOKMARK_CLEAR_ICON), art=R(art),
summary='CAUTION! This will clear your entire bookmark list, even those hidden!'))
return oc
else:
# Give error message
return MC.message_container('Error',
'At least one source must be selected in Preferences to view Bookmarks')
####################################################################################################
@route(PREFIX + '/bookmarkssub')
def BookmarksSub(type_title, art):
"""Load Bookmarked items from Dict"""
if not type_title in Dict['Bookmarks'].keys():
return MC.message_container('Error',
'{} Bookmarks list is dirty. Use About/Help > Dev Tools > Bookmark Tools > Reset {} Bookmarks'.format(type_title, type_title))
oc = ObjectContainer(title2='My Bookmarks | {}'.format(type_title), art=R(art))
# Fill in DirectoryObject information from the bookmark list
# create empty list for testing covers
for bookmark in Util.ListSortedByKey(Dict['Bookmarks'][type_title], type_title):
item_title = bookmark['item_title']
summary = bookmark['summary']
summary2 = Common.StringCode(string=summary, code='decode') if summary else None
cover_file = Common.CorrectCoverImage(bookmark['cover_file']) if bookmark['cover_file'] else None
cover_url = Common.CorrectCoverImage(bookmark['cover_url']) if bookmark['cover_url'] else None
cover = None
if cover_file and cover_url:
cover = Callback(GetThumb, cover_url=cover_url, cover_file=cover_file)
item_info = {
'item_sys_name': bookmark[type_title],
'item_title': item_title,
'short_summary': summary,
'cover_url': cover_url,
'cover_file': cover_file,
'type_title': type_title,
'base_url': Common.GetBaseURL(bookmark['page_url']),
'page_url': Common.GetBaseURL(bookmark['page_url']) + '/' + bookmark['page_url'].split('/', 3)[3],
'art': art}
# get genre info, provide legacy support for older Bookmarks
# by updating
force_update_cover = False
if 'genres' in bookmark.keys():
genres = [g.replace('_', ' ') for g in bookmark['genres'].split()]
update = False
if cover_url and Common.is_kiss_url(cover_url):
cover_type_title = Common.GetTypeTitle(cover_url)
cover_base_url = Common.RE_BASE_URL.search(bookmark['cover_url']).group(1)
if 'date_added' not in bookmark.keys():
Log.Debug("* Bookmark 'date_added' missing. Updating Bookmark Metadata.")
update = True
force_update_cover = cover_type_title == 'Anime'
elif (cover_type_title, cover_base_url) not in Common.BaseURLListTuple():
Log.Debug('* Bookmark Cover URL Domain changed. Updating Bookmark Metadata.')
update = True
else:
page_base_url = Common.RE_BASE_URL.search(bookmark['page_url']).group(1)
if (type_title, page_base_url) not in Common.BaseURLListTuple():
Log.Debug('* Bookmark Page URL Domain changed. Updating Bookmark Metadata.')
update = True
if update:
bm_info = item_info.copy()
bm_info.update({'type_title': type_title, 'genres': bookmark['genres']})
if 'date_added' in bookmark.keys():
bm_info.update({'date_added': bookmark['date_added']})
ftimer = float(Util.RandomInt(0,30)) + Util.Random()
Thread.CreateTimer(interval=ftimer, f=UpdateLegacyBookmark, bm_info=bm_info, new_cover=force_update_cover)
else:
bm_info = item_info.copy()
bm_info.update({'type_title': type_title})
ftimer = float(Util.RandomInt(0,30)) + Util.Random()
Thread.CreateTimer(interval=ftimer, f=UpdateLegacyBookmark, bm_info=bm_info)
genres = ['Temp']
if not Prefs['adult']:
matching_list = set(genres) & ADULT_LIST
if len(matching_list) > 0:
continue
oc.add(DirectoryObject(
key=Callback(ItemPage, item_info=item_info),
title=Common.StringCode(string=item_title, code='decode'),
summary=summary2, thumb=cover, art=cover))
if not Prefs['hide_clear_bookmarks']:
# add a way to clear this bookmark section and start fresh
oc.add(DirectoryObject(
key=Callback(ClearBookmarks, type_title=type_title),
title='Clear All \"{}\" Bookmarks?'.format(type_title),
thumb=R(BOOKMARK_CLEAR_ICON), art=R(art),
summary='CAUTION! This will clear your entire \"{}\" bookmark section!'.format(type_title)))
return oc
####################################################################################################
@route(PREFIX + '/alphabets')
def AlphabetList(url, title, art):
"""Create ABC Directory for each kiss site"""
oc = ObjectContainer(title2='{} By #, A-Z'.format(title), art=R(art))
for pname in list('#'+String.UPPERCASE):
oc.add(DirectoryObject(
key=Callback(DirectoryList,
page=1, pname=pname.lower() if not pname == '#' else '0',
category=pname, base_url=url, type_title=title, art=art),
title=pname))
Logger('* Built #, A-Z... Directories')
return oc
####################################################################################################
@route(PREFIX + '/genres')
def GenreList(url, title, art):
"""Create Genre Directory for each kiss site"""
genre_url = url + '/{}List'.format(title)
html = RHTML.ElementFromURL(genre_url)
oc = ObjectContainer(title2='{} By Genres'.format(title), art=R(art))
# Generate Valid Genres based on Prefs['adult']
for genre in html.xpath('//div[@class="barContent"]//a'):
genre_href = genre.get('href')
if 'Genre' in genre_href and not 'Movie' in genre_href:
if (Prefs['adult'] == False) and (genre_href.replace('/Genre/', '') in ADULT_LIST):
continue
# name used for title2
category = html.xpath('//div[@class="barContent"]//a[@href="{}"]/text()'.format(genre_href))[0].replace('\n', '').strip()
oc.add(DirectoryObject(
key=Callback(DirectoryList,
page=1, pname=genre_href, category=category, base_url=url, type_title=title, art=art),
title=category))
return oc
####################################################################################################
@route(PREFIX + '/countries')
def CountryList(url, title, art):
"""Create Country Directory for KissAsian"""
country_url = url + '/DramaList' # setup url for finding current Country list
html = RHTML.ElementFromURL(country_url)
oc = ObjectContainer(title2='Drama By Country', art=R(art))
# For loop to pull out valid Countries
for country in html.xpath('//div[@class="barContent"]//a'):
if "Country" in country.get('href'):
pname = country.get('href') # name used internally
category = country.text.replace('\n', '').strip() # name used for title2
oc.add(DirectoryObject(
key=Callback(DirectoryList,
page=1, pname=pname, category=category, base_url=url, type_title=title, art=art),
title=category))
return oc
####################################################################################################
@route(PREFIX + '/directory')
def DirectoryList(page, pname, category, base_url, type_title, art):
"""
GenreList, AlphabetList, CountryList, and Search are sent here
Pulls out Items name and creates directories for them
Might to add section that detects if Genre is empty
"""
# Define url based on genre, abc, or search
if "Search" in pname:
item_url = base_url
Logger('* Searching for \"{}\"'.format(category))
# New & Hot list is only on Anime site, but made it uniform just in case
elif pname == '/NewAndHot':
item_url = base_url + '/{}List{}'.format(type_title, pname)
# list from the front page, not effected by Prefs
elif pname == '/LatestUpdate' or pname == '/Newest' or pname == '/MostPopular':
item_url = base_url + '/{}List{}?page={}'.format(type_title, pname, page)
# Sort order 'A-Z'
elif SORT_OPT[Prefs['sort_opt']] is None:
if ('Genre' in pname or 'Country' in pname
or 'Ongoing' in pname or 'Completed' in pname):
# Genre, Country, Ongoing, or Completed Specific
item_url = base_url + '{}?page={}'.format(pname, page)
elif "All" in pname:
# All list
item_url = base_url + '/{}List?page={}'.format(type_title, page)
else:
# No Genre, Country, Ongoing, or Completed
item_url = base_url + '/{}List?c={}&page={}'.format(type_title, pname, page)
# Sort order for all options except 'A-Z'
elif ('Genre' in pname or 'Country' in pname
or 'Ongoing' in pname or 'Completed' in pname):
# Specific with Prefs
item_url = base_url + '{}{}?page={}'.format(pname, SORT_OPT[Prefs['sort_opt']], page)
elif "All" in pname:
item_url = base_url + '/{}List{}?page={}'.format(type_title, SORT_OPT[Prefs['sort_opt']], page)
else:
# No Genre with Prefs
item_url = base_url + '/{}List{}?c={}&page={}'.format(type_title, SORT_OPT[Prefs['sort_opt']], pname, page)
Logger(u"* Sorting Option = '{}'".format(SORT_OPT[Prefs['sort_opt']])) # Log Pref being used
Logger(u"* Category = '{}' | URL = '{}'".format(pname, item_url))
html = RHTML.ElementFromURL(item_url)
pages = "Last Page"
nextpg_node = None
# determine if 'next page' is used in directory page
if "Search" in pname:
# The Search result page returnes a long list with no 'next page' option
# set url back to base url
base_url = Common.GetBaseURL(item_url)
Logger("* Searching for {}".format(category)) # check to make sure its searching
else:
# parse html for 'last' and 'next' page numbers
for node in html.xpath('///div[@class="pagination pagination-left"]//li/a'):
if "Last" in node.text:
pages = str(node.get('href')) # pull out last page if not on it
elif "Next" in node.text:
nextpg_node = str(node.get('href')) # pull out next page if exist
# Create title2 to include directory and page numbers
if not "Last" in pages:
total_pages = pages.split('page=')[1]
# set title2 ie main_title
main_title = '{} | {} | Page {} of {}'.format(type_title, category, page, total_pages)
elif "Search" in pname:
# set title2 for search page
main_title = 'Search for: {} in {}'.format(category, type_title)
else:
# set title2 for last page
main_title = '{} | {} | Page {}, Last Page'.format(type_title, category, page)
oc = ObjectContainer(title2=main_title, art=R(art))
# parse url for each Item and pull out its title, summary, and cover image
# took some time to figure out how to get the javascript info
listing = html.xpath('//table[@class="listing"]//td[@title]')
if not listing:
listing = html.xpath('//div[@class="item"]')
drama_test = type_title == 'Drama' and ('Search' not in pname)
listing_count = len(listing)
allowed_count = 200
Logger('* {} items in Directory List.'.format(listing_count), kind='Info')
if listing_count > allowed_count and 'Search' in pname:
return MC.message_container('Error',
'{} found. Directory can only list up to {} items. Please narrow your Search Criteria.'.format(listing_count, allowed_count))
for item in listing:
if not drama_test:
title_html = HTML.ElementFromString(item.get('title'))
else:
title_html = item
drama_title_html = HTML.ElementFromString(item.get('title'))
try:
if not drama_test:
thumb = Common.CorrectCoverImage(item.xpath('./a/img/@src')[0])
if 'http' not in thumb:
thumb = base_url + thumb
else:
thumb = Common.CorrectCoverImage(item.xpath('./a/img/@src')[0])
if not 'http' in thumb:
Log.Debug('* thumb missing valid url. | {}'.format(thumb))
Log.Debug('* thumb xpath = {}'.format(title_html.xpath('//img/@src')))
Log.Debug('* item name | {} | {}'.format(title_html.xpath('//a/@href'), title_html.xpath('//a/text()')))
thumb = None
cover_file = None
elif Common.is_kiss_url(thumb):
cover_file = thumb.rsplit('/')[-1]
else:
cover_file = thumb.split('/', 3)[3].replace('/', '_')
except Exception as e:
Log(e)
thumb = None
cover_file = None
if not drama_test:
summary = title_html.xpath('//p/text()')[0].strip()
else:
summary = drama_title_html.xpath('//p[@class="description"]/text()')[0].strip()
a_node = item.xpath('./a')[0]
item_url_base = a_node.get('href')
item_sys_name = Common.StringCode(string=item_url_base.rsplit('/')[-1].strip(), code='encode')
item_url_final = base_url + Common.StringCode(string=item_url_base, code='encode')
Logger('*' * 80)
Logger('* item_url_base = {}'.format(item_url_base))
Logger('* item_sys_name = {}'.format(item_sys_name))
Logger('* item_url_final = {}'.format(item_url_final))
Logger('* thumb = {}'.format(thumb))
item_title = None
try:
if not drama_test:
item_title = a_node.xpath('./span[@class="title"]/text()')[0].strip()
else:
item_title = a_node.xpath('./span[@class="title"]/text()')[0].strip()
except:
pass
item_title = item_title if item_title != None else item_sys_name
Logger('* item_title = {}'.format(item_title))
if 'Movie' in pname:
title2 = item_title
else:
item_title_cleaned = RE_TITLE_CLEAN.sub('', item_title)
try:
if not drama_test:
latest = item.xpath('./following-sibling::td')[0].text_content().strip().replace(item_title_cleaned, '')
else:
try:
latest = item.xpath('./div[@class="ep-bg"]/a')[0].text_content()
except:
latest = drama_title_html.xpath('./p')[1].text_content().split(' ')[1]
latest = latest.replace('Read Online', '').replace('Watch Online', '').lstrip('_').strip()
except:
latest = ''
Log("latest: %s" % latest)
if 'Completed' in latest:
title2 = u'{} | {} Completed'.format(item_title, type_title)
elif 'Not yet aired' in latest:
title2 = u'{} | Not Yet Aired'.format(item_title)
else:
title2 = u'{} | Latest {}'.format(item_title, latest)
item_info = {
'item_sys_name': item_sys_name,
'item_title': Common.StringCode(string=item_title, code='encode'),
'short_summary': Common.StringCode(string=summary, code='encode'),
'cover_url': thumb,
'cover_file': cover_file,
'type_title': type_title,
'base_url': base_url,
'page_url': item_url_final,
'art': art
}
# if thumb is hosted on kiss site then cache locally if Prefs Cache all covers
cover = Callback(GetThumb, cover_url=thumb, cover_file=cover_file)
oc.add(DirectoryObject(
key=Callback(ItemPage, item_info=item_info),
title=title2, summary=summary, thumb=cover, art=cover))
if nextpg_node: # if not 'None' then find the next page and create a button
nextpg = int(nextpg_node.split('page=')[1])
Logger('* NextPage = {}'.format(nextpg))
Logger('* base url = {}'.format(base_url))
oc.add(NextPageObject(
key=Callback(DirectoryList,
page=nextpg, pname=pname, category=category,
base_url=base_url, type_title=type_title, art=art),
title='Next Page>>', thumb=R(NEXT_ICON)))
if len(oc) > 0:
Dict.Save()
return oc
return MC.message_container(type_title, '{} list is empty'.format(category))
####################################################################################################
@route(PREFIX + '/homedirectorylist')
def HomePageList(tab, category, base_url, type_title, art):
"""
KissCartoon, KissAsian, and ReadComicOnline have 'Top' list on home page.
This returns those list.
"""
main_title = u'{} | {}'.format(type_title, category)
oc = ObjectContainer(title2=main_title, art=R(art))
html = RHTML.ElementFromURL(base_url)
# scrape home page for Top (Day, Week, and Month) list
for node in html.xpath('//div[@id="tab-top-{}"]/div'.format(tab)):
page_node = Common.StringCode(string=node.xpath('./a')[1].get('href'), code='encode')
item_sys_name = Common.StringCode(string=page_node.split('/')[-1], code='encode')
item_title = node.xpath('./a/span/text()')[0]
latest = node.xpath('./p/span[@class="info"][text()="Latest:"]/../a/text()')[0]
title2 = u'{} | Latest {}'.format(item_title, latest)
summary = 'NA' # no summarys are given in the 'Top' lists
try:
thumb = Common.CorrectCoverImage(node.xpath('./a/img/@src')[0].get('src'))
if not 'http' in thumb:
thumb = None
cover_file = None
elif Common.is_kiss_url(thumb):
cover_file = thumb.rsplit('/')[-1]
else:
cover_file = thumb.split('/', 3)[3].replace('/', '_')
except:
thumb = None
cover_file = None
page_url = base_url + (page_node if page_node.startswith('/') else '/' + page_node)
item_info = {
'item_sys_name': item_sys_name,
'item_title': Common.StringCode(string=item_title, code='encode'),
'short_summary': summary,
'cover_url': thumb,
'cover_file': cover_file,
'type_title': type_title,
'base_url': base_url,
'page_url': page_url,
'art': art
}
cover = Callback(GetThumb, cover_url=thumb, cover_file=cover_file)
# send results to ItemPage
oc.add(DirectoryObject(
key=Callback(ItemPage, item_info=item_info), title=title2, thumb=cover, art=cover))
Dict.Save()
return oc
####################################################################################################
@route(PREFIX + '/item', item_info=dict)
def ItemPage(item_info):
"""Create the Media Page with the Video(s)/Chapter(s) section and a Bookmark option Add/Remove"""
# set variables
item_sys_name = item_info['item_sys_name']
item_title = item_info['item_title']
type_title = item_info['type_title']
base_url = item_info['base_url']
page_url = item_info['page_url']
art = item_info['art']
# decode string & set title2 for oc
item_title_decode = unicode(Common.StringCode(string=item_title, code='decode'))
title2 = u'{} | {}'.format(type_title, item_title_decode)
oc = ObjectContainer(title2=title2, art=R(art))
html = RHTML.ElementFromURL(page_url)
genres, genres_list = Metadata.GetGenres(html)
if not Prefs['adult']:
# Check for Adult content, block if Prefs set.
genres = html.xpath('//p[span[@class="info"]="Genres:"]/a/text()')
Logger('* genres = {}'.format(genres))
if genres:
matching_list = set(genres) & ADULT_LIST
if len(matching_list) > 0:
warning_string = ', '.join(list(matching_list))
Logger('* Adult Content Blocked: {}'.format(warning_string), force=True, kind='Info')
Logger('*' * 80)
return MC.message_container('Warning',
'Adult Content Blocked: {}'.format(warning_string))
# page category stings depending on media
page_category = 'Chapter(s)' if (type_title == 'Manga' or type_title == 'Comic') else 'Video(s)'
# update item_info to include page_category
item_info.update({'page_category': page_category})
# format item_url for parsing
Logger('* page url = {}'.format(page_url))
Logger('* base url = {}'.format(base_url))
Logger('*' * 80)
if not item_info['cover_url']:
try:
cover_url = Common.CorrectCoverImage(html.xpath('//head/link[@rel="image_src"]')[0].get('href'))
if Common.is_kiss_url(cover_url):
content_url = Common.GetBaseURL(cover_url) + '/' + cover_url.split('/', 3)[3]
image_file = content_url.rsplit('/')[-1]
else:
content_url = cover_url
image_file = cover_url.split('/', 3)[3].replace('/', '_')
item_info.update({'cover_url': content_url, 'cover_file': image_file})
except:
pass
cover = Callback(GetThumb, cover_url=item_info['cover_url'], cover_file=item_info['cover_file'])
if ('Manga' in type_title) or ('Comic' in type_title):
manga_info = Metadata.GetBaseMangaInfo(html, page_url)
summary = manga_info['summary'] if manga_info['summary'] else (item_info['short_summary'] if item_info['short_summary'] else None)
item_info.update({'summary': summary})
item_info.pop('short_summary')
manga_info.pop('summary')
summary2 = Common.StringCode(string=summary, code='decode')
oc.add(TVShowObject(
key=Callback(MangaSubPage, item_info=item_info, manga_info=manga_info),
rating_key=page_url, title=manga_info['title'], genres=genres,
source_title=manga_info['source_title'], summary=unicode(summary2),
thumb=cover, art=R(art)
))
elif 'Movie' in genres:
movie_info = Metadata.GetBaseMovieInfo(html, page_url)
summary = movie_info['summary'] if movie_info['summary'] else (item_info['short_summary'] if item_info['short_summary'] else None)
item_info.update({'summary': summary})
item_info.pop('short_summary')
movie_info.pop('summary')
summary2 = Common.StringCode(string=summary, code='decode')
oc.add(TVShowObject(
key=Callback(MovieSubPage, item_info=item_info, movie_info=movie_info),
rating_key=page_url, title=movie_info['title'], genres=genres,
source_title=movie_info['source_title'], summary=unicode(summary2),
thumb=cover, art=R(art)
))
else:
show_info = Metadata.GetBaseShowInfo(html, page_url)
summary = show_info['summary'] if show_info['summary'] else (item_info['short_summary'] if item_info['short_summary'] else None)
item_info.update({'summary': summary})
item_info.pop('short_summary')
show_info.pop('summary')
summary2 = Common.StringCode(string=summary, code='decode')
oc.add(TVShowObject(
key=Callback(ShowSubPage, item_info=item_info, show_info=show_info),
rating_key=page_url, title=show_info['tv_show_name'], genres=genres,
source_title=show_info['source_title'], summary=unicode(summary2),
thumb=cover, art=R(art)
))
# Setup related links
related = []
if type_title == 'Comic':
jdata = JSON.ObjectFromURL(
base_url + '/GetRelatedLinks', method='POST', cacheTime=CACHE_1HOUR,
values={'keyword': page_url.split('/')[-1].replace('-', '+')},
headers=Headers.get_headers_for_url(base_url)
)
for jd in jdata:
rel_title = jd['Name']
rel_url = jd['Link']
rel_item_info = {
'item_sys_name': Common.StringCode(string=rel_url.split('/')[-1], code='encode'),
'item_title': Common.StringCode(string=rel_title, code='encode'),
'short_summary': 'NA', 'cover_url': "", 'cover_file': "",
'type_title': type_title, 'base_url': base_url, 'page_url': rel_url, 'art': art
}
related.append(rel_item_info)
else:
for rel in html.xpath('//a[starts-with(@href, "/{}/")]'.format(type_title)):
hrel = rel.get('href')
if (len(hrel.split('/')) == 3) and (hrel != '/'+page_url.split('/', 3)[3]):
rel_title = rel.text_content().strip()
rel_item_info = {
'item_sys_name': Common.StringCode(string=hrel.split('/')[-1], code='encode'),
'item_title': Common.StringCode(string=rel_title, code='encode'),
'short_summary': 'NA', 'cover_url': "", 'cover_file': "",
'type_title': type_title, 'base_url': base_url, 'page_url': base_url + hrel, 'art': art
}
related.append(rel_item_info)
if related:
oc.add(DirectoryObject(
key=Callback(RelatedList, r_list=related, title=item_title_decode, art=art),
title='Related Links', thumb=R('icon-related.png'), art=R(art)))
# Test if the Dict does have the 'Bookmarks' section
bm = Dict['Bookmarks']
if ((True if [b[type_title] for b in bm[type_title] if b[type_title] == item_sys_name] else False) if type_title in bm.keys() else False) if bm else False:
# provide a way to remove Item from bookmarks list
oc.add(DirectoryObject(
key=Callback(RemoveBookmark, item_info=item_info),
title='Remove Bookmark', thumb=R(BOOKMARK_REMOVE_ICON),
summary=u'Remove \"{}\" from your Bookmarks list.'.format(item_title_decode)))
else:
# Item not in 'Bookmarks' yet, so lets parse it for adding!