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