Skip to content

Instantly share code, notes, and snippets.

@b7w
Created June 29, 2013 09:32
Show Gist options
  • Save b7w/5890524 to your computer and use it in GitHub Desktop.
Save b7w/5890524 to your computer and use it in GitHub Desktop.
Radioma BTSync
# -*- coding: utf-8 -*-
from datetime import datetime
import os
import shutil
import baker
class Podcast(object):
def __init__(self, file_path, link_provider=None):
self.file_path = file_path
self._link_provider = link_provider
def creation_date(self):
#TODO: get from mp3 tags?
t = os.path.getctime(self.file_path)
return datetime.fromtimestamp(t)
def _abs_path(self, root, path_format=None):
file_name = os.path.basename(self.file_path)
if path_format:
path = path_format.format(time=self.creation_date())
return os.path.abspath(os.path.join(root, path, file_name))
return os.path.abspath(os.path.join(root, file_name))
def link_to(self, root, path_format=None):
link_path = self._abs_path(root, path_format)
os.makedirs(os.path.dirname(link_path), exist_ok=True)
if not os.path.lexists(link_path):
self._link_provider(self.file_path, link_path)
return True
return False
def remove(self, root, path_format=None):
link_path = self._abs_path(root, path_format)
if os.path.lexists(link_path):
print('remove', link_path)
os.remove(link_path)
return True
return False
def __repr__(self):
return 'Podcast("{f}")'.format(f=self.file_path)
@baker.command(name='list')
def list_podcast_files(path):
abs_files = []
for root, folders, files in os.walk(path):
for file in files:
file_path = os.path.abspath(os.path.join(root, file))
abs_files.append(file_path)
return abs_files
@baker.command(name='link')
def link_podcasts(path_from, path_to):
#TODO: change to - link_provider = os.link; shutil.copyfile
link_provider = shutil.copyfile
podcasts = [Podcast(f, link_provider) for f in list_podcast_files(path_from)]
for podcast in podcasts:
podcast.link_to(path_to, '{time.year}/{time.month}')
print('Found {l} files'.format(l=len(podcasts)))
@baker.command(name='link_last')
def link_last_podcasts(path_from, path_to, count=5):
#TODO: change to - link_provider = os.link; shutil.copyfile
link_provider = shutil.copyfile
podcasts = [Podcast(f, link_provider) for f in list_podcast_files(path_from)]
podcasts = sorted(podcasts, key=lambda x: x.creation_date(), reverse=True)
for podcast in podcasts[:count]:
podcast.link_to(path_to)
for podcast in podcasts[count:]:
podcast.remove(path_to)
print('Found {l} files'.format(l=len(podcasts)))
baker.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment