-
Notifications
You must be signed in to change notification settings - Fork 87
/
uploadr.py
executable file
·1220 lines (1011 loc) · 42.9 KB
/
uploadr.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
"""
flickr-uploader designed for Synology Devices
Upload a directory of media to Flickr to use as a backup to your local storage.
Features:
-Uploads both images and movies (JPG, PNG, GIF, AVI, MOV, 3GP files)
-Stores image information locally using a simple SQLite database
-Automatically creates "Sets" based on the folder name the media is in
-Ignores ".picasabackup" directory
-Automatically removes images from Flickr when they are removed from your local hard drive
Requirements:
-Python 2.7+
-File write access (for the token and local database)
-Flickr API key (free)
Setup:
Go to http://www.flickr.com/services/apps/create/apply and apply for an API key Edit the following variables in the uploadr.ini
FILES_DIR = "files/"
FLICKR = { "api_key" : "", "secret" : "", "title" : "", "description" : "", "tags" : "auto-upload", "is_public" : "0", "is_friend" : "0", "is_family" : "1" }
SLEEP_TIME = 1 * 60
DRIP_TIME = 1 * 60
DB_PATH = os.path.join(FILES_DIR, "fickerdb")
Place the file uploadr.py in any directory and run:
$ ./uploadr.py
It will crawl through all the files from the FILES_DIR directory and begin the upload process.
Upload files placed within a directory to your Flickr account.
Inspired by:
http://micampe.it/things/flickruploadr
https://github.com/joelmx/flickrUploadr/blob/master/python3/uploadr.py
Usage:
cron entry (runs at the top of every hour )
0 * * * * /full/path/to/uploadr.py > /dev/null 2>&1
This code has been updated to use the new Auth API from flickr.
You may use this code however you see fit in any form whatsoever.
"""
import httplib
import sys
import argparse
import mimetools
import mimetypes
import os
import time
import urllib
import urllib2
import webbrowser
import sqlite3 as lite
import json
from xml.dom.minidom import parse
import hashlib
try:
# Use portalocker if available. Required for Windows systems
import portalocker as FileLocker # noqa
FILELOCK = FileLocker.lock
except ImportError:
# Use fcntl
import fcntl as FileLocker
FILELOCK = FileLocker.lockf
import errno
import subprocess
import re
import ConfigParser
from multiprocessing.pool import ThreadPool
if sys.version_info < (2, 7):
sys.stderr.write("This script requires Python 2.7 or newer.\n")
sys.stderr.write("Current version: " + sys.version + "\n")
sys.stderr.flush()
sys.exit(1)
#
# Read Config from config.ini file
#
config = ConfigParser.ConfigParser()
config.read(os.path.join(os.path.dirname(sys.argv[0]), "uploadr.ini"))
FILES_DIR = eval(config.get('Config', 'FILES_DIR'))
FLICKR = eval(config.get('Config', 'FLICKR'))
SLEEP_TIME = eval(config.get('Config', 'SLEEP_TIME'))
DRIP_TIME = eval(config.get('Config', 'DRIP_TIME'))
DB_PATH = eval(config.get('Config', 'DB_PATH'))
LOCK_PATH = eval(config.get('Config', 'LOCK_PATH'))
TOKEN_PATH = eval(config.get('Config', 'TOKEN_PATH'))
EXCLUDED_FOLDERS = eval(config.get('Config', 'EXCLUDED_FOLDERS'))
IGNORED_REGEX = [re.compile(regex) for regex in eval(config.get('Config', 'IGNORED_REGEX'))]
ALLOWED_EXT = eval(config.get('Config', 'ALLOWED_EXT'))
RAW_EXT = eval(config.get('Config', 'RAW_EXT'))
FILE_MAX_SIZE = eval(config.get('Config', 'FILE_MAX_SIZE'))
MANAGE_CHANGES = eval(config.get('Config', 'MANAGE_CHANGES'))
RAW_TOOL_PATH = eval(config.get('Config', 'RAW_TOOL_PATH'))
CONVERT_RAW_FILES = eval(config.get('Config', 'CONVERT_RAW_FILES'))
FULL_SET_NAME = eval(config.get('Config', 'FULL_SET_NAME'))
SOCKET_TIMEOUT = eval(config.get('Config', 'SOCKET_TIMEOUT'))
MAX_UPLOAD_ATTEMPTS = eval(config.get('Config', 'MAX_UPLOAD_ATTEMPTS'))
class APIConstants:
""" APIConstants class
"""
base = "https://api.flickr.com/services/"
rest = base + "rest/"
auth = base + "auth/"
upload = base + "upload/"
replace = base + "replace/"
def __init__(self):
""" Constructor
"""
pass
api = APIConstants()
class Uploadr:
""" Uploadr class
"""
token = None
perms = ""
def __init__(self):
""" Constructor
"""
self.token = self.getCachedToken()
def signCall(self, data):
"""
Signs args via md5 per http://www.flickr.com/services/api/auth.spec.html (Section 8)
"""
keys = data.keys()
keys.sort()
foo = ""
for a in keys:
foo += (a + data[a])
f = FLICKR["secret"] + "api_key" + FLICKR["api_key"] + foo
# f = "api_key" + FLICKR[ "api_key" ] + foo
return hashlib.md5(f).hexdigest()
def urlGen(self, base, data, sig):
""" urlGen
"""
data['api_key'] = FLICKR["api_key"]
data['api_sig'] = sig
encoded_url = base + "?" + urllib.urlencode(data)
return encoded_url
def authenticate(self):
""" Authenticate user so we can upload files
"""
print("Getting new token")
self.getFrob()
self.getAuthKey()
self.getToken()
self.cacheToken()
def getFrob(self):
"""
flickr.auth.getFrob
Returns a frob to be used during authentication. This method call must be
signed.
This method does not require authentication.
Arguments
"api_key" (Required)
Your API application key. See here for more details.
"""
d = {
"method": "flickr.auth.getFrob",
"format": "json",
"nojsoncallback": "1"
}
sig = self.signCall(d)
url = self.urlGen(api.rest, d, sig)
try:
response = self.getResponse(url)
if (self.isGood(response)):
FLICKR["frob"] = str(response["frob"]["_content"])
else:
self.reportError(response)
except:
print("Error: cannot get frob:" + str(sys.exc_info()))
def getAuthKey(self):
"""
Checks to see if the user has authenticated this application
"""
d = {
"frob": FLICKR["frob"],
"perms": "delete"
}
sig = self.signCall(d)
url = self.urlGen(api.auth, d, sig)
ans = ""
try:
webbrowser.open(url)
print("Copy-paste following URL into a web browser and follow instructions:")
print(url)
ans = raw_input("Have you authenticated this application? (Y/N): ")
except:
print(str(sys.exc_info()))
if (ans.lower() == "n"):
print("You need to allow this program to access your Flickr site.")
print("Copy-paste following URL into a web browser and follow instructions:")
print(url)
print("After you have allowed access restart uploadr.py")
sys.exit()
def getToken(self):
"""
http://www.flickr.com/services/api/flickr.auth.getToken.html
flickr.auth.getToken
Returns the auth token for the given frob, if one has been attached. This method call must be signed.
Authentication
This method does not require authentication.
Arguments
NTC: We need to store the token in a file so we can get it and then check it insted of
getting a new on all the time.
"api_key" (Required)
Your API application key. See here for more details.
frob (Required)
The frob to check.
"""
d = {
"method": "flickr.auth.getToken",
"frob": str(FLICKR["frob"]),
"format": "json",
"nojsoncallback": "1"
}
sig = self.signCall(d)
url = self.urlGen(api.rest, d, sig)
try:
res = self.getResponse(url)
if (self.isGood(res)):
self.token = str(res['auth']['token']['_content'])
self.perms = str(res['auth']['perms']['_content'])
self.cacheToken()
else:
self.reportError(res)
except:
print(str(sys.exc_info()))
def getCachedToken(self):
"""
Attempts to get the flickr token from disk.
"""
if (os.path.exists(TOKEN_PATH)):
return open(TOKEN_PATH).read()
else:
return None
def cacheToken(self):
""" cacheToken
"""
try:
open(TOKEN_PATH, "w").write(str(self.token))
except:
print("Issue writing token to local cache ", str(sys.exc_info()))
def checkToken(self):
"""
flickr.auth.checkToken
Returns the credentials attached to an authentication token.
Authentication
This method does not require authentication.
Arguments
"api_key" (Required)
Your API application key. See here for more details.
auth_token (Required)
The authentication token to check.
"""
if (self.token == None):
return False
else:
d = {
"auth_token": str(self.token),
"method": "flickr.auth.checkToken",
"format": "json",
"nojsoncallback": "1"
}
sig = self.signCall(d)
url = self.urlGen(api.rest, d, sig)
try:
res = self.getResponse(url)
if (self.isGood(res)):
self.token = res['auth']['token']['_content']
self.perms = res['auth']['perms']['_content']
return True
else:
self.reportError(res)
except:
print(str(sys.exc_info()))
return False
def removeIgnoredMedia(self):
print("*****Removing ignored files*****")
if (not self.checkToken()):
self.authenticate()
con = lite.connect(DB_PATH)
con.text_factory = str
with con:
cur = con.cursor()
cur.execute("SELECT files_id, path FROM files")
rows = cur.fetchall()
for row in rows:
if (self.isFileIgnored(row[1].decode('utf-8'))):
success = self.deleteFile(row, cur)
print("*****Completed ignored files*****")
def removeDeletedMedia(self):
""" Remove files deleted at the local source
loop through database
check if file exists
if exists, continue
if not exists, delete photo from fickr
http://www.flickr.com/services/api/flickr.photos.delete.html
"""
print("*****Removing deleted files*****")
if (not self.checkToken()):
self.authenticate()
con = lite.connect(DB_PATH)
con.text_factory = str
with con:
cur = con.cursor()
cur.execute("SELECT files_id, path FROM files")
rows = cur.fetchall()
for row in rows:
if (not os.path.isfile(row[1].decode('utf-8'))):
success = self.deleteFile(row, cur)
print("*****Completed deleted files*****")
def upload(self):
""" upload
"""
print("*****Uploading files*****")
allMedia = self.grabNewFiles()
# If managing changes, consider all files
if MANAGE_CHANGES:
changedMedia = allMedia
# If not, then get just the new and missing files
else:
con = lite.connect(DB_PATH)
with con:
cur = con.cursor()
cur.execute("SELECT path FROM files")
existingMedia = set(file[0] for file in cur.fetchall())
changedMedia = set(allMedia) - existingMedia
changedMedia_count = len(changedMedia)
print("Found " + str(changedMedia_count) + " files")
if args.processes:
pool = ThreadPool(processes=int(args.processes))
pool.map(self.uploadFile, changedMedia)
else:
count = 0
for i, file in enumerate(changedMedia):
success = self.uploadFile(file)
if args.drip_feed and success and i != changedMedia_count - 1:
print("Waiting " + str(DRIP_TIME) + " seconds before next upload")
time.sleep(DRIP_TIME)
count = count + 1;
if (count % 100 == 0):
print(" " + str(count) + " files processed (uploaded, md5ed or timestamp checked)")
if (count % 100 > 0):
print(" " + str(count) + " files processed (uploaded, md5ed or timestamp checked)")
print("*****Completed uploading files*****")
def convertRawFiles(self):
""" convertRawFiles
"""
if (not CONVERT_RAW_FILES):
return
print "*****Converting files*****"
for ext in RAW_EXT:
print ("About to convert files with extension:" + ext + " files.")
for dirpath, dirnames, filenames in os.walk(unicode(FILES_DIR), followlinks=True):
if '.picasaoriginals' in dirnames:
dirnames.remove('.picasaoriginals')
if '@eaDir' in dirnames:
dirnames.remove('@eaDir')
for f in filenames:
fileExt = f.split(".")[-1]
filename = f.split(".")[0]
if (fileExt.lower() == ext):
if (not os.path.exists(dirpath + "/" + filename + ".JPG")):
print("About to create JPG from raw " + dirpath + "/" + f)
flag = ""
if ext is "cr2":
flag = "PreviewImage"
else:
flag = "JpgFromRaw"
command = RAW_TOOL_PATH + "exiftool -b -" + flag + " -w .JPG -ext " + ext + " -r '" + dirpath + "/" + filename + "." + fileExt + "'"
# print(command)
p = subprocess.call(command, shell=True)
if (not os.path.exists(dirpath + "/" + filename + ".JPG_original")):
print ("About to copy tags from " + dirpath + "/" + f + " to JPG.")
command = RAW_TOOL_PATH + "exiftool -tagsfromfile '" + dirpath + "/" + f + "' -r -all:all -ext JPG '" + dirpath + "/" + filename + ".JPG'"
# print(command)
p = subprocess.call(command, shell=True)
print ("Finished copying tags.")
print ("Finished converting files with extension:" + ext + ".")
print "*****Completed converting files*****"
def grabNewFiles(self):
""" grabNewFiles
"""
files = []
for dirpath, dirnames, filenames in os.walk(unicode(FILES_DIR), followlinks=True):
for f in filenames:
filePath = os.path.join(dirpath, f)
if self.isFileIgnored(filePath):
continue
if any(ignored.search(f) for ignored in IGNORED_REGEX):
continue
ext = os.path.splitext(os.path.basename(f))[1][1:].lower()
if ext in ALLOWED_EXT:
fileSize = os.path.getsize(dirpath + "/" + f)
if (fileSize < FILE_MAX_SIZE):
files.append(os.path.normpath(dirpath + "/" + f).replace("'", "\'"))
else:
print("Skipping file due to size restriction: " + (os.path.normpath(dirpath + "/" + f)))
files.sort()
return files
def isFileIgnored(self, filename):
for excluded_dir in EXCLUDED_FOLDERS:
if excluded_dir in os.path.dirname(filename):
return True
return False
def uploadFile(self, file):
""" uploadFile
"""
if args.dry_run :
print("Dry Run Uploading " + file + "...")
return True
success = False
con = lite.connect(DB_PATH)
con.text_factory = str
with con:
cur = con.cursor()
cur.execute("SELECT rowid,files_id,path,set_id,md5,tagged,last_modified FROM files WHERE path = ?", (file,))
row = cur.fetchone()
last_modified = os.stat(file).st_mtime;
if row is None:
print("Uploading " + file + "...")
if FULL_SET_NAME:
setName = os.path.relpath(os.path.dirname(file), FILES_DIR)
else:
head, setName = os.path.split(os.path.dirname(file))
try:
photo = ('photo', file.encode('utf-8'), open(file, 'rb').read())
if args.title: # Replace
FLICKR["title"] = args.title
if args.description: # Replace
FLICKR["description"] = args.description
if args.tags: # Append
FLICKR["tags"] += " "
file_checksum = self.md5Checksum(file)
d = {
"auth_token": str(self.token),
"perms": str(self.perms),
"title": str(FLICKR["title"]),
"description": str(FLICKR["description"]),
# replace commas to avoid tags conflicts
"tags": '{} {} checksum:{}'.format(FLICKR["tags"], setName.encode('utf-8'), file_checksum).replace(',', ''),
"is_public": str(FLICKR["is_public"]),
"is_friend": str(FLICKR["is_friend"]),
"is_family": str(FLICKR["is_family"])
}
sig = self.signCall(d)
d["api_sig"] = sig
d["api_key"] = FLICKR["api_key"]
url = self.build_request(api.upload, d, (photo,))
res = None
search_result = None
for x in range(0, MAX_UPLOAD_ATTEMPTS):
try:
res = parse(urllib2.urlopen(url, timeout=SOCKET_TIMEOUT))
search_result = None
break
except (IOError, httplib.HTTPException):
print(str(sys.exc_info()))
print("Check is file already uploaded")
time.sleep(5)
search_result = self.photos_search(file_checksum)
if search_result["stat"] != "ok":
raise IOError(search_result)
if int(search_result["photos"]["total"]) == 0:
if x == MAX_UPLOAD_ATTEMPTS - 1:
raise ValueError("Reached maximum number of attempts to upload, skipping")
print("Not found, reuploading")
continue
if int(search_result["photos"]["total"]) > 1:
raise IOError("More then one file with same checksum, collisions? " + search_result)
if int(search_result["photos"]["total"]) == 1:
break
if not search_result and res.documentElement.attributes['stat'].value != "ok":
print("A problem occurred while attempting to upload the file: " + file)
raise IOError(str(res.toxml()))
print("Successfully uploaded the file: " + file)
if search_result:
file_id = int(search_result["photos"]["photo"][0]["id"])
else:
file_id = int(str(res.getElementsByTagName('photoid')[0].firstChild.nodeValue))
# Add to db
cur.execute(
'INSERT INTO files (files_id, path, md5, last_modified, tagged) VALUES (?, ?, ?, ?, 1)',
(file_id, file, file_checksum, last_modified))
success = True
except:
print(str(sys.exc_info()))
elif (MANAGE_CHANGES):
if (row[6] == None):
cur.execute('UPDATE files SET last_modified = ? WHERE files_id = ?', (last_modified, row[1]))
con.commit()
if (row[6] != last_modified):
fileMd5 = self.md5Checksum(file)
if (fileMd5 != str(row[4])):
self.replacePhoto(file, row[1], row[4], fileMd5, last_modified, cur, con);
return success
def replacePhoto(self, file, file_id, oldFileMd5, fileMd5, last_modified, cur, con):
if args.dry_run :
print("Dry Run Replace file " + file + "...")
return True
success = False
print("Replacing the file: " + file + "...")
try:
photo = ('photo', file.encode('utf-8'), open(file, 'rb').read())
d = {
"auth_token": str(self.token),
"photo_id": str(file_id)
}
sig = self.signCall(d)
d["api_sig"] = sig
d["api_key"] = FLICKR["api_key"]
url = self.build_request(api.replace, d, (photo,))
res = None
res_add_tag = None
res_get_info = None
for x in range(0, MAX_UPLOAD_ATTEMPTS):
try:
res = parse(urllib2.urlopen(url, timeout=SOCKET_TIMEOUT))
if res.documentElement.attributes['stat'].value == "ok":
res_add_tag = self.photos_add_tags(file_id, ['checksum:{}'.format(fileMd5)])
if res_add_tag['stat'] == 'ok':
res_get_info = flick.photos_get_info(file_id)
if res_get_info['stat'] == 'ok':
tag_id = None
for tag in res_get_info['photo']['tags']['tag']:
if tag['raw'] == 'checksum:{}'.format(oldFileMd5):
tag_id = tag['id']
break
if not tag_id:
print("Can't find tag {} for file {}".format(tag_id, file_id))
break
else:
self.photos_remove_tag(tag_id)
break
except (IOError, ValueError, httplib.HTTPException):
print(str(sys.exc_info()))
print("Replacing again")
time.sleep(5)
if x == MAX_UPLOAD_ATTEMPTS - 1:
raise ValueError("Reached maximum number of attempts to replace, skipping")
continue
if res.documentElement.attributes['stat'].value != "ok" \
or res_add_tag['stat'] != 'ok' \
or res_get_info['stat'] != 'ok':
print("A problem occurred while attempting to upload the file: " + file)
if res.documentElement.attributes['stat'].value != "ok":
raise IOError(str(res.toxml()))
if res_add_tag['stat'] != 'ok':
raise IOError(res_add_tag)
if res_get_info['stat'] != 'ok':
raise IOError(res_get_info)
print("Successfully replaced the file: " + file)
# Add to set
cur.execute('UPDATE files SET md5 = ?,last_modified = ? WHERE files_id = ?',
(fileMd5, last_modified, file_id))
con.commit()
success = True
except:
print(str(sys.exc_info()))
return success
def deleteFile(self, file, cur):
if args.dry_run :
print("Deleting file: " + file[1].decode('utf-8'))
return True
success = False
print("Deleting file: " + file[1].decode('utf-8'))
try:
d = {
# FIXME: double format?
"auth_token": str(self.token),
"perms": str(self.perms),
"format": "rest",
"method": "flickr.photos.delete",
"photo_id": str(file[0]),
"format": "json",
"nojsoncallback": "1"
}
sig = self.signCall(d)
url = self.urlGen(api.rest, d, sig)
res = self.getResponse(url)
if (self.isGood(res)):
# Find out if the file is the last item in a set, if so, remove the set from the local db
cur.execute("SELECT set_id FROM files WHERE files_id = ?", (file[0],))
row = cur.fetchone()
cur.execute("SELECT set_id FROM files WHERE set_id = ?", (row[0],))
rows = cur.fetchall()
if (len(rows) == 1):
print("File is the last of the set, deleting the set ID: " + str(row[0]))
cur.execute("DELETE FROM sets WHERE set_id = ?", (row[0],))
# Delete file record from the local db
cur.execute("DELETE FROM files WHERE files_id = ?", (file[0],))
print("Successful deletion.")
success = True
else:
if (res['code'] == 1):
# File already removed from Flicker
cur.execute("DELETE FROM files WHERE files_id = ?", (file[0],))
else:
self.reportError(res)
except:
# If you get 'attempt to write a readonly database', set 'admin' as owner of the DB file (fickerdb) and 'users' as group
print(str(sys.exc_info()))
return success
def logSetCreation(self, setId, setName, primaryPhotoId, cur, con):
print("adding set to log: " + setName.decode('utf-8'))
success = False
cur.execute("INSERT INTO sets (set_id, name, primary_photo_id) VALUES (?,?,?)",
(setId, setName, primaryPhotoId))
cur.execute("UPDATE files SET set_id = ? WHERE files_id = ?", (setId, primaryPhotoId))
con.commit()
return True
def build_request(self, theurl, fields, files, txheaders=None):
"""
build_request/encode_multipart_formdata code is from www.voidspace.org.uk/atlantibots/pythonutils.html
Given the fields to set and the files to encode it returns a fully formed urllib2.Request object.
You can optionally pass in additional headers to encode into the opject. (Content-type and Content-length will be overridden if they are set).
fields is a sequence of (name, value) elements for regular form fields - or a dictionary.
files is a sequence of (name, filename, value) elements for data to be uploaded as files.
"""
content_type, body = self.encode_multipart_formdata(fields, files)
if not txheaders: txheaders = {}
txheaders['Content-type'] = content_type
txheaders['Content-length'] = str(len(body))
return urllib2.Request(theurl, body, txheaders)
def encode_multipart_formdata(self, fields, files, BOUNDARY='-----' + mimetools.choose_boundary() + '-----'):
""" Encodes fields and files for uploading.
fields is a sequence of (name, value) elements for regular form fields - or a dictionary.
files is a sequence of (name, filename, value) elements for data to be uploaded as files.
Return (content_type, body) ready for urllib2.Request instance
You can optionally pass in a boundary string to use or we'll let mimetools provide one.
"""
CRLF = '\r\n'
L = []
if isinstance(fields, dict):
fields = fields.items()
for (key, value) in fields:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"' % key)
L.append('')
L.append(value)
for (key, filename, value) in files:
filetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
L.append('Content-Type: %s' % filetype)
L.append('')
L.append(value)
L.append('--' + BOUNDARY + '--')
L.append('')
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY # XXX what if no files are encoded
return content_type, body
def isGood(self, res):
""" isGood
"""
if (not res == "" and res['stat'] == "ok"):
return True
else:
return False
def reportError(self, res):
""" reportError
"""
try:
print("Error: " + str(res['code'] + " " + res['message']))
except:
print("Error: " + str(res))
def getResponse(self, url):
"""
Send the url and get a response. Let errors float up
"""
res = None
try:
res = urllib2.urlopen(url, timeout=SOCKET_TIMEOUT).read()
except urllib2.HTTPError, e:
print(e.code)
except urllib2.URLError, e:
print(e.args)
return json.loads(res, encoding='utf-8')
def run(self):
""" run
"""
while (True):
self.upload()
print("Last check: " + str(time.asctime(time.localtime())))
time.sleep(SLEEP_TIME)
def createSets(self):
print('*****Creating Sets*****')
if args.dry_run :
return True
con = lite.connect(DB_PATH)
con.text_factory = str
with con:
cur = con.cursor()
cur.execute("SELECT files_id, path, set_id FROM files")
files = cur.fetchall()
for row in files:
if FULL_SET_NAME:
setName = os.path.relpath(os.path.dirname(row[1]), FILES_DIR)
else:
head, setName = os.path.split(os.path.dirname(row[1]))
newSetCreated = False
cur.execute("SELECT set_id, name FROM sets WHERE name = ?", (setName,))
set = cur.fetchone()
if set == None:
setId = self.createSet(setName, row[0], cur, con)
print("Created the set: " + setName.decode('utf-8'))
newSetCreated = True
else:
setId = set[0]
if row[2] == None and newSetCreated == False:
print("adding file to set " + row[1].decode('utf-8'))
self.addFileToSet(setId, row, cur)
print('*****Completed creating sets*****')
def addFileToSet(self, setId, file, cur):
if args.dry_run :
return True
try:
d = {
"auth_token": str(self.token),
"perms": str(self.perms),
"format": "json",
"nojsoncallback": "1",
"method": "flickr.photosets.addPhoto",
"photoset_id": str(setId),
"photo_id": str(file[0])
}
sig = self.signCall(d)
url = self.urlGen(api.rest, d, sig)
res = self.getResponse(url)
if (self.isGood(res)):
print("Successfully added file " + str(file[1]) + " to its set.")
cur.execute("UPDATE files SET set_id = ? WHERE files_id = ?", (setId, file[0]))
else:
if (res['code'] == 1):
print("Photoset not found, creating new set...")
if FULL_SET_NAME:
setName = os.path.relpath(os.path.dirname(file[1]), FILES_DIR)
else:
head, setName = os.path.split(os.path.dirname(file[1]))
con = lite.connect(DB_PATH)
con.text_factory = str
self.createSet(setName, file[0], cur, con)
elif (res['code'] == 3):
print(res['message'] + "... updating DB")
cur.execute("UPDATE files SET set_id = ? WHERE files_id = ?", (setId, file[0]))
else:
self.reportError(res)
except:
print(str(sys.exc_info()))
def createSet(self, setName, primaryPhotoId, cur, con):
print("Creating new set: " + setName.decode('utf-8'))
if args.dry_run :
return True
try:
d = {
"auth_token": str(self.token),
"perms": str(self.perms),
"format": "json",
"nojsoncallback": "1",
"method": "flickr.photosets.create",
"primary_photo_id": str(primaryPhotoId),
"title": setName
}
sig = self.signCall(d)
url = self.urlGen(api.rest, d, sig)
res = self.getResponse(url)
if (self.isGood(res)):
self.logSetCreation(res["photoset"]["id"], setName, primaryPhotoId, cur, con)
return res["photoset"]["id"]
else:
print(d)
self.reportError(res)
except:
print(str(sys.exc_info()))
return False
def setupDB(self):
print("Setting up the database: " + DB_PATH)
con = None
try:
con = lite.connect(DB_PATH)
con.text_factory = str
cur = con.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS files (files_id INT, path TEXT, set_id INT, md5 TEXT, tagged INT)')
cur.execute('CREATE TABLE IF NOT EXISTS sets (set_id INT, name TEXT, primary_photo_id INTEGER)')
cur.execute('CREATE UNIQUE INDEX IF NOT EXISTS fileindex ON files (path)')
cur.execute('CREATE INDEX IF NOT EXISTS setsindex ON sets (name)')
con.commit()
cur = con.cursor()
cur.execute('PRAGMA user_version')
row = cur.fetchone()
if (row[0] == 0):
print('Adding last_modified column to database');
cur = con.cursor()
cur.execute('PRAGMA user_version="1"')
cur.execute('ALTER TABLE files ADD COLUMN last_modified REAL');
con.commit()
con.close()
except lite.Error, e:
print("Error: %s" % e.args[0])
if con != None:
con.close()
sys.exit(1)
finally:
print("Completed database setup")
def md5Checksum(self, filePath):
with open(filePath, 'rb') as fh:
m = hashlib.md5()
while True:
data = fh.read(8192)
if not data:
break
m.update(data)
return m.hexdigest()
# Method to clean unused sets
def removeUselessSetsTable(self):
print('*****Removing empty Sets from DB*****')
if args.dry_run :
return True
con = lite.connect(DB_PATH)
con.text_factory = str
with con:
cur = con.cursor()
cur.execute("SELECT set_id, name FROM sets WHERE set_id NOT IN (SELECT set_id FROM files)")
unusedsets = cur.fetchall()
for row in unusedsets:
print("Unused set spotted about to be deleted: " + str(row[0]) + " (" + row[1].decode('utf-8') + ")")
cur.execute("DELETE FROM sets WHERE set_id = ?", (row[0],))
con.commit()