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