playlistalo.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. #!/usr/bin/env python3
  2. #Playlistalo - simpatico script che legge le cartelle e genera la playlist
  3. import youtube_dl
  4. import shutil
  5. import sys
  6. import re
  7. import os
  8. import validators
  9. from glob import glob
  10. import json
  11. import time
  12. import subprocess
  13. import random
  14. import configparser
  15. import hashlib
  16. from musicpd import MPDClient
  17. from telegram.ext import Updater, MessageHandler, Filters
  18. from mastodon import Mastodon, StreamListener
  19. scriptpath = os.path.dirname(os.path.realpath(__file__))
  20. #Crea le cartelle
  21. os.makedirs("playlist", exist_ok=True)
  22. os.makedirs("cache", exist_ok=True)
  23. os.makedirs("fallback", exist_ok=True)
  24. os.makedirs("archive", exist_ok=True)
  25. #Scrivi la prima configurazione
  26. configfile = 'playlistalo.conf'
  27. if not os.path.exists(configfile):
  28. config = configparser.ConfigParser()
  29. config['playlistalo'] = {'ShuffleUsers': False, 'ShuffleSongs': False, 'ShuffleFallback': False, 'Telegram_token': "", 'Mastodon_token': "", 'Mastodon_url': ""}
  30. with open(configfile, 'w') as f:
  31. config.write(f)
  32. #Leggi la configurazione
  33. config = configparser.ConfigParser()
  34. config.read(configfile)
  35. playlistaloconf = config['playlistalo']
  36. SHUFFLEUSERS = playlistaloconf.getboolean('ShuffleUsers')
  37. SHUFFLESONGS = playlistaloconf.getboolean('ShuffleSongs')
  38. SHUFFLEFALLBACK = playlistaloconf.getboolean('ShuffleFallback')
  39. TELEGRAM_TOKEN = playlistaloconf.get('Telegram_token')
  40. MASTODON_TOKEN = playlistaloconf.get('Mastodon_token')
  41. MASTODON_URL = playlistaloconf.get('Mastodon_url')
  42. def addurl(url, user = "-unknown-"):
  43. #print ('--- Inizio ---')
  44. ydl_opts = {
  45. 'format': 'bestaudio[ext=m4a]',
  46. 'outtmpl': 'cache/%(id)s.m4a',
  47. 'noplaylist': True,
  48. 'quiet': True,
  49. }
  50. url = url.strip()
  51. print ("url: " + url)
  52. print ("user: " + user)
  53. if not validators.url(url):
  54. print ('--- URL malformato ---')
  55. return ("Err: url non valido")
  56. with youtube_dl.YoutubeDL(ydl_opts) as ydl:
  57. try:
  58. meta = ydl.extract_info(url, download = False)
  59. except youtube_dl.DownloadError as detail:
  60. print ('--- Errore video non disponibile ---')
  61. print(str(detail))
  62. return ("Err: " + str(detail))
  63. id = meta.get('id').strip()
  64. title = __normalizetext(meta.get('title'))
  65. print ('id: %s' %(id))
  66. print ('title: %s' %(title))
  67. #scrivo il json
  68. with open(os.path.join("cache", id + ".json"), 'w') as outfile:
  69. json.dump(meta, outfile, indent=4)
  70. #ho letto le info, ora controllo se il file esiste altrimenti lo scarico
  71. #miglioria: controllare se upload_date e' uguale a quella del json gia' esistente
  72. filetemp = os.path.join("cache", id + ".m4a")
  73. if not glob(filetemp):
  74. print ('--- Scarico ---')
  75. ydl.download([url]) #non ho capito perche' ma senza [] fa un carattere per volta
  76. if not os.path.isfile(filetemp):
  77. return("Err: file non scaricato")
  78. return(add(filetemp, user, title, id))
  79. def md5(fname):
  80. hash_md5 = hashlib.md5()
  81. with open(fname, "rb") as f:
  82. for chunk in iter(lambda: f.read(4096), b""):
  83. hash_md5.update(chunk)
  84. return hash_md5.hexdigest()
  85. def add(filetemp, user = "-unknown-", title = None, id = None):
  86. if not id:
  87. id = md5(filetemp)
  88. if not title:
  89. title = os.path.splitext(os.path.basename(filetemp))[0]
  90. #se il file esiste gia' in playlist salto (potrebbe esserci, anche rinominato)
  91. if glob("playlist/**/*|" + id + ".*"):
  92. print ('--- File già presente ---')
  93. return ("Err: %s [%s] già presente" %(title, id))
  94. os.makedirs("playlist/" + user, exist_ok=True)
  95. #qui compone il nome del file
  96. if SHUFFLESONGS:
  97. fileout = str(random.randrange(10**6)).zfill(14) + "|" + title + "|" + id + ".m4a"
  98. else:
  99. fileout = time.strftime("%Y%m%d%H%M%S") + "|" + title + "|" + id + ".m4a"
  100. fileout = os.path.join("playlist/" + user, fileout)
  101. print ('--- Converto ---')
  102. print (fileout)
  103. subprocess.call([scriptpath + "/trimaudio.sh", filetemp, fileout])
  104. if not os.path.isfile(fileout):
  105. return("Err: file non convertito")
  106. #cerca la posizione del pezzo appena inserito
  107. pos = getposition(fileout)
  108. print ('--- Fine ---')
  109. print ("")
  110. return ("OK: %s [%s] aggiunto alla playlist in posizione #%s" %(title, id, pos))
  111. def __normalizetext(s):
  112. if s is None:
  113. return None
  114. else:
  115. s = re.sub(r'[\\|/|:|*|?|"|<|>|\|]',r'',s)
  116. s = " ".join(s.split())
  117. return s
  118. def listplaylist():
  119. pl = []
  120. pl2 = []
  121. for udir in sorted(glob("playlist/*/")):
  122. #print (udir)
  123. user = os.path.basename(os.path.dirname(udir))
  124. #cerca il file last
  125. last = ""
  126. if os.path.exists(udir + "/last"):
  127. f = open(udir + "/last", "r")
  128. last = f.readline().rstrip()
  129. else:
  130. last = os.path.basename(sorted(glob(udir + "/*.m4a"))[0]).split("|")[0]
  131. #print ("LAST: " + last)
  132. #leggi i file nella cartella
  133. files = sorted(glob(udir + "/*.m4a"))
  134. seq = 0
  135. for file in files:
  136. bn = os.path.splitext(os.path.basename(file))[0]
  137. #print ("BASENAME: " + bn)
  138. seq = seq + 1
  139. dat = bn.split("|")[0]
  140. nam = bn.split("|")[1]
  141. cod = bn.split("|")[2]
  142. key = "-".join([str(seq).zfill(5), last, dat])
  143. #print ("KEY: " + key)
  144. plsong = [key, file, user, nam, cod]
  145. pl.append(plsong)
  146. pl.sort()
  147. #rimuove la prima colonna, che serve solo per l'ordinamento
  148. pl2 = [x[1:] for x in pl]
  149. #print (pl)
  150. #print ('\n'.join([", ".join(x) for x in pl]))
  151. #print ('\n'.join([x[0] for x in pl]))
  152. return pl2
  153. def listfallback():
  154. pl = []
  155. pl2 = []
  156. #leggi i file nella cartella
  157. files = sorted(glob("fallback/*.m4a"))
  158. seq = 0
  159. for file in files:
  160. bn = os.path.splitext(os.path.basename(file))[0]
  161. seq = seq + 1
  162. dat = bn.split("|")[0]
  163. nam = bn.split("|")[1]
  164. cod = bn.split("|")[2]
  165. key = "-".join([str(seq).zfill(5), dat])
  166. plsong = [key, file, "fallback", nam, cod]
  167. pl.append(plsong)
  168. pl.sort()
  169. #rimuove la prima colonna, che serve solo per l'ordinamento
  170. pl2 = [x[1:] for x in pl]
  171. return pl2
  172. def playloop():
  173. while True:
  174. plt = listtot(1)
  175. if plt:
  176. song = plt[0]
  177. print(song)
  178. #qui fa play
  179. subprocess.call(["mplayer", "-nolirc", "-msglevel", "all=0:statusline=5", song])
  180. consume(song)
  181. def clean():
  182. #cancella tutto dalla playlist
  183. shutil.rmtree("playlist")
  184. os.makedirs("playlist")
  185. def shuffleusers():
  186. #scrivere un numero casuale dentro a tutti i file last
  187. for udir in sorted(glob("playlist/*/")):
  188. #print (udir)
  189. with open(udir + "/last", "w") as f:
  190. f.write(str(random.randrange(10**6)).zfill(14))
  191. def shufflefallback():
  192. #rinominare con un numero casuale i file in fallback
  193. files = sorted(glob("fallback/*.m4a"))
  194. for file in files:
  195. fname = str(random.randrange(10**6)).zfill(14) + "|" + "|".join(os.path.basename(file).split("|")[1:])
  196. fname = os.path.dirname(file) + "/" + fname
  197. os.rename(file, fname)
  198. def getposition(file):
  199. pl = listplaylist()
  200. try:
  201. return([x[0] for x in pl].index(file) + 1)
  202. except:
  203. pass
  204. def telegram_msg_parser(bot, update):
  205. print("Messaggio ricevuto")
  206. msg = update.message.text
  207. id = str(update.message.from_user.id)
  208. username = update.message.from_user.username
  209. urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', msg)
  210. user = "t_" + "-".join([i for i in [id, username] if i])
  211. #print (urls)
  212. #print (user)
  213. if not urls:
  214. update.message.reply_text("Non ho trovato indirizzi validi...")
  215. return()
  216. update.message.reply_text("Messaggio ricevuto. Elaboro...")
  217. for url in urls:
  218. #update.message.reply_text("Scarico %s" %(url))
  219. # start the download
  220. dl = addurl(url, user)
  221. update.message.reply_text(dl)
  222. def telegram_bot():
  223. print ("Bot avviato")
  224. # Create the EventHandler and pass it your bot's token.
  225. updater = Updater(TELEGRAM_TOKEN)
  226. # Get the dispatcher to register handlers
  227. dp = updater.dispatcher
  228. # parse message
  229. dp.add_handler(MessageHandler(Filters.text, telegram_msg_parser))
  230. # Start the Bot
  231. updater.start_polling()
  232. # Run the bot until you press Ctrl-C
  233. updater.idle()
  234. class MastodonListener(StreamListener):
  235. # andiamo a definire il metodo __init__, che prende una istanza di Mastodon come parametro opzionale e lo setta nella prop. self.mastodon
  236. def __init__(self, mastodonInstance=None):
  237. self.mastodon = mastodonInstance
  238. def on_notification(self, notification):
  239. print("Messaggio ricevuto")
  240. #try:
  241. msg = notification["status"]["content"]
  242. id = str(notification["account"]["id"])
  243. username = notification["account"]["acct"]
  244. #except KeyError:
  245. # return
  246. msg = msg.replace("<br>", "\n")
  247. msg = re.compile(r'<.*?>').sub('', msg)
  248. urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', msg)
  249. user = "m_" + "-".join([i for i in [id, username] if i])
  250. #print (urls)
  251. #print (user)
  252. #visibility = notification['status']['visibility']
  253. statusid = notification['status']['id']
  254. if not urls:
  255. self.mastodon.status_post("@" + username + " " + "Non ho trovato indirizzi validi...", in_reply_to_id = statusid, visibility="direct")
  256. return()
  257. self.mastodon.status_post("@" + username + " " + "Messaggio ricevuto. Elaboro...", in_reply_to_id = statusid, visibility="direct")
  258. for url in urls:
  259. # start the download
  260. dl = addurl(url, user)
  261. self.mastodon.status_post("@" + username + " " + dl, in_reply_to_id = statusid, visibility="direct")
  262. def mastodon_bot():
  263. print ("Bot avviato")
  264. mastodon = Mastodon(access_token = MASTODON_TOKEN, api_base_url = MASTODON_URL)
  265. listener = MastodonListener(mastodon)
  266. mastodon.stream_user(listener)
  267. def listtot(res = sys.maxsize):
  268. plt = listplaylist()
  269. if len(plt) < res:
  270. [plt.append(x) for x in listfallback()]
  271. return plt[:res]
  272. def consume(song):
  273. if os.path.split(song)[0] == "playlist":
  274. os.remove(song)
  275. if not [x for x in glob(os.path.dirname(song) + "/*") if not os.path.basename(x) == "last"]:
  276. shutil.rmtree(os.path.dirname(song))
  277. else:
  278. with open(os.path.dirname(song) + "/last", "w") as f:
  279. f.write(time.strftime("%Y%m%d%H%M%S"))
  280. elif os.path.split(song)[0] == "fallback":
  281. fname = time.strftime("%Y%m%d%H%M%S") + "|" + "|".join(os.path.basename(song).split("|")[1:])
  282. fname = os.path.dirname(song) + "/" + fname
  283. os.rename(song, fname)
  284. if __name__ == '__main__':
  285. print ("This is a package, use other commands to run it")