fix BS if pretagfile does not exists
[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 eServiceReference, 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                 else:
76                         print "pretagsfile",self.pretagfile," does not exists"
77                         self.pretags = []
78
79         def updateCurrentTagList(self):
80                 print "updating cTagList"
81                 self.serviceHandler = eServiceCenter.getInstance()
82                 self.info = self.serviceHandler.info(self.service)
83                 self.tags = self.info.getInfoString(self.service, iServiceInformation.sTags).split(' ')
84                 self.tags.sort()
85                 self["cTaglist"].l.setList(self.tags)
86
87         def updateAllTagList(self):
88                 root = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + resolveFilename(SCOPE_HDD))
89                 ml = MovieList(root)
90                 ml.load(root,None)
91                 xtmp = []
92                 xtmp.extend(ml.tags)
93                 self.usedTags = xtmp
94
95                 e = []+self.pretags
96                 for i in ml.tags:
97                         try:
98                                 self.pretags.index(i)
99                         except ValueError:
100                                 e.append(i)
101
102                 taglist = []
103                 for i in e:
104                                 res = [ i ]
105                                 res.append(MultiContentEntryText(pos=(5, 0), size=(500, 25), font=0, text=i))
106                                 if self.isUsedTag(i):
107                                         res.append(MultiContentEntryText(pos=(220, 0),size=(61, 86), font=1,text="X",color=0x00FFFF00))
108                                 if self.isUserTag(i) :
109                                         res.append(MultiContentEntryText(pos=(240, 0),size=(61, 86), font=1,text="X",color=0x00FF0000))#red
110                                 if self.isPreTag(i):
111                                         res.append(MultiContentEntryText(pos=(260, 0),size=(61, 86), font=1,text="X",color=0x000000FF))#blue
112
113                                 taglist.append(res)
114
115                 taglist.sort()
116                 self["aTaglist"].l.setList(taglist)
117
118         def addTag(self,tagname):
119                 try:
120                         self.tags.index(tagname)
121                 except ValueError:
122                         self.tags.append(tagname)
123                         if len(self.tags) >1:
124                                 self.setTags(" ".join(self.tags))
125                         else:
126                                 self.setTags(tagname)
127                 self.updateCurrentTagList()
128                 self.updateAllTagList()
129
130
131         def removeTag(self,tagname):
132                 newtags = []
133                 for i in self.tags:
134                         if i is not tagname:
135                                 newtags.append(i)
136                 self.setTags(" ".join(newtags))
137                 self.updateCurrentTagList()
138                 self.updateAllTagList()
139
140
141         def setTags(self,tagstring,service=False,userNotice=True):
142                 if service is False:
143                         serviceRef = self.service
144                 else:
145                         serviceRef = service
146
147                 service_name =serviceRef.toString().split(":")[-1]
148                 filename = service_name+".meta"
149                 metadata = self.readMETAData(filename)
150                 if metadata is not False:
151                         metadata.append(tagstring.strip())
152                         return  self.writeMETAData(filename,metadata)
153                 else:
154                         if userNotice is True:
155                                 self.session.open(MessageBox,_("cant write movietags, because no meta-file found!"), MessageBox.TYPE_ERROR)
156                         return  False
157
158
159         def readMETAData(self,filename):
160                 if pathExists(filename):
161                         fp = open(filename,"r")
162                         data = []
163                         data.append(fp.readline())
164                         data.append(fp.readline())
165                         data.append(fp.readline())
166                         data.append(fp.readline())
167                         fp.close()
168                         return data
169                 else:
170                         return False
171         def writeMETAData(self,filename,metadata):
172                 if pathExists(filename):
173                         fp = open(filename,"w")
174                         fp.write(metadata[0])
175                         fp.write(metadata[1])
176                         fp.write(metadata[2])
177                         fp.write(metadata[3])
178                         fp.write(metadata[4])
179                         fp.close()
180                         return True
181                 else:
182                         return False
183
184         def clearAllTags(self,yesno):
185                 if yesno is True:
186                         self.serviceHandler = eServiceCenter.getInstance()
187                         root = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + resolveFilename(SCOPE_HDD))
188                         list = self.serviceHandler.list(root)
189                         tags = set()
190                         if list is None:
191                                 pass
192                         else:
193                                 while 1:
194                                         serviceref = list.getNext()
195                                         if not serviceref.valid():
196                                                 break
197                                         if serviceref.flags & eServiceReference.mustDescent:
198                                                 continue
199                                         self.setTags("",service=serviceref,userNotice=False)
200                 self.updateCurrentTagList()
201                 self.updateAllTagList()
202
203         def isUsedTag(self,tag):
204                 try:
205                         self.usedTags.index(tag)
206                         return True
207                 except ValueError:
208                         return False
209
210         def isPreTag(self,tag):
211                 try:
212                         self.pretags.index(tag)
213                         return True
214                 except ValueError:
215                         return False
216
217         def isUserTag(self,tag):
218                 if self.isPreTag(tag) is False and self.isUsedTag(tag) is True:
219                         return True
220                 else:
221                         return False
222
223         def keyRed(self):
224                 if self.currList is self["cTaglist"]:
225                         self.removeTag(self["cTaglist"].getCurrent())
226
227                 elif self.currList is self["aTaglist"]:
228                         print "adding Tag",self["aTaglist"].getCurrent()[0]
229                         self.addTag(self["aTaglist"].getCurrent()[0])
230
231         def keyGreen(self):
232                 if self.currList is self["cTaglist"]:
233                         self.session.openWithCallback(self.newTagEntered,InputBox, title=_("Whitepace will be replaced by Underscore"),windowTitle = _("enter the new Tag"))
234
235         def keyYellow(self):
236                 if  self.currList is self["aTaglist"]:
237                         self.session.openWithCallback(self.clearAllTags,MessageBox,_("clear all Tags?\n\nThis will delete ALL tags in ALL recodings!\nAre you sure?"), MessageBox.TYPE_YESNO)
238
239         def keyBlue(self):
240                 if self.currList is self["aTaglist"] or self.currList is None:
241                         self["aTaglist"].selectionEnabled(0)
242                         self["cTaglist"].selectionEnabled(1)
243                         self["buttonred"].setText(_("remove Tag"))
244                         self["buttongreen"].setText(_("add new Tag"))
245                         self["buttonyellow"].setText("")
246                         self["buttonblue"].setText(_("toggle List"))
247                         self.currList = self["cTaglist"]
248                 else:
249                         self["aTaglist"].selectionEnabled(1)
250                         self["cTaglist"].selectionEnabled(0)
251                         self["buttonred"].setText(_("add Tag"))
252                         self["buttongreen"].setText("")
253                         self["buttonyellow"].setText("clear all Tags")
254                         self["buttonblue"].setText(_("toggle List"))
255                         self.currList = self["aTaglist"]
256
257         def up(self):
258                 self.currList.up()
259
260         def down(self):
261                 self.currList.down()
262
263         def left(self):
264                 self.currList.pageUp()
265
266         def right(self):
267                 self.currList.pageDown()
268
269         def newTagEntered(self,newTag):
270                 if newTag >=0:
271                         self.addTag(newTag.strip().replace(" ","_"))
272
273 class TagMenuList(MenuList, HTMLComponent, GUIComponent):
274     def __init__(self, list):
275         MenuList.__init__(self,list)
276         GUIComponent.__init__(self)
277         self.l = eListboxPythonMultiContent()
278         self.list = list
279         self.l.setList(list)
280         self.l.setFont(0, gFont("Regular", 20))
281         self.l.setFont(1, gFont("Regular", 25))
282
283     GUI_WIDGET = eListbox
284
285     def postWidgetCreate(self, instance):
286         instance.setContent(self.l)
287         instance.setItemHeight(25)
288
289 def main(session, service, **kwargs):
290         try:
291                 session.open(MovieTagger, service)
292         except Exception,e:
293                 raise e
294
295 def Plugins(path,**kwargs):
296         return PluginDescriptor(name="Movie Tagger", description=_("Movie Tagger..."), where = PluginDescriptor.WHERE_MOVIELIST, fnc=main)