File: __init__.py

package info (click to toggle)
griffith 0.9.7.1-1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 5,912 kB
  • ctags: 5,224
  • sloc: python: 27,496; xml: 543; ansic: 325; makefile: 252
file content (239 lines) | stat: -rw-r--r-- 7,926 bytes parent folder | download
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
# -*- coding: UTF-8 -*-

__revision__ = '$Id: __init__.py 891 2007-12-16 21:13:53Z piotrek $'

# Copyright (c) 2006-2007 Piotr Ożarowski
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published byp
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA

# You may use and distribute this software under the terms of the
# GNU General Public License, version 2 or later

# detect all plugins:
import glob, os.path
from gettext import gettext as _

__all__ = [os.path.basename(x)[:-3] for x in glob.glob("%s/*.py" % os.path.dirname(__file__))]
__all__.remove('__init__')

class ImportPlugin:
	description = None
	author = None
	email = None
	version = None
	# file chooser:
	file_filters = None
	mime_types = None

	edit = False		# open add window for every movie?

	imported = 0
	data = None

	def __init__(self, parent, fields_to_import):
		self.db		= parent.db
		self.debug	= parent.debug
		self.locations	= parent.locations
		self.fields	= parent.field_names
		self.conditions	= parent._conditions
		self.colors	= parent._colors
		self.lang_types	= parent._lang_types
		self.layers	= parent._layers
		self.regions	= parent._regions
		self.widgets	= parent.widgets['import']
		self.fields_to_import = fields_to_import
		self._abort	= False

	def initialize(self):
		"""Initializes plugin (get all parameters from user, etc.)"""
		self.imported = 0
		return True

	def abort(self, *args):
		"""called after abort button clicked"""
		self._abort = True

	def set_source(self, name):
		"""Prepare source (open file, etc.)"""

	def count_movies(self):
		"""Returns number of movies in file which is about to be imported"""
		pass

	def get_movie_details(self):
		"""Returns dictionary with movie details"""
		pass

	def run(self, name):
		"""Import movies, function called in a loop over source files"""
		from add import validate_details, edit_movie
		from gutils import find_next_available
		from sqlalchemy import Select, func
		import gtk
		
		if not self.set_source(name):
			self.debug.show("Can't read data from file %s" % name)
			return False
		
		self.widgets['pwindow'].show()
		while gtk.events_pending():	# give GTK some time for updates
			gtk.main_iteration()

		# progressbar
		update_on = []
		count = self.count_movies()
		if count > 0:
			for i in range(0,100):
				update_on.append(int(float(i)/100*count))

		statement = Select( [ func.max(self.db.Movie.c.number) ] )
		number = statement.execute().fetchone()[0]
		if number is None:
			number = 1
		else:
			number += 1

		statement = Select([self.db.Movie.c.number])

		processed = 0
		while self._abort is False:
			details = self.get_movie_details()
			if details is None:
				break

			processed += 1
			if processed in update_on:
				self.widgets['progressbar'].set_fraction(float(processed)/float(count))
				gtk.main_iteration()
				self.widgets['progressbar'].set_text("%s (%s/%s)" % (str(self.imported), str(processed), str(count)))
				gtk.main_iteration()
				gtk.main_iteration() # extra iteration for abort button

			if (details.has_key('o_title') and details['o_title']) or (details.has_key('title') and details['title']):
				if details.has_key('o_title') and details['o_title']:
					statement.whereclause = func.lower(self.db.Movie.c.o_title)==details['o_title'].lower()
					if details.has_key('title') and details['title']:
						statement.append_whereclause( func.lower(self.db.Movie.c.title)==details['title'].lower() )
					tmp = statement.execute().fetchone()
					if tmp is not None:
						self.debug.show("movie already exists (number=%s, o_title=%s)" % (tmp.number, details['o_title']))
						continue
				elif details.has_key('title') and details['title']:
					statement.whereclause = func.lower(self.db.Movie.c.title)==details['title'].lower()
					tmp = statement.execute().fetchone()
					if tmp is not None:
						self.debug.show("movie already exists (number=%s, title=%s)" % (tmp.number, details['title']))
						continue
				validate_details(details, self.fields_to_import)
				if self.edit is True:
					response = edit_movie(self.parent, details)	# FIXME: wait until save or cancel button pressed
					if response == 1:
						self.imported += 1
				else:
					if not details.has_key('number') or (details.has_key('number') and details['number'] is None):
						#details['number'] = find_next_available(self.db)
						details['number'] = number
						number += 1
					#movie = self.db.Movie()
					#movie.add_to_db(details)
					try:
						self.db.Movie.mapper.mapped_table.insert().execute(details)
						self.imported += 1
					except Exception, e:
						self.debug.show("movie details are not unique, skipping: %s" % str(e))
			else:
				self.debug.show('skipping movie without title or original title')
		self.widgets['pwindow'].hide()
		return True

	def clear(self):
		"""clear plugin before next source file"""
		self.data = None
		self.imported = 0
		self.__source_name = None
		self._abort = False
	
	def destroy(self):
		"""close all resources"""
		pass


def on_import_plugin_changed(combobox, widgets, *args):
	from gtk import FileFilter
	import plugins.imp
	plugin_name = widgets['plugin'].get_active_text()
	__import__("plugins.imp.%s" % plugin_name)
	ip = eval("plugins.imp.%s.ImportPlugin" % plugin_name)
	widgets['author'].set_markup("<i>%s</i>" % ip.author)
	widgets['email'].set_markup("<i>%s</i>" % ip.email)
	widgets['version'].set_markup("<i>%s</i>" %ip.version)
	widgets['description'].set_markup("<i>%s</i>" %ip.description)
	# file filters
	for i in widgets['fcw'].list_filters():
		widgets['fcw'].remove_filter(i)
	f = FileFilter()
	f.set_name(plugin_name)
	if ip.file_filters is not None:
		if isinstance(ip.file_filters, tuple) or isinstance(ip.file_filters, list):
			for i in ip.file_filters:
				f.add_pattern(i)
		else:
			f.add_pattern(ip.file_filters)
	if ip.mime_types is not None:
		if isinstance(ip.mime_types, tuple) or isinstance(ip.mime_types, list):
			for i in ip.mime_types:
				f.add_mime_type(i)
		else:
			f.add_mime_type(ip.mime_types)
	widgets['fcw'].add_filter(f)
	f = FileFilter()
	f.set_name(_("All files"))
	f.add_pattern("*")
	widgets['fcw'].add_filter(f)

def on_import_button_clicked(button, self, *args):
	import plugins.imp, gutils
	plugin_name = self.widgets['import']['plugin'].get_active_text()
	filenames = self.widgets['import']['fcw'].get_filenames()
	
	fields = []
	w = self.widgets['import']['fields']
	for i in w:
		if w[i].get_active():
			fields.append(i)

	__import__("plugins.imp.%s" % plugin_name)
	ip = eval("plugins.imp.%s.ImportPlugin(self, fields)" % plugin_name)
	if ip.initialize():
		self.widgets['window'].set_sensitive(False)
		self.widgets['import']['window'].hide()
		self.widgets['import']['pabort'].connect('clicked', ip.abort, ip)
		for filename in filenames:
			self.widgets['import']['progressbar'].set_fraction(0)
			self.widgets['import']['progressbar'].set_text('')
			if ip.run(filename):
				gutils.info(self, _("%s file has been imported. %s movies added.") \
					% (plugin_name, ip.imported), self.widgets['window'])
				self.populate_treeview()
			ip.clear()
		ip.destroy()
		self.widgets['import']['pwindow'].hide()
		self.widgets['window'].set_sensitive(True)

def on_abort_button_clicked(button, self, *args):
	self.widgets['import']['window'].hide()
	self.widgets['import']['pwindow'].hide()
	self.widgets['window'].set_sensitive(True)