forked from Xycl/plugin.image.mypicsdb2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdefault.py
executable file
·2256 lines (1972 loc) · 108 KB
/
default.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
__addonname__ = 'plugin.image.mypicsdb2'
import mypicsdb.viewer as viewer
import mypicsdb.translationeditor as translationeditor
import mypicsdb.googlemaps as googlemaps
import mypicsdb.filterwizard as filterwizard
import mypicsdb.MypicsDB as MypicsDB
# common depends on __addonname__
import mypicsdb.common as common
import resources.lib.utils as utils
import os
import sys
import time
import re
import urllib
from os.path import join, isfile, basename, dirname
from urllib.parse import parse_qsl, unquote, quote
from collections import defaultdict
from time import strftime, strptime
from traceback import print_exc
import xbmc
import xbmcplugin
import xbmcgui
import xbmcaddon
import xbmcvfs
# MikeBZH44
try:
import json as simplejson
# test json has not loads, call error
if not hasattr(simplejson, "loads"):
raise Exception("Hmmm! Error with json %r" % dir(simplejson))
except Exception as e:
print("[MyPicsDB] %s" % str(e))
import simplejson
# MikeBZH44: commoncache for MyPicsDB with 1 hour timeout
try:
import mypicsdb.StorageServer as StorageServer
except:
import mypicsdb.storageserverdummy as StorageServer
# set variables used by other modules
sys_encoding = sys.getfilesystemencoding()
if "MypicsDB" in sys.modules:
del sys.modules["MypicsDB"]
# these few lines are taken from AppleMovieTrailers script
# Shared resources
HOME = common.getaddon_path()
BASE_RESOURCE_PATH = join(HOME, "resources")
DATA_PATH = common.getaddon_info('profile')
PIC_PATH = join(BASE_RESOURCE_PATH, "images")
# catching the OS :
# win32 -> win
# darwin -> mac
# linux -> linux
RunningOS = sys.platform
cache = StorageServer.StorageServer("MyPicsDB", 1)
files_fields_description = {
"strFilename": common.getstring(30300),
"strPath": common.getstring(30301),
"Thumb": common.getstring(30302),
}
global MPDB
class Main:
def __init__(self):
try:
MPDB = MypicsDB.MyPictureDB()
except Exception as msg:
common.log("Main.__init__", "%s - %s" % (Exception, str(msg)), xbmc.LOGERROR)
raise msg
common.log("Main.get_args", 'MyPicturesDB plugin called with "%s".' % sys.argv[2][1:])
self.parm = self.get_args()
self.args = defaultdict(str)
self.args.update(parse_qsl(self.parm))
@staticmethod
def get_args():
parm = unquote(sys.argv[2]).replace("\\\\", "\\")
# change for ruuk's plugin screensaver
parm = parm.replace('&plugin_slideshow_ss=true', '')
# for peppe_sr due to his used skin widget plugin
p = re.compile('&reload=[^&]*')
parm = p.sub('', parm)
return parm[1:]
def add_directory(self, name, params, action, iconimage=None, fanart=None,
contextmenu=None, total=0, info="*", replacemenu=True, path=None):
try:
try:
parameter = "&".join([param + "=" + common.quote_param(valeur) for param, valeur in params])
except Exception as msg:
common.log("Main.add_directory", "%s - %s" % (Exception, str(msg)), xbmc.LOGERROR)
parameter = ""
if path:
# By using path instead of plugin call, kodi will generate a thumbnail with 4 pics in the folder.
u = path
else:
u = sys.argv[0] + "?" + parameter + "&action=" + action + "&name=" + common.quote_param(name)
liz = xbmcgui.ListItem(label=name)
liz.setProperty("mypicsdb", "True")
if iconimage:
liz.setArt({'thumb': iconimage})
if fanart:
liz.setArt({'fanart': fanart})
if contextmenu:
liz.addContextMenuItems(contextmenu)
return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=True)
except Exception as msg:
common.log("Main.add_directory", "%s - %s" % (Exception, str(msg)), xbmc.LOGERROR)
pass
def add_action(self, name, params, action, iconimage, fanart=None,
contextmenu=None, total=0, info="*", replacemenu=True):
try:
try:
parameter = "&".join([param + "=" + common.quote_param(valeur) for param, valeur in params])
except Exception as msg:
common.log("Main.add_action", "%s - %s" % (Exception, str(msg)), xbmc.LOGERROR)
parameter = ""
u = sys.argv[0] + "?" + parameter + "&action=" + action + "&name=" + common.quote_param(name)
liz = xbmcgui.ListItem(label=name)
liz.setArt({'thumb': iconimage})
if contextmenu:
liz.addContextMenuItems(contextmenu)
return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=False)
except Exception as msg:
common.log("Main.add_action", "%s - %s" % (Exception, str(msg)), xbmc.LOGERROR)
pass
def add_picture(self, picname, picpath, count=0, info="*", fanart=None, contextmenu=None, replacemenu=True):
suffix = ""
rating = ""
coords = None
date = None
try:
fullfilepath = join(picpath, picname)
common.log("Main.add_picture", "Name = %s" % fullfilepath)
liz = xbmcgui.ListItem(picname, info)
try:
# type(exiftime) == datetime.datetime, type(rating) == str
(exiftime, rating) = MPDB.get_pic_date_rating(picpath, picname)
date = exiftime.strftime("%Y.%m.%d") if exiftime else ""
except Exception as msg:
common.log("Main.add_picture", "%s - %s" % (Exception, msg), xbmc.LOGERROR)
# is the file a video ?
if utils.is_video(picname):
infolabels = {"date": date}
liz.setInfo(type="video", infoLabels=infolabels)
# or is the file a picture ?
elif utils.is_picture(picname):
ratingmini = int(common.getaddon_setting("ratingmini"))
if ratingmini > 0:
if not rating or int(rating) < ratingmini:
return
coords = MPDB.get_gps(picpath, picname)
if coords:
suffix = suffix + "[COLOR=C0C0C0C0][G][/COLOR]"
_query = """
select coalesce(tc.TagContent,0), tt.TagType
from TagTypes tt, TagContents tc, TagsInFiles tif, Files fi
where tt.TagType in ( 'EXIF ExifImageLength', 'EXIF ExifImageWidth' )
and tt.idTagType = tc.idTagType
and tc.idTagContent = tif.idTagContent
and tif.idFile = fi.idFile
and fi.strPath = ?
and fi.strFilename = ?
"""
resolutionXY = MPDB.cur.request(_query, (picpath, picname))
if not date:
infolabels = {"picturepath": picname + " " + suffix, "count": count}
else:
infolabels = {"picturepath": picname + " " + suffix, "date": date, "count": count}
try:
if exiftime:
common.log("Main.add_picture", "Picture has EXIF Date/Time %s" % exiftime)
infolabels["exif:exiftime"] = date
except:
pass
try:
if "Width" in resolutionXY[0][1]:
resolutionX = resolutionXY[0][0]
resolutionY = resolutionXY[1][0]
else:
resolutionX = resolutionXY[1][0]
resolutionY = resolutionXY[0][0]
if resolutionX != None and resolutionY != None and resolutionX != "0" and resolutionY != "0":
common.log("Main.add_picture",
"Picture has resolution %s x %s" % (str(resolutionX), str(resolutionY)))
infolabels["exif:resolution"] = str(resolutionX) + ',' + str(resolutionY)
except:
pass
if int(rating) > 0:
common.log("Main.add_picture", "Picture has rating: %s" % rating)
suffix = suffix + "[COLOR=C0FFFF00]" + ("*" * int(rating)) + "[/COLOR]" + \
"[COLOR=C0C0C0C0]" + ("*" * (5 - int(rating))) + "[/COLOR]"
persons = MPDB.get_pic_persons(picpath, picname)
liz.setProperty('mypicsdb_person', persons)
liz.setInfo(type="pictures", infoLabels=infolabels)
liz.setProperty("mypicsdb", "True")
liz.setLabel(picname + " " + suffix)
if fanart:
liz.setArt({'fanart': fanart})
liz.setProperty('fanart_image', fanart)
if contextmenu:
# if coords:
# common.log("Main.add_picture", "Picture has geolocation", xbmc.LOGINFO)
# contextmenu.append((common.getstring(30220),\
# "RunPlugin(\"%s?action='geolocate'&place='%s'&path='%s'&filename='%s'&viewmode='view'\",)" %\
# (sys.argv[0],"%0.6f,%0.6f" % (coords))
liz.addContextMenuItems(contextmenu)
return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=fullfilepath, listitem=liz, isFolder=False)
except Exception as msg:
common.log("", "%s - %s" % (Exception, msg), xbmc.LOGERROR)
def change_view(self):
view_modes = {
'skin.confluence': 500,
'skin.aeon.nox': 551,
'skin.confluence-vertical': 500,
'skin.jx720': 52,
'skin.pm3-hd': 53,
'skin.rapier': 50,
'skin.simplicity': 500,
'skin.slik': 53,
'skin.touched': 500,
'skin.transparency': 53,
'skin.xeebo': 55,
}
skin_dir = xbmc.getSkinDir()
if skin_dir in view_modes:
xbmc.executebuiltin('Container.SetViewMode(' + str(view_modes[skin_dir]) + ')')
def show_home(self):
display_all = common.getaddon_setting('m_all') == 'true'
# last scan picture added
if common.getaddon_setting('m_1') == 'true' or display_all:
name = common.getstring(30209) % common.getaddon_setting("recentnbdays")
params = [("method", "recentpicsdb"), ("period", ""), ("value", ""),
("page", "1"), ("viewmode", "view")]
iconimage = join(PIC_PATH, "folder_recent_added.png")
self.add_directory(name, params, "showpics", iconimage)
# Last pictures
if common.getaddon_setting('m_2') == 'true' or display_all:
name = common.getstring(30130) % common.getaddon_setting("lastpicsnumber")
params = [("method", "lastpicsshooted"), ("page", "1"), ("viewmode", "view")]
iconimage = join(PIC_PATH, "folder_recent_shot.png")
self.add_directory(name, params, "showpics", iconimage)
# N random pictures
if common.getaddon_setting('m_13') == 'true' or display_all:
name = common.getstring(30654) % common.getaddon_setting("randompicsnumber")
params = [("method", "random"), ("page", "1"), ("viewmode", "view"), ("onlypics", "oui")]
iconimage = join(PIC_PATH, "folder_random.png")
self.add_directory(name, params, "showpics", iconimage)
# videos
if common.getaddon_setting('m_3') == 'true' or display_all and common.getaddon_setting("usevids") == "true":
name = common.getstring(30051)
params = [("method", "videos"), ("page", "1"), ("viewmode", "view")]
iconimage = join(PIC_PATH, "folder_videos.png")
self.add_directory(name, params, "showpics", iconimage)
# Saved filter wizard settings
self.add_directory(common.getstring(30655),
[("wizard", "settings"), ("viewmode", "view")],
"showwizard",
join(PIC_PATH, "folder_wizard.png"))
# show filter wizard
self.add_action(common.getstring(30600),
[("wizard", "dialog"), ("viewmode", "view")],
"showwizard",
join(PIC_PATH, "folder_wizard.png"))
# Browse by Date
if common.getaddon_setting('m_4') == 'true' or display_all:
name = common.getstring(30101)
params = [("period", "year"), ("value", ""), ("viewmode", "view")]
iconimage = join(PIC_PATH, "folder_date.png")
self.add_directory(name, params, "showdate", iconimage)
# Browse by Folders
if common.getaddon_setting('m_5') == 'true' or display_all:
name = common.getstring(30102)
params = [("method", "folders"), ("folderid", "all"), ("onlypics", "non"), ("viewmode", "view")]
iconimage = join(PIC_PATH, "folder_pictures.png")
self.add_directory(name, params, "showfolder", iconimage)
# Browse by root folders only
if common.getaddon_setting('m_6') == 'true' or display_all:
name = common.getstring(30103)
params = [("method", "folders"), ("folderid", "root"), ("onlypics", "non"), ("viewmode", "view")]
iconimage = join(PIC_PATH, "folder_pictures.png")
self.add_directory(name, params, "showfolder", iconimage)
# Browse by child folders only
if common.getaddon_setting('m_7') == 'true' or display_all:
name = common.getstring(30104)
params = [("method", "folders"), ("folderid", "child"), ("onlypics", "non"), ("viewmode", "view")]
iconimage = join(PIC_PATH, "folder_pictures.png")
self.add_directory(name, params, "showfolder", iconimage)
# Browse by Tags
if common.getaddon_setting('m_14') == 'true' or display_all:
name = common.getstring(30122)
params = [("tags", ""), ("viewmode", "view")]
iconimage = join(PIC_PATH, "folder_tags.png")
self.add_directory(name, params, "showtagtypes", iconimage)
# Periods
if common.getaddon_setting('m_10') == 'true' or display_all:
name = common.getstring(30105)
params = [("period", ""), ("viewmode", "view")]
iconimage = join(PIC_PATH, "folder_date_ranges.png")
self.add_directory(name, params, "showperiod", iconimage)
# Collections
if common.getaddon_setting('m_11') == 'true' or display_all:
name = common.getstring(30150)
params = [("collect", ""), ("method", "show"), ("viewmode", "view"),
("usercollection", "")]
iconimage = join(PIC_PATH, "folder_collections.png")
self.add_directory(name, params, "showcollection", iconimage)
# User Collections Only
if common.getaddon_setting('m_11') == 'true' or display_all:
name = common.getstring(30670)
params = [("collect", ""), ("method", "show"), ("viewmode", "view"),
("usercollection", "1")]
iconimage = join(PIC_PATH, "folder_collections.png")
self.add_directory(name, params, "showcollection", iconimage)
# Global search
if common.getaddon_setting('m_12') == 'true' or display_all:
name = common.getstring(30098)
params = [("searchterm", ""), ("viewmode", "view")]
iconimage = join(PIC_PATH, "folder_search.png")
self.add_directory(name, params, "globalsearch", iconimage)
# picture sources
self.add_directory(common.getstring(30099),
[("do", "showroots"), ("viewmode", "view")],
"rootfolders",
join(PIC_PATH, "folder_paths.png"))
# Settings
self.add_action(common.getstring(30009),
[("showsettings", ""), ("viewmode", "view")],
"showsettings",
join(PIC_PATH, "folder_settings.png"))
# Translation Editor
self.add_action(common.getstring(30620),
[("showtranslationeditor", ""),
("viewmode", "view")],
"showtranslationeditor",
join(PIC_PATH, "folder_translate.png"))
# Show readme
self.add_action(common.getstring(30123),
[("help", ""), ("viewmode", "view")],
"help",
join(PIC_PATH, "folder_help.png"))
xbmcplugin.addSortMethod(
int(sys.argv[1]), xbmcplugin.SORT_METHOD_UNSORTED)
# xbmcplugin.setPluginCategory(handle=int(sys.argv[1]), \
# category=unquote("My Pictures Library".encode("utf-8")))
xbmcplugin.endOfDirectory(int(sys.argv[1]), cacheToDisc=True)
def show_date(self):
if int(common.getaddon_setting("ratingmini")) > 0:
min_rating = int(common.getaddon_setting("ratingmini"))
else:
min_rating = 0
# period = year|month|date
# value = "2009"|"12/2009"|"25/12/2009"
common.log("Main.show_date", "start")
action = "showdate"
monthname = common.getstring(30006).split("|")
fullmonthname = common.getstring(30008).split("|")
if self.args['period'] == "year":
common.log("Main.show_date", "period=year")
listperiod = MPDB.get_years(min_rating)
nextperiod = "month"
allperiod = ""
action = "showdate"
periodformat = "%Y"
displaydate = common.getstring(30004) # %Y
thisdateformat = ""
displaythisdate = ""
elif self.args['period'] == "month":
common.log("Main.show_date", "period=month")
listperiod = MPDB.get_months(self.args['value'], min_rating)
nextperiod = "date"
allperiod = "year"
action = "showdate"
periodformat = "%Y-%m"
displaydate = common.getstring(30003) # %b %Y
thisdateformat = "%Y"
displaythisdate = common.getstring(30004) # %Y
elif self.args['period'] == "date":
common.log("Main.show_date", "period=date")
listperiod = MPDB.get_dates(self.args['value'], min_rating)
nextperiod = "date"
allperiod = "month"
action = "showpics"
periodformat = "%Y-%m-%d"
displaydate = common.getstring(30002) # "%a %d %b %Y"
thisdateformat = "%Y-%m"
displaythisdate = common.getstring(30003) # "%b %Y"
else:
common.log("Main.show_date", "period=empty")
listperiod = []
nextperiod = None
# if not None in listperiod:
dptd = displaythisdate
# replace %b marker by short month name
dptd = dptd.replace("%b", monthname[strptime(self.args['value'], thisdateformat).tm_mon - 1])
# replace %B marker by long month name
dptd = dptd.replace("%B", fullmonthname[strptime(self.args['value'], thisdateformat).tm_mon - 1])
nameperiode = strftime(dptd, strptime(self.args['value'], thisdateformat))
common.log("", "dptd = " + dptd)
common.log("", "nameperiode = " + nameperiode)
common.log("", "allperiod = " + allperiod)
count = MPDB.count_pics_in_period(allperiod, self.args['value'], min_rating)
if count > 0:
self.add_directory(name=common.getstring(30100) % (nameperiode, count),
params=[("method", "date"), ("period", allperiod), ("value", self.args['value']),
("page", ""), ("viewmode", "view")],
action="showpics",
iconimage=join(PIC_PATH, "folder_date.png"),
contextmenu=[(common.getstring(30152),
"RunPlugin(\"%s?" % (sys.argv[0]) +
"action=addfolder&method=date&period=%s&value=%s&viewmode=scan\")" % \
(allperiod, self.args['value'])), ]
)
count = MPDB.count_pics_wo_imagedatetime(
allperiod, self.args['value'], min_rating)
if count > 0 and self.args['period'] == "year":
self.add_directory(name=common.getstring(30054) % (count),
params=[("method", "date"), ("period", "wo"), ("value", self.args['value']),
("page", ""), ("viewmode", "view")],
# paramètres
action="showpics", # action
iconimage=join(
PIC_PATH, "folder_date.png"), # icone
contextmenu=[(common.getstring(30152),
"RunPlugin(\"%s?" % ( sys.argv[0]) +
"action=addfolder&method=date&period=%s&value=%s&viewmode=scan\")" % \
(allperiod, self.args['value'])), ])
total = len(listperiod)
for period in listperiod:
if period:
if action == "showpics":
context = [(common.getstring(30152),
"RunPlugin(\"%s?" % (sys.argv[0]) +
"action=addfolder&method=date&period=%s&value=%s&viewmode=scan\")" % \
(nextperiod, period)), ]
else:
context = [(common.getstring(30152),
"RunPlugin(\"%s?" % (sys.argv[0]) +
"action=addfolder&method=date&period=%s&value=%s&viewmode=scan\")" % \
(self.args['period'], period)), ]
try:
dateformat = strptime(period, periodformat)
self.add_directory(
name="%s (%s %s)" % (strftime(self.prettydate(displaydate, dateformat), dateformat),
MPDB.count_pics_in_period(
self.args['period'], period, min_rating),
common.getstring(30050)), # libellé
params=[("method", "date"), ("period", nextperiod),
("value", period), ("viewmode", "view")], # paramètres
action=action, # action
iconimage=join(PIC_PATH, "folder_date.png"), # icone
contextmenu=context, # menucontextuel
total=total) # nb total d'éléments
except:
pass
xbmcplugin.addSortMethod(
int(sys.argv[1]), xbmcplugin.SORT_METHOD_UNSORTED)
xbmcplugin.endOfDirectory(int(sys.argv[1]))
def show_folders(self):
common.log("Main.show_folders", "start")
if int(common.getaddon_setting("ratingmini")) > 0:
min_rating = int(common.getaddon_setting("ratingmini"))
else:
min_rating = 0
if self.args['folderid'] == 'all': # get all folders
childrenfolders = [row for row in MPDB.cur.request(
"SELECT idFolder,FolderName FROM Folders")]
elif self.args['folderid'] == 'root': # get root folders
childrenfolders = [row for row in MPDB.cur.request(
"SELECT idFolder,FolderName FROM Folders WHERE ParentFolder is null")]
elif self.args['folderid'] == 'child': # get child folders
childrenfolders = [row for row in MPDB.cur.request(
"SELECT idFolder,FolderName FROM Folders WHERE ParentFolder is NOT null")]
else: # else, get subfolders for given folder Id
childrenfolders = [row for row in MPDB.cur.request_with_binds(
"SELECT idFolder,FolderName FROM Folders WHERE ParentFolder=?", (self.args['folderid'],))]
# show folders in the folder
for idchildren, childrenfolder in childrenfolders:
common.log("Main.show_folders", "children folder = %s" % childrenfolder)
path = MPDB.cur.request_with_binds(
"SELECT FullPath FROM Folders WHERE idFolder = ?", (idchildren,))[0][0]
# path should end with os.sep to use kodi's folder thumbnails as is
if not path.endswith(os.sep):
path = path + os.sep
count = MPDB.count_pics_in_folder(idchildren, min_rating)
if count > 0:
name="%s (%s %s)" % (childrenfolder, count, common.getstring(30050))
params=[("method", "folders"), ("folderid", str(idchildren)),
("onlypics", "non"), ("viewmode", "view")]
contextmenu=[(common.getstring(30212), # Exclude this folder from database
"Container.Update(\"%s?" % (sys.argv[0]) +
"action=rootfolders&do=addrootfolder&addpath=%s&exclude=1&viewmode=view\",)" % \
(common.quote_param(path))),
(common.getstring(30152), # Add to collection
"RunPlugin(\"%s?" % (sys.argv[0]) +
"action=addfolder&method=folders&viewmode=scan&folderid=%s\")" % \
(common.quote_param(str(idchildren))))]
thumb = utils.find_folder_thumb(path)
self.add_directory(name=name,
params=params,
action="showfolder",
iconimage=thumb,
contextmenu=contextmenu,
total=len(childrenfolders),
path=path)
# Now show pictures in the folder
# maintenant, on liste les photos si il y en a, du dossier en cours
if min_rating > 0:
_query = """
SELECT p.FullPath, f.strFilename
FROM Files f, Folders p
WHERE f.idFolder=p.idFolder AND f.idFolder=? AND f.ImageRating > ?
Order by f.imagedatetime
"""
picsfromfolder = [row for row in MPDB.cur.request_with_binds(
_query, (self.args['folderid'], min_rating,))]
else:
_query = """
SELECT p.FullPath, f.strFilename
FROM Files f, Folders p
WHERE f.idFolder=p.idFolder AND f.idFolder=?
Order by f.imagedatetime
"""
picsfromfolder = [row for row in MPDB.cur.request_with_binds(
_query, (self.args['folderid'],))]
# show pictures in the folder
count = 0
# context.append((common.getstring(30303),"SlideShow(%s%s,recursive,notrandom)"%(sys.argv[0], self.parm)))
for path, filename in picsfromfolder:
common.log("Main.show_folders", "pic's path = %s pic's name = %s" % (path, filename))
count = count + 1
context = [(common.getstring(30152), # Add to collection
"RunPlugin(\"%s?" % (sys.argv[0]) +
"action=addtocollection&viewmode=view&path=%s&filename=%s\")" % \
(common.quote_param(path), common.quote_param(filename)))]
self.add_picture(filename, path, count=count, contextmenu=context,
fanart=utils.find_fanart(path, filename))
xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_LABEL)
xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_DATE)
xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_PROGRAM_COUNT)
self.change_view()
xbmcplugin.endOfDirectory(int(sys.argv[1]))
def show_translationeditor(self):
ui = translationeditor.TranslationEditor("script-mypicsdb-translationeditor.xml",
common.getaddon_path(), "Default")
ui.doModal()
del ui
def show_map(self):
"""get a google map for the given place
place is a string for an address, or a couple of gps lat/lon data
"""
common.log("Main.show_map", "Start")
try:
path = self.args['path']
filename = self.args['filename']
joined = join(path, filename)
except:
common.log("Main.show_map", "Error with parameter", xbmc.LOGERROR)
return
common.log("Main.show_map", "Open Dialog")
ui = googlemaps.GoogleMap(
"script-mypicsdb-googlemaps.xml", common.getaddon_path(), "Default")
ui.set_file(joined)
ui.set_place(self.args['place'])
ui.set_datapath(DATA_PATH)
ui.doModal()
del ui
common.log("Main.show_map", "Close Dialog")
def show_help(self):
viewer.Viewer()
def show_settings(self):
xbmcaddon.Addon().openSettings()
def show_wizard(self):
if self.args['wizard'] == 'dialog':
global GlobalFilterTrue, GlobalFilterFalse, GlobalMatchAll, g_start_date, g_end_date
common.log("Main.show_wizard", "Show Dialog")
ui = filterwizard.FilterWizard(
"script-mypicsdb-filterwizard.xml", common.getaddon_path(), "Default")
ui.set_delegate(filterwizard_delegate)
ui.doModal()
del ui
common.log("Main.show_wizard", "Delete Dialog")
newtagtrue = ""
newtagfalse = ""
matchall = GlobalMatchAll
start_date = g_start_date
end_date = g_end_date
if len(GlobalFilterTrue) > 0:
for tag in GlobalFilterTrue:
if len(newtagtrue) == 0:
newtagtrue = tag
else:
newtagtrue += "|||" + tag
common.log("Main.show_wizard", newtagtrue)
if len(GlobalFilterFalse) > 0:
for tag in GlobalFilterFalse:
if len(newtagfalse) == 0:
newtagfalse = tag
else:
newtagfalse += "|||" + tag
if len(GlobalFilterTrue) > 0 or len(GlobalFilterFalse) > 0 or start_date != '' or end_date != '':
xbmc.executebuiltin("Container.Update(%s?" % (sys.argv[0]) +
"action=showpics&viewmode=view&method=wizard&matchall=%s&kw=%s&nkw=%s&start=%s&end=%s)" %\
(matchall, common.quote_param(newtagtrue), common.quote_param(newtagfalse),
start_date, end_date))
elif self.args['wizard'] == 'settings':
filterlist = MPDB.filterwizard_list_filters()
total = len(filterlist)
for filtername in filterlist:
common.log('Main.show_wizard', filtername)
params=[("method", "wizard_settings"), ("viewmode", "view"), ("filtername", filtername),
("period", ""), ("value", ""), ("page", "1")]
self.add_directory(name="%s" % (filtername),
params=params,
action="showpics",
iconimage=join(PIC_PATH, "folder_wizard.png"),
contextmenu=[(common.getstring(30152),
"RunPlugin(\"%s?" % (sys.argv[0]) +
"action=addfolder&method=wizard_settings&filtername=%s&viewmode=scan\")" %\
(filtername)), ],
total=total)
xbmcplugin.addSortMethod(
int(sys.argv[1]), xbmcplugin.SORT_METHOD_LABEL)
xbmcplugin.endOfDirectory(int(sys.argv[1]))
def show_tagtypes(self):
if int(common.getaddon_setting("ratingmini")) > 0:
min_rating = int(common.getaddon_setting("ratingmini"))
else:
min_rating = 0
listtags = MPDB.list_tagtypes_count(min_rating)
total = len(listtags)
common.log("Main.show_tagtypes", "total # of tag types = %s" % total)
for tag, nb in listtags:
if nb:
self.add_directory(name="%s (%s %s)" % (tag, nb, common.getstring(30052)), # libellé
params=[("method", "tagtype"), ("tagtype", tag), ("page", "1"),
("viewmode", "view")], # paramètres
action="showtags", # action
iconimage=join(PIC_PATH, "folder_tags.png"), # icone
# contextmenu = [('','')],
total=total) # nb total d'éléments
xbmcplugin.addSortMethod(
int(sys.argv[1]), xbmcplugin.SORT_METHOD_LABEL)
xbmcplugin.endOfDirectory(int(sys.argv[1]))
def show_tags(self):
if int(common.getaddon_setting("ratingmini")) > 0:
min_rating = int(common.getaddon_setting("ratingmini"))
else:
min_rating = 0
tagtype = self.args['tagtype']
listtags = [k for k in MPDB.list_tags_count(tagtype, min_rating)]
total = len(listtags)
common.log("Main.show_tags", "total # of tags = %s" % total)
for tag, nb in listtags:
if nb:
contextmenu=[(common.getstring(30152),
"RunPlugin(\"%s?" % (sys.argv[0]) +
"action=addfolder&method=tag&tag=%s&tagtype=%s&viewmode=scan\")" % \
(common.quote_param(tag), tagtype)),
(common.getstring(30061),
"RunPlugin(\"%s?" % (sys.argv[0]) +
"action=showpics&method=tag&viewmode=zip&name=%s&tag=%s&tagtype=%s\")" % \
(common.quote_param(tag), common.quote_param(tag), tagtype)),
(common.getstring(30062),
"RunPlugin(\"%s?" % (sys.argv[0]) +
"action=showpics&method=tag&viewmode=export&name=%s&tag=%s&tagtype=%s\")" % \
(common.quote_param(tag), common.quote_param(tag), tagtype))]
self.add_directory(name="%s (%s %s)" % (tag, nb, common.getstring(30050)), # libellé
params=[("method", "tag"), ("tag", tag), ("tagtype", tagtype), ("page", "1"),
("viewmode", "view")],
# paramètres
action="showpics", # action
iconimage=join(PIC_PATH, "folder_tags.png"), # icone
contextmenu=contextmenu, # menucontextuel
total=total) # nb total d'éléments
xbmcplugin.addSortMethod(
int(sys.argv[1]), xbmcplugin.SORT_METHOD_LABEL)
xbmcplugin.endOfDirectory(int(sys.argv[1]))
def show_period(self): # TODO finished the datestart and dateend editing
common.log("show_period", "started")
update = False
self.add_directory(name=common.getstring(30106),
params=[("period", "setperiod"),
("viewmode", "view")], # paramètres
action="showperiod", # action
iconimage=join(
PIC_PATH, "folder_date_ranges.png"), # icone
contextmenu=None) # menucontextuel
# If We previously choose to add a new period, this test will ask user for setting the period :
if self.args['period'] == "setperiod":
common.log("show_period", "setperiod")
# the choice of the date is made with pictures in database (datetime of pics are used)
dateofpics = MPDB.get_pics_dates()
nameddates = [strftime(self.prettydate(common.getstring(30002), strptime(date, "%Y-%m-%d")),
strptime(date, "%Y-%m-%d")) for date in dateofpics]
common.log("show_period >> namedates", nameddates)
if len(nameddates):
dialog = xbmcgui.Dialog()
# dateofpics) choose the start date
rets = dialog.select(common.getstring(30107),
["[[%s]]" % common.getstring(30114)] + nameddates)
if not rets == -1: # is not canceled
if rets == 0: # input manually the date
d = dialog.numeric(1, common.getstring(30117),
strftime("%d/%m/%Y", strptime(dateofpics[0], "%Y-%m-%d")))
common.log("period", str(d))
if d != '':
datestart = strftime("%Y-%m-%d", strptime(d.replace(" ", "0"), "%d/%m/%Y"))
else:
datestart = ''
deb = 0
else:
datestart = dateofpics[rets - 1]
deb = rets - 1
if datestart != '':
# dateofpics[deb:])#choose the end date (all dates before startdate are ignored to preserve begin/end)
retf = dialog.select(common.getstring(30108), ["[[%s]]" % common.getstring(30114)] + nameddates[deb:])
if not retf == -1: # if end date is not canceled...
if retf == 0: # choix d'un date de fin manuelle ou choix précédent de la date de début manuelle
d = dialog.numeric(1, common.getstring(30118),
strftime("%d/%m/%Y", strptime(dateofpics[-1], "%Y-%m-%d")))
if d != '':
dateend = strftime(
"%Y-%m-%d", strptime(d.replace(" ", "0"), "%d/%m/%Y"))
else:
dateend = ''
deb = 0
else:
dateend = dateofpics[deb + retf - 1]
if dateend != '':
# now input the title for the period
#
kb = xbmc.Keyboard(common.getstring(30109) % (datestart, dateend),
common.getstring(30110), False)
kb.doModal()
if (kb.isConfirmed()):
titreperiode = kb.getText()
else:
titreperiode = common.getstring(
30109) % (datestart, dateend)
# add the new period inside the database
MPDB.period_add(titreperiode, datestart, dateend)
update = True
else:
common.log("show_period", "No pictures with an EXIF date stored in DB")
# search for inbase periods and show periods
for periodname, dbdatestart, dbdateend in MPDB.periods_list():
datestart, dateend = MPDB.period_dates_get_pics(dbdatestart, dbdateend)
period = common.getstring(30113) % (datestart.strftime(common.getstring(30002)),
dateend.strftime(common.getstring(30002)))
contextmenu=[(common.getstring(30111),
"RunPlugin(\"%s?" % (sys.argv[0]) +
"action=removeperiod&viewmode=view&periodname=%s&period=period\")" % \
(common.quote_param(periodname))),
(common.getstring(30112),
"RunPlugin(\"%s?" % (sys.argv[0]) +
"action=renameperiod&viewmode=view&periodname=%s&period=period\")" % \
(common.quote_param(periodname))),
(common.getstring(30152),
"RunPlugin(\"%s?" % (sys.argv[0]) +
"action=addfolder&method=date&period=period&datestart=%s&dateend=%s&viewmode=scan\")" % \
(datestart, dateend))]
self.add_directory(name="%s [COLOR=C0C0C0C0](%s)[/COLOR]" % (periodname, period), # libellé
params=[("method", "date"), ("period", "period"), ("datestart", datestart),
("dateend", dateend), ("page", "1"), ("viewmode", "view")], # paramètres
action="showpics", # action
iconimage=join(PIC_PATH, "folder_date_ranges.png"), # icone
contextmenu=contextmenu) # menucontextuel
xbmcplugin.addSortMethod(
int(sys.argv[1]), xbmcplugin.SORT_METHOD_UNSORTED)
self.change_view()
xbmcplugin.endOfDirectory(int(sys.argv[1]), updateListing=update)
def show_collection(self):
if int(common.getaddon_setting("ratingmini")) > 0:
min_rating = int(common.getaddon_setting("ratingmini"))
else:
min_rating = 0
# herve502
from xml.dom.minidom import parseString
# /herve502
common.log("show_collection", "started")
if self.args['method'] == "setcollection": # ajout d'une collection
kb = xbmc.Keyboard("", common.getstring(30155), False)
kb.doModal()
if (kb.isConfirmed()):
namecollection = kb.getText()
else:
# name input for collection has been canceled
return
# create the collection in the database
common.log("show_collection", "setcollection = %s" % namecollection)
MPDB.collection_new(namecollection)
refresh = True
# import a collection from Filter Wizard Settings
elif self.args['method'] == "importcollection_wizard":
filters = MPDB.filterwizard_list_filters()
dialog = xbmcgui.Dialog()
ret = dialog.select(common.getstring(30608), filters)
if ret > -1:
# ask user for name of new collection
collection_name = filters[ret]
kb = xbmc.Keyboard(collection_name, common.getstring(30155), False)
kb.doModal()
if kb.isConfirmed():
collection_name = kb.getText()
# MPDB.collection_add_dyn_data(collection_name, filters[ret], 'FilterWizard')
rows = MPDB.filterwizard_get_pics_from_filter(filters[ret], 0)
if rows != None:
MPDB.collection_new(collection_name)
for pathname, filename in rows:
MPDB.collection_add_pic(collection_name, pathname, filename)
else:
common.log("show_collection",
str(filters[ret]) + "is empty and therefore not created.")
refresh = True
# herve502
elif self.args['method'] == "importcollection_picasa": # import xml from picasa
dialog = xbmcgui.Dialog()
importfile = dialog.browse(1, common.getstring(30162), "files", ".xml", True, False, "")
if not importfile:
return
not_imported = ""
try:
fh = open(importfile, 'r')
importfile = fh.read()
fh.close()
album = parseString(importfile)
collection_name = album.getElementsByTagName(
"albumName")[0].firstChild.data.encode("utf-8").strip()
# ask user if title as new collection name is correct
kb = xbmc.Keyboard(
collection_name, common.getstring(30155), False)
kb.doModal()
if (kb.isConfirmed()):
collection_name = kb.getText()
# create the collection in the database
common.log("show_collection",
"setcollection = %s" % collection_name)
MPDB.collection_new(collection_name)
# Xycl get pictures with complete path name
file_names = album.getElementsByTagName("itemOriginalPath")
for itemName in file_names: # iterate over the nodes
filepath = itemName.firstChild.data.encode(
"utf-8").strip() # get data ("name of picture")
filename = basename(filepath)
pathname = dirname(filepath)
try:
# Path in DB can end with "/" or "\" or without the path delimiter.
# Therefore it's a little bit tricky to test for exsistence of path.
# At first we use what is stored in DB
# if no row returns then the [0] at the end of select below will raise an exception.
# easy test of existence of file in DB
_query = """
select strFilename, strPath
from Files
where lower(strFilename) = ? and lower(strPath) = ?"
"""
filename, pathname = MPDB.cur.request_with_binds(
_query, (filename.lower(), pathname.lower()))[0]
MPDB.collection_add_pic(collection_name, pathname, filename)
except: