[MerlinSkinThemes] - there's also DM52x ;-)
[enigma2-plugins.git] / movietagger / src / plugin.py
1 from Plugins.Plugin import PluginDescriptor
2 from Screens.Screen import Screen
3 from Components.Label import Label
4 from Components.MenuList import MenuList
5 from Components.MovieList import MovieList
6 from Screens.InputBox import InputBox
7 from Screens.MessageBox import MessageBox
8 from Components.ActionMap import ActionMap
9 from Components.MultiContent import MultiContentEntryText
10 from enigma import eServiceReference, eListboxPythonMultiContent, eServiceCenter, gFont, iServiceInformation
11
12 from Tools.Directories import pathExists, resolveFilename, SCOPE_HDD, SCOPE_PLUGINS
13
14 VERSION = "1.3"
15
16 class MovieTagger(Screen):
17         skin = """
18                 <screen position="center,70" size="600,460" title="Movie Tagger" >
19                         <widget name="moviename" position="10,0" size="580,60" valign="top" font="Regular;25"/>
20                         <ePixmap pixmap="skin_default/div-h.png" position="0,62" zPosition="1" size="600,2" />
21                         <widget name="assignedTags" position="10,65" size="260,30" valign="top" halign="left" zPosition="2" foregroundColor="white" font="Regular;23"/>
22                         <widget name="cTaglist" position="10,100" size="260,250" scrollbarMode="showOnDemand"/>
23                         <widget name="definedTags" position="300,65" size="290,30" valign="top" halign="left" zPosition="2" foregroundColor="white" font="Regular;23"/>
24                         <widget name="aTaglist" position="290,100" size="300,250" scrollbarMode="showOnDemand"/>
25                 
26                         <ePixmap pixmap="skin_default/div-h.png" position="0,358" zPosition="1" size="600,2" />
27                         <widget name="usedTag" position="10,365" size="185,50" valign="top" halign="center" zPosition="2" foregroundColor="#ffff00" font="Regular;21"/>
28                         <widget name="userTag" position="200,365" size="185,50" valign="top" halign="center" zPosition="2" foregroundColor="#ff0000" font="Regular;21"/>
29                         <widget name="preTag" position="400,365" size="190,50" valign="top" halign="center" zPosition="2" foregroundColor="#00ff00" font="Regular;21"/>
30
31                         <ePixmap pixmap="skin_default/buttons/red.png" position="0,420" zPosition="0" size="140,40" transparent="1" alphatest="on" />
32                         <ePixmap pixmap="skin_default/buttons/green.png" position="155,420" zPosition="0" size="140,40" transparent="1" alphatest="on" />
33                         <ePixmap pixmap="skin_default/buttons/yellow.png" position="305,420" zPosition="0" size="140,40" transparent="1" alphatest="on" />
34                         <ePixmap pixmap="skin_default/buttons/blue.png" position="455,420" zPosition="0" size="140,40" transparent="1" alphatest="on" />
35
36                         <widget name="buttonred" position="0,420" size="140,40" valign="center" halign="center" zPosition="2" foregroundColor="white" transparent="1" font="Regular;18"/>
37                         <widget name="buttongreen" position="155,420" size="140,40" valign="center" halign="center" zPosition="2" foregroundColor="white" transparent="1" font="Regular;18"/>
38                         <widget name="buttonyellow" position="305,420" size="140,40" valign="center" halign="center" zPosition="2" foregroundColor="white" transparent="1" font="Regular;18"/>
39                         <widget name="buttonblue" position="455,420" size="140,40" valign="center" halign="center" zPosition="2" foregroundColor="white" transparent="1" font="Regular;18"/>
40                 </screen>"""
41
42         currList = None
43
44         def __init__(self, session, service):
45                 self.session = session
46                 self.service = service
47                 self.serviceHandler = eServiceCenter.getInstance()
48                 self.info = self.serviceHandler.info(self.service)
49
50                 self.skin = MovieTagger.skin
51                 Screen.__init__(self, session)
52                 self["moviename"] = Label(self.info.getName(self.service))
53                 self["assignedTags"] = Label("AssignedTags")
54                 self["definedTags"] = Label("DefinedTags")
55                 self["usedTag"] = Label("UsedTag")
56                 self["userTag"] = Label("UserTag")
57                 self["preTag"] = Label("PreTag")
58                 self["buttonred"] = Label("red")
59                 self["buttongreen"] = Label("green")
60                 self["buttonyellow"] = Label("yellow")
61                 self["buttonblue"] = Label("blue")
62                 self["cTaglist"] = MenuList([])
63                 self["aTaglist"] = TagMenuList([])
64                 self["actions"] = ActionMap(["WizardActions","MenuActions","ShortcutActions"],
65                         {
66                         "back":         self.close,
67                         "red":          self.keyRed,
68                         "green":        self.keyGreen,
69                         "yellow":       self.keyYellow,
70                         "blue":         self.keyBlue,
71                         "up":           self.up,
72                         "down":         self.down,
73                         "left":         self.left,
74                         "right":        self.right,
75                         }, -1)
76                 self.pretags = self.loadPreTags("/etc/enigma2/movietags") or self.loadPreTags(resolveFilename(SCOPE_PLUGINS, "Extensions/MovieTagger/movietags"))
77                 self.updateCurrentTagList()
78                 self.updateAllTagList()
79                 self.currList = self["aTaglist"]
80                 self.onLayoutFinish.append(self.keyBlue)
81
82         def loadPreTags(self, filename):
83                 try:
84                         with open(filename, "r") as f:
85                                 pretags = sorted(f.read().splitlines())
86                 except:
87                         print "pretags file %s does not exist" % filename
88                         return []
89                 else:
90                         print "pretags loaded from %s:" % filename, pretags
91                         return pretags
92
93         def updateCurrentTagList(self):
94                 print "updating cTagList"
95                 self.serviceHandler = eServiceCenter.getInstance()
96                 self.info = self.serviceHandler.info(self.service)
97                 self.tags = self.info.getInfoString(self.service, iServiceInformation.sTags).split(' ')
98                 self.tags.sort()
99                 self["cTaglist"].l.setList(self.tags)
100
101         def updateAllTagList(self):
102                 root = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + resolveFilename(SCOPE_HDD))
103                 ml = MovieList(root)
104                 ml.load(root,None)
105                 xtmp = []
106                 xtmp.extend(ml.tags)
107                 self.usedTags = xtmp
108
109                 e = []+self.pretags
110                 for i in ml.tags:
111                         try:
112                                 self.pretags.index(i)
113                         except ValueError:
114                                 e.append(i)
115
116                 taglist = []
117                 for i in e:
118                         res = [ i ]
119                         res.append(MultiContentEntryText(pos=(5,0),size=(500,25),font=0,text=i))
120                         if self.isUsedTag(i):
121                                 res.append(MultiContentEntryText(pos=(220,0),size=(20,25),font=1,text="X",color=0x00FFFF00)) #yellow
122                         if self.isUserTag(i) :
123                                 res.append(MultiContentEntryText(pos=(240,0),size=(20,25),font=1, text="X",color=0x00FF0000)) #red
124                         if self.isPreTag(i):
125                                 res.append(MultiContentEntryText(pos=(260,0),size=(20,25),font=1,text="X",color=0x0000FF00)) #green
126
127                         taglist.append(res)
128
129                 taglist.sort()
130                 self["aTaglist"].l.setList(taglist)
131
132         def addTag(self,tagname):
133                 try:
134                         self.tags.index(tagname)
135                 except ValueError:
136                         self.tags.append(tagname)
137                         if len(self.tags) >1:
138                                 self.setTags(" ".join(self.tags))
139                         else:
140                                 self.setTags(tagname)
141                 self.updateCurrentTagList()
142                 self.updateAllTagList()
143
144
145         def removeTag(self,tagname):
146                 newtags = []
147                 for i in self.tags:
148                         if i is not tagname:
149                                 newtags.append(i)
150                 self.setTags(" ".join(newtags))
151                 self.updateCurrentTagList()
152                 self.updateAllTagList()
153
154
155         def setTags(self,tagstring,service=False,userNotice=True):
156                 if service is False:
157                         serviceRef = self.service
158                 else:
159                         serviceRef = service
160
161                 service_name =serviceRef.toString().split(":")[-1]
162                 filename = service_name+".meta"
163                 metadata = self.readMETAData(filename)
164                 if metadata is not False:
165                         metadata.append(tagstring.strip())
166                         return  self.writeMETAData(filename,metadata)
167                 else:
168                         if userNotice is True:
169                                 self.session.open(MessageBox,_("Can't write movietags, because no meta-file found!"), MessageBox.TYPE_ERROR)
170                         return  False
171
172
173         def readMETAData(self,filename):
174                 if pathExists(filename):
175                         fp = open(filename,"r")
176                         data = []
177                         data.append(fp.readline())
178                         data.append(fp.readline())
179                         data.append(fp.readline())
180                         data.append(fp.readline())
181                         fp.close()
182                         return data
183                 else:
184                         return False
185         def writeMETAData(self,filename,metadata):
186                 if pathExists(filename):
187                         fp = open(filename,"w")
188                         fp.write(metadata[0])
189                         fp.write(metadata[1])
190                         fp.write(metadata[2])
191                         fp.write(metadata[3])
192                         fp.write(metadata[4])
193                         fp.close()
194                         return True
195                 else:
196                         return False
197
198         def clearAllTags(self,yesno):
199                 if yesno is True:
200                         self.serviceHandler = eServiceCenter.getInstance()
201                         root = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + resolveFilename(SCOPE_HDD))
202                         list = self.serviceHandler.list(root)
203                         if list is None:
204                                 pass
205                         else:
206                                 while 1:
207                                         serviceref = list.getNext()
208                                         if not serviceref.valid():
209                                                 break
210                                         if serviceref.flags & eServiceReference.mustDescent:
211                                                 continue
212                                         self.setTags("",service=serviceref,userNotice=False)
213                 self.updateCurrentTagList()
214                 self.updateAllTagList()
215
216         def isUsedTag(self,tag):
217                 try:
218                         self.usedTags.index(tag)
219                         return True
220                 except ValueError:
221                         return False
222
223         def isPreTag(self,tag):
224                 try:
225                         self.pretags.index(tag)
226                         return True
227                 except ValueError:
228                         return False
229
230         def isUserTag(self,tag):
231                 if self.isPreTag(tag) is False and self.isUsedTag(tag) is True:
232                         return True
233                 else:
234                         return False
235
236         def keyRed(self):
237                 if self.currList is self["cTaglist"]:
238                         self.removeTag(self["cTaglist"].getCurrent())
239
240                 elif self.currList is self["aTaglist"]:
241                         print "adding Tag",self["aTaglist"].getCurrent()[0]
242                         self.addTag(self["aTaglist"].getCurrent()[0])
243
244         def keyGreen(self):
245                 if self.currList is self["cTaglist"]:
246                         self.session.openWithCallback(self.newTagEntered,InputBox, title=_('Whitepace will be replaced by "_"'),windowTitle = _("Enter the new Tag"))
247
248         def keyYellow(self):
249                 if  self.currList is self["aTaglist"]:
250                         self.session.openWithCallback(self.clearAllTags,MessageBox,_("Clear all Tags?\n\nThis will delete ALL tags in ALL recodings!\nAre you sure?"), MessageBox.TYPE_YESNO)
251
252         def keyBlue(self):
253                 self.setTitle(' '.join((_("Movie Tagger"), _("Ver."), VERSION)))
254                 self["assignedTags"].setText(_("Assigned Tags"))
255                 self["definedTags"].setText(_("Specified Tags"))
256                 self["usedTag"].setText(_("Used Tag"))
257                 self["userTag"].setText(_("User-specific Tag"))
258                 self["preTag"].setText(_("Predefined Tag"))
259                 if self.currList is self["aTaglist"] or self.currList is None:
260                         self["aTaglist"].selectionEnabled(0)
261                         self["cTaglist"].selectionEnabled(1)
262                         self["buttonred"].setText(_("Remove Tag"))
263                         self["buttongreen"].setText(_("Add new Tag"))
264                         self["buttonyellow"].setText("")
265                         self["buttonblue"].setText(_("Toggle List"))
266                         self.currList = self["cTaglist"]
267                 else:
268                         self["aTaglist"].selectionEnabled(1)
269                         self["cTaglist"].selectionEnabled(0)
270                         self["buttonred"].setText(_("Add Tag"))
271                         self["buttongreen"].setText("")
272                         self["buttonyellow"].setText(_("Clear all Tags"))
273                         self["buttonblue"].setText(_("Toggle List"))
274                         self.currList = self["aTaglist"]
275
276         def up(self):
277                 self.currList.up()
278
279         def down(self):
280                 self.currList.down()
281
282         def left(self):
283                 self.currList.pageUp()
284
285         def right(self):
286                 self.currList.pageDown()
287
288         def newTagEntered(self,newTag):
289                 if newTag >=0:
290                         self.addTag(newTag.strip().replace(" ","_"))
291
292 class TagMenuList(MenuList):
293         def __init__(self, list, enableWrapAround = False):
294                 MenuList.__init__(self, list, enableWrapAround, eListboxPythonMultiContent)
295                 self.l.setFont(0, gFont("Regular", 20))
296                 self.l.setFont(1, gFont("Regular", 25))
297
298         def postWidgetCreate(self, instance):
299                 MenuList.postWidgetCreate(self, instance)
300                 instance.setItemHeight(25)
301
302 def main(session, service, **kwargs):
303         try:
304                 session.open(MovieTagger, service)
305         except Exception,e:
306                 raise e
307
308 def Plugins(path,**kwargs):
309         return PluginDescriptor(name="Movie Tagger", description=_("Movie Tagger..."), where = PluginDescriptor.WHERE_MOVIELIST, fnc=main)