~m-buck/+junk/gtk-desktop-info

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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# plugin_common.py is a library of functions common to all plugins
#
#  Author: Kaivalagi
# Created: 14/06/2009
from htmlentitydefs import name2codepoint, codepoint2name
import LyricWiki_services
import codecs
import os
import re
import subprocess
import textwrap
import logging
import traceback

app_name = "gtk-desktop-info"
app_path = os.path.dirname(os.path.abspath(__file__))
module_name = __file__.replace(os.path.dirname (__file__) + "/", "").replace(".pyc","").replace(".py", "")

logger = logging.getLogger(app_name+"."+module_name)

def getTypedValue(value, expectedtype):

    try:
        if len(value.strip(" ")) == 0:
            return None

        elif value.lower() == "true":
            if expectedtype == "boolean":
                return True
            else:
                logger.error("Expected type was '%s', but the value '%s' was given"%(expectedtype, value))

        elif value.lower() == "false":
            if expectedtype == "boolean":
                return False
            else:
                logger.error("Expected type was '%s', but the value '%s' was given"%(expectedtype, value))

        elif isNumeric(value) == True:
            if expectedtype == "integer":
                return int(value)
            else:
                raise

        else:
            return value

    except (TypeError, ValueError):
        raise

def getFormattedDuration(seconds):

    # hours:minutes:seconds
    #hours = int(seconds/3600%60)
    #minutes = int(seconds/60%60)
    #seconds = int(seconds%60)

    #if hours > 0:
    #    output += str(hours).rjust(1,"0")+":"
    #output += str(minutes).rjust(2,"0")+":"+str(seconds).rjust(2,"0")

    # minutes:seconds
    minutes = int(seconds/60)
    seconds = int(seconds%60)

    output = str(minutes).rjust(2,"0")+":"+str(seconds).rjust(2,"0")

    #output = str(int(seconds/3600%60)).rjust(1,"0")+":"+str(int(seconds/60%60)).rjust(1,"0")+":"+str(int(seconds%60)).rjust(2,"0")

    return output

def getHoursMinutesStringFromSeconds(seconds):
    time = int(seconds)
    hours, time = divmod(time, 60*60)
    minutes, seconds = divmod(time, 60)
    output = str(hours).rjust(2,"0") + ":" + str(minutes).rjust(2,"0")
    return output

def removeLineByString(lines,string):

    # define list from multiple lines, to allow remove function
    lineslist = lines.split("\n")
    lineslistchanged = False

    for line in lineslist:
        if line.find(string) <> -1:
            lineslist.remove(line)
            lineslistchanged = True
            break

    if lineslistchanged == True:
        # rebuild lines string from updated list
        lines = "\n".join(lineslist)

    return lines

def getSpaces(spaces):
    string = ""
    for i in range(0, spaces+1):
        string = string + " "
    return string

def getWrappedText(text,width=40,indent=""):
    wrappedtext=""
    for line in textwrap.wrap(text,width=(width-len(indent)),expand_tabs=False,replace_whitespace=False):
        wrappedtext = wrappedtext + "\n" + indent + line
    return wrappedtext


def getHTMLText(text):
    try:
        text = u""+text
    except:
        pass

    try:
        htmlentities = []
        for char in text: #html:
            if ord(char) < 128:
                htmlentities.append(char)
            else:
                htmlentities.append('&%s;' % codepoint2name[ord(char)])
        html = "".join(htmlentities)

        html = html.replace("\n","<br>\n") # switch out new line for html breaks
        return html
    except:
        return text

def getCleanText(html):
    try:
        text = str(html)
        text = text.replace("\n","") # remove new lines from html
        text = text.replace("&apos;","'") # workaround for shitty xml codes not compliant with html
        text = text.replace("<br>","\n") # switch out html breaks for new line
        text = re.sub('<(.|\n)+?>','',text) # remove any html tags
        text =  re.sub('&(%s);' % '|'.join(name2codepoint), lambda m: chr(name2codepoint[m.group(1)]), text)
        return text
    except:
        return html

def isNumeric(string):
    try:
        dummy = float(string)
        return True
    except:
        return False

def addLinkHtml(text):
    try:
        re_url = re.compile(r'''((?:mailto:|ftp://|http://)[^ <>'"{}|\\^`[\]]*)''')
        return re_url.sub(r'<a href="\1">\1</a>', text)
    except:
        return text

def getShellCommandOutput(shell_command):

    proc = subprocess.Popen(shell_command,
                       shell=True,
                       stdout=subprocess.PIPE,
                       )
    output = proc.communicate()[0].rstrip("\n")

    return output

def getLyricsBROKEN(artist, title):
    
    # obtain current conditions data from xoap service
    try:
        url = "http://lyricwiki.org/api.php?artist=%s&song=%s"%(urllib.quote(artist),urllib.quote(title))
        
        logger.info("Fetching lyrics html from " + url)

        usock = urllib2.urlopen(url)
        html = usock.read()
        usock.close()

    except Exception, e:
        logger.error("Server connection error: " + e.__str__()+"\n"+traceback.format_exc())
        return "<p>Failed to retrieve the song lyrics</p>"

    # Extract the lyrics from within the <pre> tags and add html line breaks
    html = re.split(r"<pre>",html)[1] # lose anything <pre> tag and before
    html = re.split(r"</body>",html)[0] # lose anything </html> tag and afters
    lyrics, bottom = re.split(r"</pre>",html) # split off anything </pre> tag and after
            
    lyrics = lyrics.replace("\n","<br>\n") # put in line breaks for lyrics
     
    # output the lyrics and the link at the bottom of the page
    html = lyrics+bottom
    
    return html

def getLyrics(artist, title):

    #currentLyricsFilePath = "/tmp/currentLyrics.txt"
    currentLyricsUrlFilePath = "/tmp/currentLyricsUrl.txt"
    
    if artist == None:
        artist = ""
        
    if title == None:
        title = ""

    #currentLyricsFileExists = os.path.exists(currentLyricsFilePath)
    currentLyricsUrlFileExists = os.path.exists(currentLyricsUrlFilePath)

    songChanged = hasSongChanged(artist, title)

    # get lyrics data if required
    if songChanged == True or currentLyricsUrlFileExists == False:          
        
        try:
            soap = LyricWiki_services.LyricWikiBindingSOAP("http://lyricwiki.org/server.php")
            song = LyricWiki_services.getSongRequest()
            song.Artist = artist
            song.Song = title
            result = soap.getSong(song)
        
        except Exception, e:
            logger.error("SOAP error: " + e.__str__()+"\n"+traceback.format_exc())
            return "<p>Failed to retrieve the song lyrics</p>"
            
        #lyrics = result.Return.Lyrics
        url = result.Return.Url             

        # time to update the url in the file
        try:
            currentLyricsUrlFile = codecs.open(currentLyricsUrlFilePath, mode="w", encoding='utf-8')
        except Exception, e:
            logger.error("Error loading current lyrics file: " + e.__str__()+"\n"+traceback.format_exc())
        else:
                currentLyricsUrlFile.write(url)
        finally:
            currentLyricsUrlFile.close()
        
        # time to update the lyrics in the file
        #try:
        #    currentLyricsFile = codecs.open(currentLyricsFilePath, mode="w", encoding='utf-8')
        #except Exception, e:
        #    logger.error("Error loading current lyrics file: " + e.__str__()+"\n"+traceback.format_exc())
        #else:
        #        currentLyricsFile.write(lyrics)
        #finally:
        #    currentLyricsFile.close()
                        
    else:
        # read what we already have for the url
        try:
            currentLyricsUrlFile = codecs.open(currentLyricsUrlFilePath, mode="r", encoding='utf-8')
        except Exception, e:
            logger.error("Error loading current lyrics file: " + e.__str__()+"\n"+traceback.format_exc())
        else:
            url = currentLyricsUrlFile.read()  
        finally:
            currentLyricsUrlFile.close()
            
        # read what we already have for the lyrics
        #try:
        #    currentLyricsFile = codecs.open(currentLyricsFilePath, mode="r", encoding='utf-8')
        #except Exception, e:
        #    logger.error("Error loading current lyrics file: " + e.__str__()+"\n"+traceback.format_exc())
        #else:
        #    lyrics = currentLyricsFile.read()  
        #finally:
        #    currentLyricsFile.close()
                        
        
    # output the lyrics and the link at the bottom of the page
    #html = "<p>%s</p><br><br><a href=\"%s\">%s</a>"%(lyrics,url,url)
    html = "<a href=\"%s\">Song Lyrics</a>"%(url)
    
    return html

def hasSongChanged(artist, title):

    currentSongFilePath = "/tmp/currentSong.txt"

    currentSong = ""
    songChanged = False
    
    if artist == None:
        artist = ""
        
    if title == None:
        title = ""
        
    currentSongFileExists = os.path.exists(currentSongFilePath)

    # has the song changed
    if currentSongFileExists == True:
        try:
            currentSongFile = codecs.open(currentSongFilePath, mode="r", encoding="utf-8")
        except Exception, e:
            logger.error("Error opening current song file: " + e.__str__()+"\n"+traceback.format_exc())
        else:
            currentSong = currentSongFile.read()

            if currentSong != artist+":"+title:
                songChanged = True
        finally:
            currentSongFile.close()

    if songChanged == True or currentSongFileExists == False:
        
        # write the new song details
        try:
            currentSongFile = codecs.open(currentSongFilePath, mode="w", encoding="utf-8")
        except Exception, e:
            logger.error("Error opening current song file: " + e.__str__()+"\n"+traceback.format_exc())
        else:
            currentSongFile.write(artist+":"+title) 
        finally:
            currentSongFile.close()
            
    return songChanged