category page made, but without pagination
[living-lab-site.git] / scripts / auto-publishing / publish_videos.py
1 #!/usr/bin/python
2 #
3 # Copyright Calin-Andrei Burloiu, calin.burloiu@gmail.com
4 #
5 # Automatically publishes videos in P2P-Tube DB based on the video files and
6 # a videos info file. Parameters: videos_info_file videos_directory category_id
7 #
8 import sys
9 import MySQLdb
10 import os
11 import fnmatch
12 import subprocess
13 import string
14 import json
15
16 # cms_content table
17 class VideosTable:
18     tableName = "videos"
19     user_id = 1
20     thumbs_count = 1
21     default_thumb = 0
22     
23     directory = os.curdir
24     default_video_ext = 'ogv'
25
26     def __init__(self, dbCur, directory, name, title, description, tags, category_id):
27         self.dbCur = dbCur
28         self.directory = directory
29
30         self.name = name
31         self.title = title
32         self.description = description
33         self.duration, self.formats = self.findVideosMeta()
34         self.formats_json = json.dumps(self.formats, separators=(',', ':'))
35         self.category_id = category_id
36         
37         tagList = tags.split(',')
38         self.tags = {}
39         for tag in tagList:
40             if tag != '':
41                 self.tags[tag.strip()] = 0
42         self.tags_json = json.dumps(self.tags, separators=(',', ':'))
43         
44     def getVideoDefinition(self, fileName):
45         pipe = subprocess.Popen('mediainfo --Inform="Video;%Height%" ' + os.path.join(self.directory, fileName), shell=True, stdout=subprocess.PIPE).stdout
46         height = pipe.readline().strip()
47
48         pipe = subprocess.Popen('mediainfo --Inform="Video;%ScanType%" ' + os.path.join(self.directory, fileName), shell=True, stdout=subprocess.PIPE).stdout
49         scanType = pipe.readline().strip()
50         if scanType == '' or scanType == 'Progressive':
51             scanType = 'p'
52         elif scanType == 'Interlaced':
53             scanType = 'i';
54
55         return height + scanType
56
57     def getVideoDuration(self, fileName):
58         pipe = subprocess.Popen('mediainfo --Inform="General;%Duration/String3%" ' + os.path.join(self.directory, fileName), shell=True, stdout=subprocess.PIPE).stdout
59         output = pipe.readline().strip()
60         dotPos = output.find('.')
61         if output[0:2] == '00':
62             duration = output[3:dotPos]
63         else:
64             duration = output[:dotPos]
65
66         return duration
67         
68
69     # Returns a pair with duration and formats list.
70     def findVideosMeta(self):
71         files = [f for f in os.listdir(self.directory) if os.path.isfile(os.path.join(self.directory, f))]
72         files = fnmatch.filter(files, self.name + "*")
73
74         # Duration not set
75         duration = None
76
77         # Formats list
78         formats = []
79         for f in files:
80             if f.find('.tstream') == -1:
81                 # Duration (if not set yet)
82                 if duration == None:
83                     duration = self.getVideoDuration(f)
84                 format_ = {}
85                 format_['def'] = f[(f.rfind('_')+1):f.rfind('.')]
86                 ext = f[(f.rfind('.')+1):]
87                 if ext != self.default_video_ext:
88                     format_['ext'] = ext
89                 if format_['def'] != self.getVideoDefinition(f):
90                     raise VideoDefException(f)
91                 formats.append(format_)
92
93         return (duration, formats)
94
95     def insert(self):
96         if self.duration == None or self.formats_json == None or self.tags_json == None:
97             print "Bzzzz"
98         query = "INSERT INTO `" + self.tableName + "` (name, title, description, duration, formats, category_id, user_id, tags, date, thumbs_count, default_thumb) VALUES ('" + self.name + "', '" + self.title + "', '" + self.description + "', '" + self.duration + "', '" + self.formats_json + "', " + str(self.category_id) + ", " + str(self.user_id) + ", '" + self.tags_json + "', NOW(), " + str(self.thumbs_count) + ", " + str(self.default_thumb) + ")"
99         self.dbCur.execute(query)    
100     
101     @staticmethod
102     def getAllNames(dbCur, category_id):
103         allNames = set()
104         query = "SELECT name FROM `" + VideosTable.tableName + "` WHERE category_id = " + str(category_id)
105         dbCur.execute(query)
106
107         while(True):
108             row = dbCur.fetchone()
109             if row == None:
110                 break
111             allNames.add(row[0])
112
113         return allNames
114
115
116 class VideoDefException(Exception):
117     def __init__(self, value):
118         self.value = 'Invalid video definition in file name "' + value + '"! '
119
120     def __str__(self):
121         return repr(self.value)
122
123
124 def main():
125     # Check arguments.
126     if len(sys.argv) < 3:
127         sys.stdout.write('usage: ' + sys.argv[0] + ' videos_info_file videos_dir category_id\n')
128         exit(1)
129
130     # Command line arguments
131     fileName = sys.argv[1]
132     directory = sys.argv[2]
133     category_id = int(sys.argv[3])
134     if len(sys.argv) == 4:
135         thumbsDir = sys.argv[3]
136     else:
137         thumbsDir = None
138
139     # Connect to DB
140     dbConn = MySQLdb.connect(host = 'koala.cs.pub.ro', user = 'koala_p2pnext',
141             passwd = 'ahmitairoo', db = 'koala_livinglab')
142     dbCur = dbConn.cursor()
143
144     allNames = VideosTable.getAllNames(dbCur, category_id)
145
146     # Open info file
147     file = open(fileName, 'r')
148
149     # Read videos info file
150     i = 1
151     name = file.readline()
152     while name != '':
153         name = name.strip()
154         title = file.readline().strip()
155         description = file.readline().strip()
156         tags = file.readline().strip()
157         
158         if not name in allNames:
159             sys.stdout.write(str(i) + '. ' + name + '\r')
160             try:
161                 video = VideosTable(dbCur, directory, name, title, description, tags, category_id)
162                 video.insert()
163                 i = i+1
164
165             except VideoDefException as e:
166                 sys.stdout.write('\n' + e.value + '\n')
167
168         name = file.readline()
169
170     # Clean-up
171     dbCur.close()
172     dbConn.close()
173     sys.stdout.write('\n')
174
175     return 0
176
177
178 if __name__ == "__main__":
179     sys.exit(main())