Browse Source

new functions: add, addurl, listtot, consume

itec 4 years ago
parent
commit
0a81f0fa2d
3 changed files with 67 additions and 49 deletions
  1. 2 2
      pl_add.py
  2. 10 0
      pl_addurl.py
  3. 55 47
      playlistalo.py

+ 2 - 2
pl_add.py

@@ -5,6 +5,6 @@ import playlistalo
 import sys
 
 if __name__ == '__main__':
-    url = sys.argv[1]
+    file = sys.argv[1]
     user = sys.argv[2]
-    print (playlistalo.add(url, user))
+    print (playlistalo.add(file, user))

+ 10 - 0
pl_addurl.py

@@ -0,0 +1,10 @@
+#!/usr/bin/env python3
+#Aggiunge un file in playlist
+
+import playlistalo
+import sys
+
+if __name__ == '__main__':
+    url = sys.argv[1]
+    user = sys.argv[2]
+    print (playlistalo.addurl(url, user))

+ 55 - 47
playlistalo.py

@@ -13,6 +13,8 @@ import time
 import subprocess
 import random
 import configparser
+import hashlib
+
 from musicpd import MPDClient
 
 from telegram.ext import Updater, MessageHandler, Filters
@@ -21,14 +23,10 @@ from mastodon import Mastodon, StreamListener
 scriptpath = os.path.dirname(os.path.realpath(__file__))
 
 #Crea le cartelle
-if not os.path.exists("playlist"):
-    os.makedirs("playlist")
-if not os.path.exists("cache"):
-    os.makedirs("cache")
-if not os.path.exists("fallback"):
-    os.makedirs("fallback")
-if not os.path.exists("archive"):
-    os.makedirs("archive")
+os.makedirs("playlist", exist_ok=True)
+os.makedirs("cache", exist_ok=True)
+os.makedirs("fallback", exist_ok=True)
+os.makedirs("archive", exist_ok=True)
 
 #Scrivi la prima configurazione
 configfile = 'playlistalo.conf'
@@ -53,7 +51,7 @@ MASTODON_URL = playlistaloconf.get('Mastodon_url')
 
 
 
-def add(url, user = "-unknown-"):
+def addurl(url, user = "-unknown-"):
     #print ('--- Inizio ---')
 
     ydl_opts = {
@@ -100,13 +98,28 @@ def add(url, user = "-unknown-"):
     if not os.path.isfile(filetemp):
         return("Err: file non scaricato")
 
+    return(add(filetemp, user, title, id))
+
+
+def md5(fname):
+    hash_md5 = hashlib.md5()
+    with open(fname, "rb") as f:
+        for chunk in iter(lambda: f.read(4096), b""):
+            hash_md5.update(chunk)
+    return hash_md5.hexdigest()
+
+def add(filetemp, user = "-unknown-", title = None, id = None):
+    if not id:
+        id = md5(filetemp)
+    if not title:
+        title = os.path.splitext(os.path.basename(filetemp))[0]
+
     #se il file esiste gia' in playlist salto (potrebbe esserci, anche rinominato)
     if glob("playlist/**/*|" + id + ".*"):
          print ('--- File già presente ---')
          return ("Err: %s [%s] già presente" %(title, id))
 
-    if not os.path.exists("playlist/" + user):
-        os.makedirs("playlist/" + user)
+    os.makedirs("playlist/" + user, exist_ok=True)
     #qui compone il nome del file
     if SHUFFLESONGS:
         fileout = str(random.randrange(10**6)).zfill(14) + "|" + title + "|" + id + ".m4a"
@@ -203,42 +216,15 @@ def listfallback():
     return pl2
 
 
-def playsingle():
-    pl = listplaylist()
-    #print ('\n'.join([x[0] for x in pl]))
-
-    if pl:
-        firstsong = pl[0][0]
-        print (firstsong)
-        #qui fa play
-        subprocess.call(["mplayer", "-nolirc", "-msglevel", "all=0:statusline=5", firstsong])
-        #alla fine consuma
-        os.rename(firstsong, "archive/" + os.path.basename(firstsong))
-        #se non ci sono + file cancella la cartella
-        if not glob(os.path.dirname(firstsong) + "/*.m4a"):
-            shutil.rmtree(os.path.dirname(firstsong))
-        else:
-            with open(os.path.dirname(firstsong) + "/last", "w") as f:
-                f.write(time.strftime("%Y%m%d%H%M%S"))
-    else:
-        #usa il fallback
-        #eventualmente aggiungere file di avviso con istruzioni veloci
-        plf = listfallback()
-        #print ('\n'.join([x[0] for x in plf]))
-        if plf:
-            firstsong = plf[0][0]
-            print (firstsong)
-            #qui fa play
-            subprocess.call(["mplayer", "-nolirc", "-msglevel", "all=0:statusline=5", firstsong])
-            #alla fine consuma
-            fname =  time.strftime("%Y%m%d%H%M%S") + "|" + "|".join(os.path.basename(firstsong).split("|")[1:])
-            fname = os.path.dirname(firstsong) + "/" + fname
-            os.rename(firstsong, fname)
-
-
 def playloop():
     while True:
-        playsingle()
+        plt = listtot(1)
+        if plt:
+            song = plt[0]
+            print(song)
+            #qui fa play
+            subprocess.call(["mplayer", "-nolirc", "-msglevel", "all=0:statusline=5", song])
+            consume(song)
 
 def clean():
     #cancella tutto dalla playlist
@@ -291,7 +277,7 @@ def telegram_msg_parser(bot, update):
     for url in urls:
         #update.message.reply_text("Scarico %s" %(url))
         # start the download
-        dl = add(url, user)
+        dl = addurl(url, user)
         update.message.reply_text(dl)
 
 
@@ -340,7 +326,7 @@ class MastodonListener(StreamListener):
         
         for url in urls:
             # start the download
-            dl = add(url, user)
+            dl = addurl(url, user)
             self.mastodon.status_post("@" + username + " " + dl, in_reply_to_id = statusid, visibility="direct")
 
 
@@ -351,6 +337,28 @@ def mastodon_bot():
     mastodon.stream_user(listener)
 
 
+def listtot(res = sys.maxsize):
+    plt = listplaylist()
+    if len(plt) < res:
+        [plt.append(x) for x in listfallback()]
+    return plt[:res]
+
+
+def consume(song):
+    if os.path.split(song)[0] == "playlist":
+        os.remove(song)
+        if not [x for x in glob(os.path.dirname(song) + "/*") if not os.path.basename(x) == "last"]:
+            shutil.rmtree(os.path.dirname(song))
+        else:
+            with open(os.path.dirname(song) + "/last", "w") as f:
+                f.write(time.strftime("%Y%m%d%H%M%S"))
+    
+    elif os.path.split(song)[0] == "fallback":
+        fname =  time.strftime("%Y%m%d%H%M%S") + "|" + "|".join(os.path.basename(song).split("|")[1:])
+        fname = os.path.dirname(song) + "/" + fname
+        os.rename(song, fname)
+
+