-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathosvm.py
4188 lines (3523 loc) · 170 KB
/
osvm.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/env python
# Create Globals instance
import osvmGlobals as globs
#import wx.lib.platebtn as platebtn
import sys
import platform
# Python version
globs.pythonVersion = (sys.version).split()[0] # 2.x or 3.x ?
globs.system = platform.system() # Linux or Windows or MacOS (Darwin)
globs.hostarch = platform.architecture()[0] # 64bit or 32bit
if '2.' in globs.pythonVersion:
try:
# for Python2
from Tkinter import * ## notice capitalized T in Tkinter
except ImportError:
# for Python3
from tkinter import * ## notice lowercase 't' in tkinter here
root = Tk()
root.title("ERROR!")
label = Label(root, text="\nERROR: %s requires Python 3.x to run.\n\n" % (globs.myName))
label.pack()
root.mainloop()
exit()
# XXX HACK to share the wx widget from 2.7 with python 3.6
sys.path.insert(0,'/usr/local/Cellar/wxmac/3.0.3.1_1/lib')
try:
import wx
except ImportError:
try:
root = Tk()
root.title("ERROR!")
label = Label(root, text="\nERROR: %s requires wxPython widgets to run.\n\n" % (globs.myName) +
"wxPython is available at http://www.wxpython.org/\n\n" +
"%s has been developped and tested with python 3.6 and wxPython 4.0.1 (Cocoa)\n" % (globs.myName))
label.pack()
root.mainloop()
exit()
#raise ImportError,"The wxPython module is required to run this program."
except:
print("ERROR: %s requires wxPython widgets to run.\n\n" % (globs.myName)),\
("wxPython is available at http://www.wxpython.org/\n\n",) \
("%s has been developped and tested with python 3.6 and wxPython 4.0.1 (Cocoa)\n" % (globs.myName))
exit()
import ast
import argparse
import builtins as __builtin__
import configparser
import ctypes
import datetime
import http.client
import inspect
import io
import math
import os
from os.path import expanduser
from PIL import Image, ImageOps # ExifTags,
import queue
import re
from urllib.request import Request, urlopen
from urllib.error import URLError
import urllib.request, urllib.error # urllib.parse,
import shutil
import socket
import struct
import subprocess
import threading
import tempfile
import time
import wx.adv
import wx.lib.colourdb as wb
import wx.lib.inspection
from wx.lib.newevent import NewEvent
import wx.lib.agw.flatnotebook as fnb
#from copy import deepcopy
#import wx.lib.scrolledpanel as scrolled
#import glob
#import traceback
#from urllib.parse import urlparse
# Local modules
moduleList = (
'ChromecastDialog',
'CleanDownloadDirDialog',
'DateDialog',
'ExifDialog',
'FileListFrame',
'HelpDialog',
'InstallDialog',
'LedControl',
'LogFrame',
'LogoPanel',
'MailDialog',
'MediaViewerDialog',
'PreferencesDialog',
'PropertiesDialog',
'rotateImage',
'ThumbnailDialog',
'WifiDialog',
'simpleQRScanner')
for m in moduleList:
print('Loading %s' % m)
mod = __import__(m, fromlist=[None])
globals()[m] = globals().pop('mod') # Rename module in globals()
try:
import pychromecast
except ImportError:
msg = 'PyChromeCast module not installed. Disabling Casting'
print(msg)
globs.pycc = False
globs.disabledModules.append(('PyChromecast',msg))
else:
globs.pycc = True
try:
import vlc # MediaViewer
except ImportError:
msg = 'Vlc module not installed. Disabling Video Viewer'
print(msg)
globs.vlcVideoViewer = False
globs.disabledModules.append(('VLC',msg))
else:
globs.vlcVideoViewer = True
try:
import objc # WifiDialog
except ImportError:
msg = 'Objc module not installed. Disabling Network Selector'
print(msg)
globs.networkSelector = False
globs.disabledModules.append(('Objc',msg))
else:
globs.networkSelector = True
if globs.system == 'Windows':
try:
#print 'Importing Windows win32 packages'
import win32api
import win32process
import win32event
except ImportError:
from tkinter import *
root = Tk()
root.title("ERROR!")
label = Label(root, text="\nERROR: %s requires win32 module to run.\n\n" % (globs.myName) +
"win32 is available at http://sourceforge.net/projects/pywin32/files/pywin32/\n\n" +
"%s has been developped and tested with python 3.6, wxPython 4.0.1 and pywin32 219\n" % (globs.myName))
label.pack()
root.mainloop()
sys.exit()
#raise ImportError,"The win32 modules are not installed."
wxRescanNeeded, EVT_RESCAN_NEEDED = NewEvent()
########################################
def myprint(*args, **kwargs):
"""My custom print() function."""
# Adding new arguments to the print function signature
# is probably a bad idea.
# Instead consider testing if custom argument keywords
# are present in kwargs
__builtin__.print('%s():' % inspect.stack()[1][3], *args, **kwargs)
def dateInSeconds(d, t):
''' return a value containing a date in seconds since 1/1/70. '''
maskDay = 0x001F # "0000000000011111"
maskMonth = 0x01E0 # "0000000111100000"
maskYear = 0xFE00 # "1111 1110 0000 0000"
day = (d & maskDay) >> 0
month = (d & maskMonth) >> 5
year = ((d & maskYear) >> 9) + 1980
maskSeconds = 0x001F # 0000000000011111
maskMinutes = 0x07E0 # 0000011111100000
maskHours = 0xF800 # 1111100000000000
hours = ((t & maskHours) >> 11) + 0 # XXX ???
minutes = (t & maskMinutes) >> 5
seconds = (t & maskSeconds) * 2
# myprint(year, month, day, hours, minutes, seconds)
t = datetime.datetime(year, month, day, min(hours,23), min(minutes,59), min(seconds,59))
return time.mktime(t.timetuple())
def getHumanDate(d):
''' return a string containing a date in human/readable format. '''
#d = 19330 # 2/12/2017
maskDay = 0x1F # "0000000000011111"
maskMonth = 0x1E0 # "0000000111100000"
maskYear = 0xFE00 # "1111 1110 0000 0000"
day = (d & maskDay) >> 0
month = (d & maskMonth) >> 5
year = ((d & maskYear) >> 9) + 1980
humanDate = "%d/%d/%d" % (month,day,year)
return humanDate
def getHumanTime(t):
''' return a string containing a time in human/readable format. '''
maskSeconds = 0x001F # 0000000000011111
maskMinutes = 0x07E0 # 0000011111100000
maskHours = 0xF800 # 1111100000000000
hours = ((t & maskHours) >> 11) # + 1 # XXX ???
minutes = (t & maskMinutes) >> 5
seconds = (t & maskSeconds) * 2
humanTime = "%d:%d:%d" % (hours,minutes,seconds)
return humanTime
def secondsToTime(t):
d = time.strftime('%H:%M:%S', time.localtime(t))
return d
def secondsTomdY(t):
d = time.strftime('%m/%d/%Y', time.localtime(t))
return d
def secondsTodmY(t):
d = time.strftime('%d/%m/%Y', time.localtime(t))
return d
def secondsTomdy(t):
d = time.strftime('%m/%d/%y', time.localtime(t))
return d
def secondsTodmy(t):
d = time.strftime('%d/%m/%y', time.localtime(t))
return d
def module_path(local_function):
''' returns the module path without the use of __file__.
Requires a function defined locally in the module.
from http://stackoverflow.com/questions/729583/getting-file-path-of-imported-module'''
return os.path.abspath(inspect.getsourcefile(local_function))
def humanBytes(size):
power = float(2**10) # 2**10 = 1024
n = 0
power_labels = {0 : 'B', 1: 'KB', 2: 'MB', 3: 'GB', 4: 'TB'}
while size > power:
size = float(size / power)
n += 1
return '%s %s' % (('%.2f' % size).rstrip('0').rstrip('.'), power_labels[n])
def diskUsage(path):
st = os.statvfs(path)
free = st.f_bavail * st.f_frsize
total = st.f_blocks * st.f_frsize
used = (st.f_blocks - st.f_bfree) * st.f_frsize
return (humanBytes(total), humanBytes(used), humanBytes(free))
def cleanup():
myprint('Destroying HTTP Server pid=%d' % globs.httpServer.pid)
try:
outs, errs = globs.httpServer.communicate(timeout=2)
except subprocess.TimeoutExpired:
myprint('Killing HTTP Server')
globs.httpServer.kill()
outs, errs = globs.httpServer.communicate()
myprint('Removing temporary files')
if os.path.exists(globs.htmlRootFile):
try:
os.remove(globs.htmlRootFile)
except:
myprint('Failed to remove %s' % (globs.htmlRootFile))
if os.path.exists(globs.htmlDirFile):
try:
os.remove(globs.htmlDirFile)
except:
myprint('Failed to remove %s' % (globs.htmlDirFile))
myprint('Removing corrupted/partial files')
for v in globs.localFileInfos.values():
filePath = v[globs.F_PATH]
try:
localFileSize = os.stat(filePath).st_size
except:
myprint('Error: os.stat()')
continue
else:
if localFileSize == 0:
myprint('Removing empty file %s' % filePath)
os.remove(filePath)
def getTmpFile():
f = tempfile.NamedTemporaryFile(delete=False)
return f.name
def dumpOperationList(title, oplist):
optype = ["DOWNLOAD", "MARK", "UNMARK"]
opstep = ["DOWNLOAD", "EXTRACT", "INSTALL"]
i = 0
print('**** Dump: %s ****' % title)
for op in oplist:
# print ('%d: STATUS: %d' % (i, op[globs.OP_STATUS]))
if op[globs.OP_STATUS] != 0:
print('*** %d ***' % (i))
print(' File Name: %s' % op[globs.OP_FILENAME])
print(' File Path: %s' % op[globs.OP_FILEPATH])
print(' File Type: %s' % op[globs.OP_FILETYPE])
ldate = time.strftime('%d-%b-%Y %H:%M', time.localtime(op[globs.OP_FILEDATE]))
print(' File Date: %s' % ldate)
print(' Request Type: %s' % optype[op[globs.OP_TYPE]])
if op[globs.OP_TYPE] == globs.FILE_DOWNLOAD:
print(' Local filename: %s' % op[globs.OP_FILEPATH])
print(' Remote File URL: %s' % op[globs.OP_REMURL])
print(' Remote File Size: %d/%d' % (op[globs.OP_SIZE][0],op[globs.OP_SIZE][1]))
print(' Current Transfer Block Counter: %d' % op[globs.OP_INCOUNT])
print(' Current Installation Step: %s' % opstep[op[globs.OP_INSTEP]])
if op[globs.OP_INTH]:
print(' Installation Thread: %s' % op[globs.OP_INTH].name)
i += 1
#
# Remove a local file. return -1 in case of failure
#
# def removeFile(pathname):
# try:
# myprint('Deleting:',pathname)
# os.remove(pathname)
# except OSError as e:
# msg = "Cannot remove %s: %s" % (pathname, "{0}".format(e.strerror))
# myprint(msg)
# return -1
# return 0
#
# Create a symbolic link on source. return -1 in case of failure
#
def createSymLink(path, link):
try:
myprint('path=%s link=%s' % (path,link))
os.symlink(path, link)
except IOError as e:
msg = "I/O error: %s %s" % ("({0}): {1}".format(e.errno, e.strerror),link)
myprint(msg)
return -1
return 0
# Browse a directory, looking for filenames ending with: JPG, MOV, ORF, MPO, MP4
def listLocalFiles(dir, hidden=False, relative=True, suffixes=('jpg', 'mov', 'orf', 'mpo', 'mp4')):
# suffixes = ('jpg', 'mov', 'orf', 'mpo', 'mp4')
myprint('Looking for files with suffix:', suffixes)
nodes = []
try:
for fname in os.listdir(dir):
if not hidden and fname.startswith('.'):
continue
if not fname.lower().endswith(suffixes):
continue
if not relative:
fname = os.path.join(dir, fname)
nodes.append(fname)
nodes.sort()
except:
myprint("Error: Can't browse:", dir)
return nodes
#
# Browse the Download directory.
# Output is a dictionary globs.localFileInfos{} containing:
# - key: fileName#
# - value: list of info for this file
#
# Return # entry in the dictionary
def localFilesInfo(dirName):
myprint('dirName=%s globs.cameraConnected=%s' % (dirName, globs.cameraConnected))
globs.localFileInfos = {}
fileList = listLocalFiles(dirName, hidden=False)
i = 0
# Get local file informations: size, date,...
# Cleanup the Download directory. Delete partially downloaded files
for fileName in fileList:
filePath = os.path.join(dirName, fileName)
if os.path.islink(filePath):
# Skip over symbolic links
continue
try:
statinfo = os.stat(filePath)
localFileSize = statinfo.st_size
except:
myprint('Error: os.stat()')
continue
# Check if local file exists on camera. Rotated images are bypassed
if not '-rot' in fileName:
if not globs.viewMode and globs.cameraConnected:
try:
remFileName = globs.availRemoteFiles[fileName][globs.F_NAME]
except:
# Local file does not exist anymore on remote/camera. Probably deleted...
myprint('File %s not found on remote/camera. Deleting.' % (fileName))
if globs.keepLocalFolderInSync:
print('deleting %s' % filePath)
#os.remove(filePath)
continue
# if not globs.viewMode:
# try:
# remFileSize = 0
# remFileSize = globs.availRemoteFiles[fileName][globs.F_SIZE]
# except:
# # Local file does not exist anymore on remote/camera. Probably deleted...
# print('File %s not found on remote/camera' % (fileName))
# if not remFileSize:
# print('MUST DELETE EMPTY LOCAL FILE %s' % (fileName))
# #os.remove(filePath)
# continue
# else:
# if localFileSize != remFileSize:
# print('MUST DELETE INCOMPLETE LOCAL FILE %s (%d)' % (fileName,localFileSize))
# os.remove(filePath)
# continue
fileDate = statinfo.st_mtime # in seconds
globs.localFileInfos[fileName] = [fileName,localFileSize,fileDate,filePath]
i += 1
globs.localFilesSorted = filterRotatedFiles(sorted(list(globs.localFileInfos.items()), key=lambda x: int(x[1][globs.F_DATEINSECS]), reverse=globs.fileSortRecentFirst))
return i
def filterRotatedFiles(fileList):
myprint('Filter =',globs.ROT_IMG_ENTRIES[globs.rotImgChoice])
if globs.rotImgChoice == 0:
# Must show rotated images if available and original files if not
lrotonly = [x[1][0] for x in fileList if '-rot' in x[0]] # list with rotated img only
l = list()
for e in fileList:
#print('###',e)
fileName = e[0]
field11 = e[1][1]
field12 = e[1][2]
filePath = e[1][3]
prefix = fileName.split('.')[0] # File prefix
if '-rot' in prefix: # Rotated file
continue
n = [x for x in lrotonly if re.search('%s-rot[0-9]+.jpg' % prefix, x, re.IGNORECASE)]
if n:
# Build a new tuple and append to output list
t = (n[0], [ n[0],field11,field12,os.path.join(os.path.dirname(filePath),n[0])])
l.append(t)
else:
l.append(e)
return l
if globs.rotImgChoice == 1:
# Must show only original files even if some files have been rotated
l = [x for x in fileList if not '-rot' in x[0]] # only original files
return l
if globs.rotImgChoice == 2: # Show both rotated/not rotated files
# Must show both rotated and non-rotated files, e.g. all files
return fileList
def downloadThumbnail(e):
uri = e[globs.F_THUMBURL]
thumbFile = e[globs.F_NAME]
thumbSize = e[globs.F_SIZE]
thumbnailPath = os.path.join(globs.thumbDir, thumbFile)
if os.path.isfile(thumbnailPath):
try:
f = open(thumbnailPath, 'r')
except IOError:
os.remove(thumbnailPath)
myprint('%s: Cannot use existing thumbnail. Will download it' % (thumbFile))
else:
f.close() # Using available local file
# myprint('Using existing thumbnail %s' % (thumbFile))
return 0
if globs.cameraConnected:
myprint("Downloading %s from camera" % (thumbFile))
try:
response = urllib.request.urlopen(uri)
except IOError as e:
msg = "I/O error: Opening URL %s %s" % (uri, "({0}): {1}".format(e.errno, e.strerror))
myprint(msg)
globs.cameraConnected = False
if globs.cameraConnected:
tmp = response.read()
try:
myprint("Creating %s" % (thumbnailPath))
out = open(thumbnailPath, 'wb')
out.write(tmp)
out.close()
return 0
except IOError as e:
msg = "I/O error: Creating %s: %s" % (thumbnailPath, "({0}): {1}".format(e.errno, e.strerror))
myprint(msg)
return -1
def getRootDirInfo(rootDir, uri):
if globs.cameraConnected:
myprint("Downloading from network: %s" % (uri))
try:
response = urllib.request.urlopen(uri)
except IOError as e:
msg = "I/O error: Opening URL %s %s" % (uri, "({0}): {1}".format(e.errno, e.strerror))
myprint(msg)
globs.cameraConnected = False
if globs.cameraConnected:
tmp = response.read()
try:
myprint("Opening: %s" % (globs.htmlDirFile))
out = open(globs.htmlDirFile, 'wb')
out.write(tmp)
out.close()
except IOError as e:
msg = "I/O error: Opening %s: %s" % (globs.htmlDirFile, "({0}): {1}".format(e.errno, e.strerror))
myprint(msg)
return -1
else:
myprint("You are offline")
return -1
# Filter out unnecessary lines
input = open(globs.htmlDirFile, 'r')
tmp = input.read()
input.close()
filterUrl = "%s/%s" % (globs.remBaseDir,rootDir) # e.g. /DCIM/100OLYMP XXX
tmp2 = [x for x in tmp.split('\n') if re.search(filterUrl, x)]
# Example :
# wlansd[0]="/DCIM/100OLYMP,PC020065.JPG,1482293,0,19330,31239";
globs.availRemoteFiles = {}
i = 0
for line in tmp2:
info = line.split('=')[1][1:] # e.g.: /DCIM/100OLYMP,PC020065.JPG,1482293,0,19330,31239";
# dirName = /DCIM/100OLYMP
# fileName = PC020065.JPG
# fileSize = 1482293
# fileAttr = 0
# fileDate = 19330
# t = 31239";
fields = info.split(',')
dirName,fileName,fileSize,fileAttr,fileDate,t = fields
fileTime = int(t[:len(t)-2]) # remove trailing "; characters
thumbnailUrl = "%s/get_thumbnail.cgi?DIR=%s/%s" % (globs.rootUrl,dirName,fileName) # e.g: http://192.168.0.10:80/get_thumbnail.cgi?DIR=/DCIM/100OLYMP/PC020065.JPG
# globs.availRemoteFiles[fileName] = [fileName, int(fileSize), int(fileDate), '', dirName, int(fileAttr), int(dateInSeconds(int(fileDate), int(fileTime))), int(fileTime), thumbnailUrl]
globs.availRemoteFiles[fileName] = [fileName, int(fileSize), int(dateInSeconds(int(fileDate), int(fileTime))), '', dirName, int(fileAttr), int(fileDate), int(fileTime), thumbnailUrl]
i += 1
myprint("%d files found" % i)
#print(globs.availRemoteFiles)
# Sort the dict by date: Latest file first
globs.availRemoteFilesSorted = sorted(list(globs.availRemoteFiles.items()), key=lambda x: int(x[1][globs.F_DATEINSECS]), reverse=globs.fileSortRecentFirst)
# for e in globs.availRemoteFilesSorted:
# print("Found remote file: %s size %d created %s %s %d" % (e[1][globs.F_NAME],e[1][globs.F_SIZE],getHumanDate(e[1][globs.F_DATE]),getHumanTime(e[1][globs.F_TIME]),int(e[1][globs.F_DATEINSECS])))
return i
def htmlRoot(): # XXX
if globs.cameraConnected:
myprint("Downloading from network: %s" % (globs.rootUrl))
try:
response = urllib.request.urlopen(globs.rootUrl,None,5)
except IOError as e:
msg = "I/O error: Opening URL %s %s" % (globs.rootUrl, "({0}): {1}".format(e.errno, e.strerror))
myprint(msg)
globs.cameraConnected = False
if globs.cameraConnected:
tmp = response.read()
try:
myprint("Opening: %s" % (globs.htmlRootFile))
out = open(globs.htmlRootFile, 'wb')
out.write(tmp)
out.close()
except IOError as e:
msg = "I/O error: Opening %s: %s" % (globs.htmlRootFile, "({0}): {1}".format(e.errno, e.strerror))
myprint(msg)
return -1
else:
myprint ('You are offline')
return -1
# Filter out unnecessary lines
input = open(globs.htmlRootFile, 'r')
tmp = input.read()
input.close()
baseRootDirs = [x for x in tmp.split('\n') if re.search(globs.remBaseDir, x)]
# Example :
# wlansd[0]="/DCIM,100OLYMP,0,16,19311,45705";
globs.rootDirList = []
i = 0
for line in baseRootDirs:
fields = line.split(',')
foo1,dirName,foo2,dirAttr,dirDate,foo3 = fields
if not int(dirAttr) & 0x10:
myprint("Invalid entry %s. Skipping" % (dirName))
continue
globs.rootDirList.append(dirName)
i += 1
myprint("%d root dirs found" % len(globs.rootDirList))
for d in globs.rootDirList:
myprint("Detected remote folder: %s" % d)
return len(globs.rootDirList)
def clearDirectory(dir):
myprint('Deleting:',dir)
if not os.path.isdir(dir):
return
shutil.rmtree(dir)
def updateFileDicts():
# Reset camera status. Will be updated if connection fails
globs.cameraConnected = True
# Download the root HTML from the camera
#relRootUrl = '%s%s' % (globs.osvmFilesDownloadUrl, globs.remBaseDir)
globs.rootDirCnt = htmlRoot()
myprint('%d root directories available for download' % (globs.rootDirCnt))
if globs.rootDirCnt <= 0:
globs.availRemoteFilesCnt = 0
globs.cameraConnected = False
globs.availRemoteFiles.clear()
globs.availRemoteFilesSorted.clear()
else:
for d in globs.rootDirList:
uri = '%s%s/%s' % (globs.osvmFilesDownloadUrl, globs.remBaseDir, d)
myprint("1%s 2%s 3%s" % (globs.osvmFilesDownloadUrl, globs.remBaseDir, d))
myprint("Querying URL %s..." % (uri))
globs.availRemoteFilesCnt = getRootDirInfo(d, uri)
myprint('%d remote files available' % globs.availRemoteFilesCnt)
for e in sorted(globs.availRemoteFiles.values()):
ret = downloadThumbnail(e)
if ret:
myprint ("Error while downloading thumbnail.")
break
# Detect local files
globs.localFilesCnt = localFilesInfo(globs.osvmDownloadDir)
myprint('%d local files, %d remote files' % (globs.localFilesCnt, globs.availRemoteFilesCnt))
return globs.localFilesCnt,globs.availRemoteFilesCnt
def str2bool(v):
return v.lower() in ("yes", "true", "t", "1")
def touch(path):
with open(path, 'a'):
os.utime(path, None)
# Delete local files if needed
def deleteLocalFile(pDialog, filePath):
ret = 0 # error counter
msg = 'Removing local file %s\n' % (filePath)
wx.CallAfter(pDialog.installError, 0, msg)
removeCmd = 'rm %s' % filePath.replace(" ", "\\ ")
p = subprocess.Popen(removeCmd, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True)
for line in p.stdout.readlines():
msg += line.strip()
ret = p.wait()
print('removeCmd =',removeCmd,'ret=',ret,'msg=',msg)
if not ret:
msg = "File %s successfully removed\n" % (filePath)
globs.localFilesCnt = localFilesInfo(globs.osvmDownloadDir)
wx.CallAfter(pDialog.installError, ret, msg)
return (ret, msg)
# Return the background and foreground colors to paint a widget associated
# to the given file
def fileColor(fileName):
color = globs.fileColors[globs.FILE_NOT_INSTALLED] # Default color
try:
e = globs.localFileInfos[fileName]
except:
return color
color = globs.fileColors[globs.FILE_INSTALLED]
return color
#
# Set/unset busy cursor (from thread)
#
def setBusyCursor(state):
if state:
wx.BeginBusyCursor(cursor=wx.HOURGLASS_CURSOR)
else:
wx.EndBusyCursor()
# Dump object attributes
def dumpAttrs(obj):
for attr in dir(obj):
print("obj.%s = %s" % (attr, getattr(obj, attr)))
def checkUrl(url):
p = urlparse(url)
conn = http.client.HTTPConnection(p.netloc)
conn.request('HEAD', p.path)
resp = conn.getresponse()
return resp.status < 400
def startHTTPServer():
null = open('/dev/null', 'w')
p = subprocess.Popen(
[sys.executable, '-m', 'http.server', globs.SERVER_HTTP_PORT],
shell=False,
cwd=globs.osvmDownloadDir,
stdout=null,
stderr=null,
)
myprint('Initializing HTTP Server on port %s, root=%s' % (globs.SERVER_HTTP_PORT, globs.osvmDownloadDir))
time.sleep(1)
return p
def serverIpAddr():
try:
ipAddr = [l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0]
except OSError as e:
msg = 'serverIpAddr(): Error %s' % ("({0}): {1}".format(e.errno, e.strerror))
print(msg)
ipAddr = '0;0;0;0'
myprint(ipAddr)
return ipAddr
# Check if local images need to be rotated using Exif metadata and proceed accordingly
def rotateLocalImages(exifData):
fileList = listLocalFiles(globs.osvmDownloadDir, hidden=False, relative=False, suffixes=('jpg'))
for f in [x for x in fileList if not '-rot' in x]: # Skip over rotated images
try:
exifDataAsStr = exifData[os.path.basename(f)]
except:
myprint('No Exif data for %s' % f)
else:
rotateImage.rotateImage(f, ast.literal_eval(exifDataAsStr))
# Check if some thumbnails are missing in globs.osvmDownloadDir
def createImagesThumbnail():
fileList = listLocalFiles(globs.osvmDownloadDir, hidden=False, relative=True, suffixes=('jpg'))
for f in [x for x in fileList if not '-rot' in x]: # Skip over rotated images
thumbnailFilePath = os.path.join(globs.thumbDir, f)
if not os.path.exists(thumbnailFilePath):
filePath = os.path.join(globs.osvmDownloadDir, f)
myprint('Creating: %s' % (thumbnailFilePath))
size = (160,120)
thumb = ImageOps.fit(Image.open(filePath), size, Image.ANTIALIAS)
thumb.save(thumbnailFilePath)
# image = Image.open(filePath)
# try:
# exif = image.info['exif'] # Read exif from info attribute
# except:
# exif = b''
# #Create thumbnail of image, keeping exif data
# size = (160,120)
# image.thumbnail(size, Image.ANTIALIAS)
# image.save(thumbnailFilePath, exif=exif)
# image.close()
# Modify modification time
os.utime(thumbnailFilePath, (0, os.path.getmtime(filePath)))
def unbufprint(text):
sys.__stdout__.write(text)
sys.__stdout__.flush()
############# CLASSES #########################################################
class SlideShowThread(threading.Thread):
def __init__(self, parent, name, threadLock):
threading.Thread.__init__(self)
self._parent = parent
self._name = name
self._threadLock = threadLock
print('%s: Started' % self._name)
def stopIt(self):
print('%s: Stopping' % self._name)
self._stopper.set()
print('%s: isStopped() : %s' % (self._name, self.isStopped()))
def isStopped(self):
return self._stopper.isSet()
def run(self):
print('%s: Running. Server: %s:%s' % (self._name, globs.serverAddr, globs.SERVER_HTTP_PORT))
while True:
self._threadLock.acquire() # will block until 'Start slideshow' button is pressed
# self._stopper.clear() # Thread is running
f = self._parent.mediaFileList[globs.slideShowNextIdx % globs.slideShowLastIdx]
fileURL = 'http://%s:%s/%s' % (globs.serverAddr, globs.SERVER_HTTP_PORT, f[globs.F_NAME])
print('%s: idx %d/%d Loading URL: %s' % (self._name, globs.slideShowNextIdx,globs.slideShowLastIdx, fileURL))
mediaFileType = { 'jpg':'image/jpg', 'mov':'video/mov', 'mp4':'video/mov' }
suffix = f[globs.F_NAME].split('.')[1].lower()
globs.castMediaCtrl.play_media(fileURL, mediaFileType[suffix])
if suffix == 'mov':
idleCnt = 0
while True:
if globs.castMediaCtrl.status.player_state == 'IDLE':
idleCnt += 1
print('IDLE',idleCnt)
if idleCnt > 2: # Assume end of video
break
time.sleep(1)
else:
globs.castMediaCtrl.block_until_active()
self._threadLock.release()
time.sleep(int(globs.ssDelay))
globs.slideShowNextIdx = (globs.slideShowNextIdx + 1) % globs.slideShowLastIdx
#### class Preferences
class Preferences():
def __init__(self):
pass
def _loadPreferences(self):
newInitFile1 = self._loadInitFile()
newInitFile2 = self._parseInitFile()
if newInitFile1 or newInitFile2:
dlg = PreferencesDialog.PreferencesDialog(self)
dlg.ShowModal()
dlg.Destroy()
#globs.printGlobals()
def _savePreferences(self):
self._saveInitFile()
# Return a dictionary (if exists) for the given section in the ConfigParser object
def _initFileSectionGet(self, config, section):
dict1 = {}
try:
options = config.options(section)
except:
myprint('exception on option: %s' % options)
return dict1
for opt in options:
try:
dict1[opt] = config.get(section, opt)
if dict1[opt] == -1:
myprint('skipping: %s' % opt)
except:
myprint("Got exception: %s" % opt)
dict1[opt] = None
return dict1
def _loadInitFile(self):
myprint("Loading preference file:", globs.initFilePath)
self.config = configparser.ConfigParser()
cf = self.config.read(globs.initFilePath)
if self.config.sections() == []:
# Create a new Init file, return TRUE
self._createDefaultInitFile()
cf = self.config.read([globs.initFilePath])
return True
return False
def _createDefaultInitFile(self):
myprint('Warning: Cannot read preference file, Creating default: %s' % globs.initFilePath)
if os.path.exists(globs.initFilePath):
initFilePathBk = os.path.join(os.path.join(expanduser("~"), globs.osvmDir, globs.initFileBk))
myprint('Saving old/existing confile file to %s' % (initFilePathBk))
shutil.copy2(globs.initFilePath, initFilePathBk)
# add the default settings to the file
self.config['Version'] = {globs.INI_VERSION: globs.iniFileVersion}
self.config['Preferences'] = {}
self.config['Preferences'][globs.COMPACT_MODE] = str(globs.DEFAULT_COMPACT_MODE)
self.config['Preferences'][globs.ASK_BEFORE_COMMIT] = str(globs.DEFAULT_ASK_BEFORE_COMMIT)
self.config['Preferences'][globs.ASK_BEFORE_EXIT] = str(globs.DEFAULT_ASK_BEFORE_EXIT)
self.config['Preferences'][globs.KEEP_LOCAL_FOLDER_IN_SYNC] = str(globs.DEFAULT_KEEP_LOCAL_FOLDER_IN_SYNC)
self.config['Preferences'][globs.SAVE_PREFS_ON_EXIT] = str(globs.DEFAULT_SAVE_PREFERENCES_ON_EXIT)
self.config['Preferences'][globs.OVERWRITE_LOCAL_FILES] = str(globs.DEFAULT_OVERWRITE_LOCAL_FILES)
self.config['Preferences'][globs.AUTO_SWITCH_TO_CAMERA_NETWORK] = str(globs.AUTO_SWITCH_TO_CAMERA_NETWORK)
self.config['Preferences'][globs.THUMB_GRID_COLUMNS] = str(globs.DEFAULT_THUMB_GRID_NUM_COLS)
self.config['Preferences'][globs.THUMB_SCALE_FACTOR] = str(globs.DEFAULT_THUMB_SCALE_FACTOR)
self.config['Preferences'][globs.OSVM_DOWNLOAD_DIR] = globs.DEFAULT_OSVM_DOWNLOAD_DIR
self.config['Preferences'][globs.SORT_ORDER] = str(globs.DEFAULT_SORT_ORDER)
self.config['Preferences'][globs.LOG_FRAME ] = str(globs.DEFAULT_LOG_FRAME)
self.config['Sync Mode Preferences'] = {}
self.config['Sync Mode Preferences'][globs.REM_BASE_DIR] = globs.DEFAULT_OSVM_REM_BASE_DIR
self.config['Sync Mode Preferences'][globs.OSVM_FILES_DOWNLOAD_URL] = globs.DEFAULT_OSVM_ROOT_URL
self.config['Sync Mode Preferences'][globs.MAX_DOWNLOAD] = str(globs.DEFAULT_MAX_DOWNLOAD)
self.config['View Mode Preferences'] = {}
self.config['View Mode Preferences'][globs.SS_DELAY] = str(globs.DEFAULT_SLIDESHOW_DELAY)
self.config['View Mode Preferences'][globs.LAST_CAST_DEVICE_NAME] = ''
self.config['View Mode Preferences'][globs.LAST_CAST_DEVICE_UUID] = ''
self.config['View Mode Preferences'][globs.ROT_IMG_CHOICE] = str(globs.DEFAULT_ROT_IMG_CHOICE)
self.config['Networks'] = {}
self.config['Networks'][globs.FAVORITE_NETWORK] = ''',''' #None,None
self.config['Colors'] = {}
for i in range(len(globs.DEFAULT_FILE_COLORS)):
self.config['Colors']['color_%d' % (i)] = str(globs.DEFAULT_FILE_COLORS[i][0].GetRGB())
self.config['Mail Preferences'] = {}
self.config['Mail Preferences'][globs.SMTP_SERVER] = globs.DEFAULT_SMTP_SERVER
self.config['Mail Preferences'][globs.SMTP_SERVER_PROTOCOL] = globs.DEFAULT_SMTP_SERVER_PROTOCOL
self.config['Mail Preferences'][globs.SMTP_SERVER_PORT] = str(globs.DEFAULT_SMTP_SERVER_PORT)
self.config['Mail Preferences'][globs.SMTP_SERVER_USE_AUTH] = str(globs.DEFAULT_SMTP_SERVER_USE_AUTH)
self.config['Mail Preferences'][globs.SMTP_SERVER_USER_NAME] = globs.DEFAULT_SMTP_SERVER_USER_NAME
self.config['Mail Preferences'][globs.SMTP_SERVER_USER_PASSWD] = globs.DEFAULT_SMTP_SERVER_USER_PASSWD
self.config['Mail Preferences'][globs.SMTP_FROM_USER] = globs.DEFAULT_SMTP_FROM_USER
self.config['Mail Preferences'][globs.SMTP_RECIPIENTS_LIST] = globs.DEFAULT_SMTP_RECIPIENTS_LIST
# Writing our configuration file back to initFile
with open(globs.initFilePath, 'w') as cfgFile:
self.config.write(cfgFile)
cfgFile.close()
def _parseInitFile(self):
try:
self.config.read( globs.initFilePath)
# Get OSVM version section
iniFileVersion = self.config['Version'][globs.INI_VERSION]
if iniFileVersion != globs.iniFileVersion:
print ('_parseInitFile(): Outdated INI file. Resetting to defaults')
# Get preferences from Preferences
sectionPreferences = self.config['Preferences']
if not globs.compactMode: # User has not used '-c' cmdline argument
globs.compactMode = str2bool(sectionPreferences[globs.COMPACT_MODE])
else:
globs.thumbnailGridRows = 5
globs.askBeforeCommit = str2bool(sectionPreferences[globs.ASK_BEFORE_COMMIT])
globs.askBeforeExit = str2bool(sectionPreferences[globs.ASK_BEFORE_EXIT])
globs.keepLocalFolderInSync = str2bool(sectionPreferences[globs.KEEP_LOCAL_FOLDER_IN_SYNC])
globs.savePreferencesOnExit = str2bool(sectionPreferences[globs.SAVE_PREFS_ON_EXIT])
globs.overwriteLocalFiles = str2bool(sectionPreferences[globs.OVERWRITE_LOCAL_FILES])
globs.autoSwitchToFavoriteNetwork = str2bool(sectionPreferences[globs.AUTO_SWITCH_TO_CAMERA_NETWORK])
globs.thumbnailGridColumns = int(sectionPreferences[globs.THUMB_GRID_COLUMNS])
globs.thumbnailScaleFactor = float(sectionPreferences[globs.THUMB_SCALE_FACTOR])
# If user has used the '-p' cmdline argument, override the osvmDownloadDir parameter
if globs.imagePathCmdLineArg:
globs.osvmDownloadDir = globs.imagePathCmdLineArg
else:
globs.osvmDownloadDir = sectionPreferences[globs.OSVM_DOWNLOAD_DIR]
globs.fileSortRecentFirst = str2bool(sectionPreferences[globs.SORT_ORDER])
globs.logFrame = str2bool(sectionPreferences[globs.LOG_FRAME])
sectionSyncModePref = self.config['Sync Mode Preferences']
globs.remBaseDir = sectionSyncModePref[globs.REM_BASE_DIR]
globs.osvmFilesDownloadUrl = sectionSyncModePref[globs.OSVM_FILES_DOWNLOAD_URL]
globs.maxDownload = int(sectionSyncModePref[globs.MAX_DOWNLOAD])
if globs.maxDownload == 0:
globs.maxDownload = globs.MAX_OPERATIONS
globs.ssDelay = self.config['View Mode Preferences'][globs.SS_DELAY]
globs.lastCastDeviceName = self.config['View Mode Preferences'][globs.LAST_CAST_DEVICE_NAME]
globs.lastCastDeviceUuid = self.config['View Mode Preferences'][globs.LAST_CAST_DEVICE_UUID]