summaryrefslogtreecommitdiffstats
path: root/amarok/src/scripts/amarok_live/amarok_live.py
blob: cf7313694f5104f1e78b959ea7c29f0a2688dfdf (plain)
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
#!/usr/bin/env python

############################################################################
# Python wrapper script for running the Amarok LiveCD remastering scripts
# from within Amarok.  Based on the Python-Qt template script for Amarok
# (c) 2005 Mark Kretschmann <markey@web.de>
# 
# (c) 2005 Leo Franchi <lfranchi@gmail.com>
#
# Depends on: Python 3, PyTQt
############################################################################
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
############################################################################

import configparser
import os
import sys
import threading
import signal
from time import sleep

try:
    from TQt.qt import *
except:
    os.popen( "kdialog --sorry 'PyTQt (TQt bindings for Python) is required for this script.'" )
    raise


# Replace with real name
debug_prefix = "LiveCD Remastering"


class ConfigDialog ( TQDialog ):
    """ Configuration widget """

    def __init__( self ):
        TQDialog.__init__( self )
        self.setWFlags( TQt.WDestructiveClose )
        self.setCaption("Amarok Live! Configuration")

        self.lay = TQGridLayout( self, 3, 2)

        self.lay.addColSpacing( 0, 300 )

        self.isopath = TQLineEdit( self )
        self.isopath.setText( "Path to Amarok Live! iso" )
        self.tmppath = TQLineEdit( self )
        self.tmppath.setText( "Temporary directory used, 2.5gb free needed" )

        self.lay.addWidget( self.isopath, 0, 0 )
        self.lay.addWidget( self.tmppath, 1, 0 )

        self.isobutton = TQPushButton( self )
        self.isobutton.setText("Browse..." )
        self.tmpbutton = TQPushButton( self )
        self.tmpbutton.setText("Browse..." )

        self.cancel = TQPushButton( self )
        self.cancel.setText( "Cancel" )
        self.ok = TQPushButton( self )
        self.ok.setText( "Ok" )

        self.lay.addWidget( self.isobutton, 0, 1 )
        self.lay.addWidget( self.tmpbutton, 1, 1 )
        self.lay.addWidget( self.cancel, 2, 1 )
        self.lay.addWidget( self.ok, 2, 0)

        self.connect( self.isobutton, SIGNAL( "clicked()" ), self.browseISO )
        self.connect( self.tmpbutton, SIGNAL( "clicked()" ), self.browsePath )

        self.connect( self.ok, SIGNAL( "clicked()" ), self.save )
        self.connect( self.ok, SIGNAL( "clicked()" ), self.unpack )
#        self.connect( self.ok, SIGNAL( "clicked()" ), self.destroy )
        self.connect( self.cancel, SIGNAL( "clicked()" ), self, SLOT("reject()") )

        self.adjustSize()

        path = None
        try:
            config = configparser.ConfigParser()
            config.read( "remasterrc" )
            path = config.get( "General", "path" )
            iso = config.get( "General", "iso")

            if not path == "": self.tmppath.setText(path)
            if not iso == "": self.isopath.setText(iso)
        except:
            pass



    def save( self ):
        """ Saves configuration to file """
        self.file = file( "remasterrc", 'w' )
        self.config = configparser.ConfigParser()
        self.config.add_section( "General" )
        self.config.set( "General", "path", self.tmppath.text() )
        self.config.set( "General", "iso", self.isopath.text() )
        self.config.write( self.file )
        self.file.close()

        self.accept()

    def clear():

        self.file = file( "remasterrc", 'w' )
        self.config = configparser.ConfigParser()
        self.config.add_section( "General" )
        self.config.set( "General", "path", ""  )
        self.config.set( "General", "iso", "" )
        self.config.write( self.file )
        self.file.close()

    def browseISO( self ):

        path = TQFileDialog.getOpenFileName( "/home",
                                                 "CD Images (*.iso)",
                                                 self,
                                                 "iso choose dialogr",
                                                 "Choose ISO to remaster")
        self.isopath.setText( path )

    def browsePath( self ):

        tmp = TQFileDialog.getExistingDirectory( "/home",
                                                self,
                                                "get tmp dir",
                                                "Choose working directory",
                                                1)
        self.tmppath.setText( tmp )


    def unpack( self ):

        # now the fun part, we run part 1
        fd = os.popen("tde-config --prefix", "r")
        tdedir = fd.readline()
        tdedir = tdedir.strip()
        scriptdir = tdedir + "/share/apps/amarok/scripts/amarok_live"
        fd.close()

        path, iso = self.readConfig()
        os.system("tdesu -t sh %s/amarok.live.remaster.part1.sh %s %s" % (scriptdir, path, iso))
        #os.wait()
        print("got path: %s" % path)




    def readConfig( self ) :
        path = ""
        iso = ""
        try:
            config = configparser.ConfigParser()
            config.read("remasterrc")
            path = config.get("General", "path")
            iso = config.get("General", "iso")
        except:
            pass
        return (path, iso)



class Notification( TQCustomEvent ):
    __super_init = TQCustomEvent.__init__
    def __init__( self, str ):

        self.__super_init(TQCustomEvent.User + 1)
        self.eventStr = str

class Remasterer( TQApplication ):
    """ The main application, also sets up the TQt event loop """

    def __init__( self, args ):
        TQApplication.__init__( self, args )
        debug( "Started." )

        # Start separate thread for reading data from stdin
        self.stdinReader = threading.Thread( target = self.readStdin )
        self.stdinReader.start()

        self.readSettings()

        # ugly hack, thanks mp8 anyway
        os.system("dcop amarok script removeCustomMenuItem \"Amarok live\" \"Add playlist to livecd\"")
        os.system("dcop amarok script removeCustomMenuItem \"Amarok live\" \"Add selected to livecd\"")
        os.system("dcop amarok script removeCustomMenuItem \"Amarok live\" \"Create Remastered CD\"")
        os.system("dcop amarok script removeCustomMenuItem \"Amarok live\" \"Clear Music on livecd\"")

        os.system("dcop amarok script addCustomMenuItem \"Amarok live\" \"Add playlist to livecd\"")
        os.system("dcop amarok script addCustomMenuItem \"Amarok live\" \"Add selected to livecd\"")
        os.system("dcop amarok script addCustomMenuItem \"Amarok live\" \"Create Remastered CD\"")
        os.system("dcop amarok script addCustomMenuItem \"Amarok live\" \"Clear Music on livecd\"")


    def readSettings( self ):
        """ Reads settings from configuration file """

        try:
            path = config.get( "General", "path" )

        except:
            debug( "No config file found, using defaults." )


############################################################################
# Stdin-Reader Thread
############################################################################

    def readStdin( self ):
        """ Reads incoming notifications from stdin """

        while True:
            # Read data from stdin. Will block until data arrives.
            line = sys.stdin.readline()

            if line:
                tqApp.postEvent( self, Notification(line) )
            else:
                break


############################################################################
# Notification Handling
############################################################################

    def customEvent( self, notification ):
        """ Handles notifications """

        eventStr = TQString(notification.eventStr)
        debug( "Received notification: " + str( eventStr ) )

        if eventStr.contains( "configure" ):
            self.configure()
        if eventStr.contains( "stop" ):
            self.stop()

        elif eventStr.contains( "customMenuClicked" ):
            if eventStr.contains( "selected" ):
                self.copyTrack( eventStr )
            elif eventStr.contains( "playlist" ):
                self.copyPlaylist()
            elif eventStr.contains( "Create" ):
                self.createCD()
            elif eventStr.contains( "Clear" ):
                self.clearCD()


# Notification callbacks. Implement these functions to react to specific notification
# events from Amarok:

    def configure( self ):
        debug( "configuration" )

        self.dia = ConfigDialog()
        self.dia.show()
        #self.connect( self.dia, SIGNAL( "destroyed()" ), self.readSettings )

    def clearCD( self ):

        self.dia = ConfigDialog()
        path, iso = self.dia.readConfig()

        os.system("rm -rf %s/amarok.live/music/* %s/amarok.live/playlist/* %s/amarok.live/home/amarok/.trinity/share/apps/amarok/current.xml" % (path, path, path))

    def onSignal( self, signum, stackframe ):
        stop()

    def stop( self ):

        fd = open("/tmp/amarok.stop", "w")
        fd.write( "stopping")
        fd.close()

        os.system("dcop amarok script removeCustomMenuItem \"Amarok live\" \"Add playlist to livecd\"")
        os.system("dcop amarok script removeCustomMenuItem \"Amarok live\" \"Add selected to livecd\"")
        os.system("dcop amarok script removeCustomMenuItem \"Amarok live\" \"Create Remastered CD\"")
        os.system("dcop amarok script removeCustomMenuItem \"Amarok live\" \"Clear Music on livecd\"")


    def copyPlaylist( self ):

        self.dia = ConfigDialog()
        path, iso = self.dia.readConfig()
        if path == "":
            os.system("dcop amarok playlist popupMessage 'Please run configure first.'")
            return

        tmpfileloc = os.tmpnam()
        os.system("dcop amarok playlist saveM3u '%s' false" % tmpfileloc)
        tmpfile = open(tmpfileloc)

        import urllib.request, urllib.parse, urllib.error

        files = ""
        m3u = ""
        for line in tmpfile.readlines():
            if line[0] != "#":

                line = line.strip()

                # get filename
                name = line.split("/")[-1]

                #make url
                url = "file://" + urllib.parse.quote(line)

                #make path on livecd
                livecdpath = "/music/" + name

                files += url + " "
                m3u += livecdpath + "\n"

        tmpfile.close()

        files = files.strip()

        os.system("kfmclient copy %s file://%s/amarok.live/music/" % (files, path))

        import random
        suffix = random.randint(0,10000)
#        os.system("mkdir %s/amarok.live/home/amarok/.trinity/share/apps/amarok/playlists/" % path)
        m3uOut = open("/tmp/amarok.live.%s.m3u" % suffix, 'w')

        m3u = m3u.strip()
        m3uOut.write(m3u)

        m3uOut.close()

        os.system("mv /tmp/amarok.live.%s.m3u %s/amarok.live/playlist/" % (suffix,path))
        os.system("rm /tmp/amarok.live.%s.m3u" % suffix)


        os.remove(tmpfileloc)

    def copyTrack( self, menuEvent ):

        event = str( menuEvent )
        debug( event )
        self.dia = ConfigDialog()

        path,iso = self.dia.readConfig()
        if path == "":
            os.system("kdialog --sorry 'You have not specified where the Amarok live iso is. Please click configure and do so first.'")
        else:
            # get the list of files. yes, its ugly. it works though.
            #files =  event.split(":")[-1][2:-1].split()[2:]
            #trying out a new one 
         #files = event.split(":")[-1][3:-2].replace("\"Amarok live!\" \"add to livecd\" ", "").split("\" \"")
            #and another

            files = event.replace("customMenuClicked: Amarok live Add selected to livecd", "").split()

            allfiles = ""
            for file in files:
                allfiles += file + " "
            allfiles = allfiles.strip()
            os.system("kfmclient copy %s file://%s/amarok.live/music/" % (allfiles, path))

    def createCD( self ):

        self.dia = ConfigDialog()
        path,iso = self.dia.readConfig()
        if path == "":
            os.system("kdialog --sorry 'You have not configured Amarok live! Please run configure.")

        fd = os.popen("tde-config --prefix", "r")
        tdedir = fd.readline()
        tdedir = tdedir.strip()
        scriptdir = tdedir + "/share/apps/amarok/scripts/amarok_live"
        fd.close()

        os.system("tdesu sh %s/amarok.live.remaster.part2.sh %s" % (scriptdir, path))

        fd = open("/tmp/amarok.script", 'r')
        y = fd.readline()
        y = y.strip()
        if y == "end": # user said no more, clear path
            self.dia.clear()
        fd.close()


############################################################################

def onSignal( signum, stackframe ):
    fd = open("/tmp/amarok.stop", "w")
    fd.write( "stopping")
    fd.close()

    print('STOPPING')

    os.system("dcop amarok script removeCustomMenuItem \"Amarok live\" \"Add playlist to livecd\"")
    os.system("dcop amarok script removeCustomMenuItem \"Amarok live\" \"Add selected to livecd\"")
    os.system("dcop amarok script removeCustomMenuItem \"Amarok live\" \"Create Remastered CD\"")
    os.system("dcop amarok script removeCustomMenuItem \"Amarok live\" \"Clear Music on livecd\"")


def debug( message ):
    """ Prints debug message to stdout """

    print(debug_prefix + " " + message)

def main():
    app = Remasterer( sys.argv )

    # not sure if it works or not...  playing it safe
    dia = ConfigDialog()

    app.exec_loop()

if __name__ == "__main__":

    mainapp = threading.Thread(target=main)
    mainapp.start()
    signal.signal(15, onSignal)
    print(signal.getsignal(15))
    while 1: sleep(120)

    #main( sys.argv )