playlistalo.py 11 KB

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