3 # Simple script to export a file from the datastore
4 # Reinier Heeres, <reinier@heeres.eu>, 2007-12-24
5 # Phil Bordelon <phil@thenexusproject.org>
12 from sugar
.datastore
import datastore
15 # Limit the number of objects returned on an ambiguous query to this number,
16 # for quicker operation.
19 def build_option_parser():
21 usage
= "Usage: %prog [-o OBJECT_ID] [-q SEARCH_STR] [-t SEARCH_STR] [-m] OUTFILE"
22 parser
= optparse
.OptionParser(usage
=usage
)
24 parser
.add_option("-o", "--object_id", action
="store", dest
="object_id",
25 help="Retrieve object with explicit ID OBJECT_ID", metavar
="OBJECT_ID",
28 parser
.add_option("-q", "--query", action
="store", dest
="query",
29 help="Full-text-search the metadata for SEARCH_STR", metavar
="SEARCH_STR",
32 parser
.add_option("-t", "--title", action
="store", dest
="title",
33 help="Full-text-search the title for SEARCH_STR", metavar
="SEARCH_STR",
36 parser
.add_option("-m", "--metadata", action
="store_true", dest
="show_meta",
37 help="Show all non-preview metadata [default: hide]", default
=False)
41 if __name__
== "__main__":
43 parser
= build_option_parser()
44 options
, args
= parser
.parse_args()
51 # Get object directly if we were given an explicit object ID.
52 if options
.object_id
is not None:
53 dsentry
= datastore
.get(options
.object_id
)
55 # Compose the query based on the options provided.
59 if options
.query
is not None:
60 query
['query'] = options
.query
61 if options
.title
is not None:
62 query
['title'] = options
.title
64 # We only want a single file at a time; limit the number of objects
65 # returned to two, as anything more than one means the criteria were
67 objects
, count
= datastore
.find(query
, limit
=RETURN_LIMIT
, sorting
='-mtime')
69 print 'WARNING: %d objects found; retrieving most recent.' % (count
)
70 for i
in xrange(1, RETURN_LIMIT
):
76 # If neither an explicit object ID nor a query gave us data, fail.
78 print 'ERROR: unable to determine journal object to copy.'
82 # Print metadata if that is what the user asked for.
85 for key
, val
in dsentry
.metadata
.get_dictionary().iteritems():
87 print '%20s -> %s' % (key
, val
)
89 # If no file is associated with this object, we can't save it out.
90 if dsentry
.get_file_path() == "":
91 print 'ERROR: no file associated with object, just metadata.'
96 outroot
, outext
= os
.path
.splitext(outname
)
98 # Do our best to determine the output file extension, based on Sugar's
99 # MIME-type-to-extension mappings.
101 mimetype
= dsentry
.metadata
['mime_type']
102 outext
= sugar
.mime
.get_primary_extension(mimetype
)
106 # Lastly, actually copy the file out of the datastore and onto the
108 shutil
.copyfile(dsentry
.get_file_path(), outroot
+ '.' + outext
)
109 print '%s -> %s' % (dsentry
.get_file_path(), outroot
+ '.' + outext
)