#!/usr/bin/env python3
# -*- coding: UTF-8 -*-


#This script has the purpose to import old TVHeadend recordings in a new TVHeadend installation, when no old logs exist. It scans a folder with TVHeadend recordings and sets for each file a recording timer in TVHeadend. This is adapted from the following skript:
#https://tvheadend.org/boards/5/topics/28252?r=29113#message-29113 by user ullix tv.
#The storage folder is expected to have subfolders for each movie or series. My recordings have a filename scheme of "YYYY-MM-DDTHH-MM-xxx.ts" because I had %FT%R in the beginning of recording string. Variables have to be adapted to personal situation and scripts need either to be adapted or filenames to be renamed.
import json, urllib, time, datetime, subprocess, os

#Input variables
recdir = "/volume1/tvrecords/"
api_url = "http://user:passwort@192.168.115.200:9981/api/dvr/entry/create?conf="
mask = """{
    "enabled": true,
    "start": 1000,
    "stop":  2000,
    "channelname": "Imported",
    "title": {
        "ger": "my title"
    },
    "comment": "added by tvimport.py",
    "files": [
        {
            "filename": "/full/path/to/videofile.ts"
        }
    ]
}"""
mask = mask.replace("\n", "")     # remove the line feeds



#Functions
def filedate2num(filepath):
    """Convert filename that starts with 'YYYY-MM-DDTHH-MM' to a unix timestamp; use cdate, i.e. last inode change time not creation, on error""" 
    try:
        dt = int(time.mktime(datetime.datetime.strptime(filepath.split("/")[-1][0:15], "%Y-%m-%dT%H-%M").timetuple()))
    except:
        print "ERROR in filestr2num: file name doesn't start with 'YYYY-MM-DDTHH-MM.ts'. Use Inode Change Time instead."
        dt = int(os.stat(filepath).st_ctime)
    return dt


def videoDuration(video_file_path):
    """Get video duration in sec from a ffprobe call, using json output"""


    #command is:  ffprobe -loglevel quiet -print_format json -show_format /full/path/to/videofile
    command     = ["ffprobe", "-loglevel", "quiet", "-print_format", "json", "-show_format",  video_file_path]
    pipe        = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    out, err    = pipe.communicate()
    js          = json.loads(out)
    return  int(float(js['format']['duration']) + 1.)


def importRecord(filepath, mask, url):
    """Creates a json file with the information from video file and sends a recording timer to the server."""
    video_start = filedate2num(filepath)
    new_mask                         = json.loads(mask)
    new_mask['files'][0]['filename'] = filepath[8:]
    new_mask['title']['ger']         = filepath.split("/")[-1][:-3]
    new_mask['start']                = video_start
    new_mask['stop']                 = video_start + videoDuration(filepath)
    print "New File Info: \n", json.dumps(new_mask, sort_keys = True, indent = 4)
    api_string = url + json.dumps(new_mask)
    filehandle = urllib.urlopen(api_string)
    print "Server Answer:", filehandle.read()


#Iterating through recordings folder
directories = os.listdir(recdir)
for folder in directories:
    for root, dirs, files in os.walk(recdir+folder):
        for filename in files:
            importRecord(recdir+folder+"/"+filename, mask, api_url)