BlowfishCMS
A small content management system for OpenBSD
version 0.45.6 · ISC · 2026-12-03 · releases
191 lines · 16.1 KB · download this file
#!/usr/bin/env python3
"""The video library and the video gallery block: uploads in pieces (with
resume), the MP4 checks, posters, the library and the public block. Runs
on a new site's catalogue with the small sample videos in tests/fixtures; never touches live data or media."""
import sys,pathlib;sys.path.insert(0,str(pathlib.Path(__file__).resolve().parent))
from sample_content import start_catalog
import os,sys,tempfile,pathlib,sqlite3,subprocess,json,re,urllib.parse,secrets,struct,zlib
sys.path.insert(0,str(pathlib.Path(__file__).resolve().parent));import signin # signs requests in (REMOTE_USER → session cookie)
script=str(pathlib.Path(sys.argv[1]).resolve())
fixtures=pathlib.Path(__file__).resolve().parent/'fixtures'
checks=[]
def check(v,msg):
assert v,msg
checks.append(msg);print('PASS',msg,flush=True)
def png(w=64,h=36):
def chunk(k,d):return struct.pack('>I',len(d))+k+d+struct.pack('>I',zlib.crc32(k+d)&0xffffffff)
rows=b''.join(b'\0'+bytes((x*7+y)%256 for x in range(w*3)) for y in range(h))
return b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',w,h,8,2,0,0,0))+chunk(b'IDAT',zlib.compress(rows))+chunk(b'IEND',b'')
with tempfile.TemporaryDirectory(prefix='blowfish-video-test-') as tmp:
root=pathlib.Path(tmp);data=root/'var/db/blowfishcms';(data/'admin/tmp').mkdir(parents=True)
(data/'admin/csrf.key').write_text(secrets.token_hex(32))
for kind in ['photography','music','artwork','blog']:(root/'media/blowfishcms'/kind).mkdir(parents=True)
copied_uploads=start_catalog(data/'catalog.sqlite')
with signin.connect(data/'catalog.sqlite') as copy:
for table in ['pages','page_blocks','site_settings']:copy.execute('drop table if exists '+table)
env={**os.environ,'BLOWFISH_ROOT':str(root),'BLOWFISH_PAGES_SEED':str(pathlib.Path(__file__).resolve().parent/'fixtures/sample-pages-seed.json')}
subprocess.run(['perl',script,'--migrate'],env=env,check=True,stdout=subprocess.DEVNULL)
con=sqlite3.connect(data/'catalog.sqlite');con.row_factory=sqlite3.Row
cols=[r['name'] for r in con.execute('pragma table_info(uploads)')]
check('duration' in cols and 'fps' in cols,'migration adds duration and frame rate to uploads')
cookie=''
def run(path,fields=None,files=(),fetch=True,user='admin'):
global cookie
url=urllib.parse.urlsplit(path);body=b'';ctype='application/x-www-form-urlencoded'
if fields is not None:
if files:
b='---'+secrets.token_hex(12);parts=[]
for k,v in fields.items():parts.append(f'--{b}\r\nContent-Disposition: form-data; name="{k}"\r\n\r\n{v}\r\n'.encode())
for k,name,mime,content in files:parts.append(f'--{b}\r\nContent-Disposition: form-data; name="{k}"; filename="{name}"\r\nContent-Type: {mime}\r\n\r\n'.encode()+content+b'\r\n')
body=b''.join(parts)+f'--{b}--\r\n'.encode();ctype='multipart/form-data; boundary='+b
else:body=urllib.parse.urlencode(fields).encode()
e={**env,'GATEWAY_INTERFACE':'CGI/1.1','REQUEST_METHOD':'POST' if fields is not None else 'GET','SCRIPT_NAME':url.path,'DOCUMENT_URI':url.path,'QUERY_STRING':url.query,
'CONTENT_TYPE':ctype,'CONTENT_LENGTH':str(len(body)),'HTTP_COOKIE':cookie,'REMOTE_USER':user,'HTTP_ORIGIN':'https://example.net','REMOTE_ADDR':'192.0.2.1'}
if fetch:e['HTTP_X_REQUESTED_WITH']='fetch'
p=subprocess.run(['perl',script],input=body,env=signin.sign(e),stdout=subprocess.PIPE,stderr=subprocess.PIPE)
assert p.returncode==0,(p.stderr.decode(),p.stdout[:300])
head,html=p.stdout.decode().split('\r\n\r\n',1);hdr=dict(l.split(': ',1) for l in head.split('\r\n'))
if 'Set-Cookie' in hdr and hdr['Set-Cookie'].startswith('bf_csrf='):cookie=hdr['Set-Cookie'].split(';')[0]
return int(hdr['Status']),html,hdr
run('/admin/?kind=video',fetch=False)
csrf=cookie.split('=',1)[1]
def act(action,files=(),**f):
status,body,_=run('/admin/',{'csrf':csrf,'kind':'video','action':action,**f},files=files)
return status,(json.loads(body) if body.startswith('{') else body)
def upload(path,piece=65536,poster=None,**meta):
data=pathlib.Path(path).read_bytes()
s,r=act('upload_start',name=pathlib.Path(path).name,size=str(len(data)),**meta)
assert s==200,r;uid=r['upload']
for off in range(0,len(data),piece):
s,r=act('upload_chunk',files=[('chunk','piece','application/octet-stream',data[off:off+piece])],upload=uid,offset=str(off));assert s==200,r
return act('upload_finish',files=[('poster','poster.png','image/png',poster)] if poster else (),upload=uid)
# ---- Before the setup step: no video folder ---------------------------------
s,r=act('upload_start',name='a.mp4',size='1000')
check(s==400 and 'server setup' in r['message'],'missing video folder explained')
(root/'media/blowfishcms/video').mkdir()
# ---- Starting an upload ----------------------------------------------------------
check(act('upload_start',name='clip.mov',size='1000')[1]['message'].startswith('Choose an MP4'),'only MP4 files accepted')
check('2 GB or smaller' in act('upload_start',name='big.mp4',size=str(2*1024**3+1))[1]['message'],'videos over 2 GB refused before uploading')
check(act('upload_start',name='empty.mp4',size='0')[0]==400,'empty file refused')
s,body,_=run('/admin/',{'csrf':csrf,'kind':'video','action':'upload_start','name':'a.mp4','size':'10'},fetch=False)
check(s!=200 or 'uploader' in body,'upload actions only through the page uploader')
check(run('/admin/',{'csrf':'bad','kind':'video','action':'upload_start','name':'a.mp4','size':'10'})[0]==403,'uploads need the CSRF token')
check(run('/admin/?kind=video',user='')[0] in (303,401,403),'video library needs the admin login')
# ---- Pieces, order and resume ------------------------------------------------------
good=(fixtures/'video-1080p60.mp4').read_bytes()
s,r=act('upload_start',name='Lesson_01-intro.mp4',size=str(len(good)),collection='Tutorials',description='First steps')
uid=r['upload'];check(s==200 and r['chunk']==8*1024*1024 and r['received']==0,'upload started; pieces of up to 8 MB')
piece=40000
act('upload_chunk',files=[('chunk','p','application/octet-stream',good[:piece])],upload=uid,offset='0')
s,r=act('upload_chunk',files=[('chunk','p','application/octet-stream',good[piece:2*piece])],upload=uid,offset='0')
check(s==400 and 'out of order' in r['message'],'repeated piece refused')
s,r=act('upload_chunk',files=[('chunk','p','application/octet-stream',good[2*piece:3*piece])],upload=uid,offset=str(2*piece))
check(s==400,'gap refused')
s,r=act('upload_status',upload=uid);check(s==200 and r['received']==piece and r['size']==len(good),'status reports what arrived (resume point)')
check(act('upload_finish',upload=uid)[1]['message']=="The upload isn't complete yet.",'unfinished upload not published')
for off in range(piece,len(good),piece):act('upload_chunk',files=[('chunk','p','application/octet-stream',good[off:off+piece])],upload=uid,offset=str(off))
s,r=act('upload_chunk',files=[('chunk','p','application/octet-stream',b'x')],upload=uid,offset=str(len(good)))
check(s==400,'nothing accepted past the announced size')
s,r=act('upload_finish',files=[('poster','poster.png','image/png',png())],upload=uid)
check(s==200 and r['ok'] and '1920×1080' in r['message'] and '60 fps' in r['message'] and '0:02' in r['message'] and 'fast start' not in r['message'],'finished: size, frame rate and length read from the file')
row=dict(con.execute("select * from uploads where kind='video'").fetchone())
check(row['title']=='Lesson 01 intro' and row['collection']=='Tutorials' and row['description']=='First steps' and row['width']==1920 and row['height']==1080 and round(row['fps'])==60 and 1.9<row['duration']<2.1,'stored with title, collection and details')
stored=root/'media/blowfishcms/video'/row['filename']
check(stored.read_bytes()==good,'video stored unchanged')
check(row['thumbnail'].endswith('.webp') and (root/'media/blowfishcms/video'/row['thumbnail']).exists(),'poster stored through the image pipeline')
check(not list((data/'admin/tmp').glob('upload-*')),'temporary files removed after publishing')
check(act('upload_status',upload=uid)[0]==400,'finished uploads are forgotten')
# ---- The checks ---------------------------------------------------------------------
s,r=upload(fixtures/'video-hevc.mp4');check(s==400 and 'H.264' in r['message'] and 'HEVC' in r['message'],'HEVC refused with advice to export H.264')
bad=root/'notvideo.mp4';bad.write_bytes(b'this is not a video at all'*100)
s,r=upload(bad);check(s==400 and 'MP4' in r['message'],'non-MP4 data refused')
cut=root/'cut.mp4';cut.write_bytes(good[:len(good)//2])
s,r=upload(cut);check(s==400 and 'complete' in r['message'],'truncated file refused')
check(not list((data/'admin/tmp').glob('upload-*')) and len(list((root/'media/blowfishcms/video').glob('*.mp4')))==1,'refused uploads leave nothing behind')
s,r=upload(fixtures/'video-slow-start.mp4',piece=100000,collection='Extras')
check(s==200 and 'fast start' in r['message'],'video without fast start published with a note')
# ---- Library -------------------------------------------------------------------------
s,html,_=run('/admin/?kind=video',fetch=False)
check(s==200 and html.count('<li class="lib-item"')==2 and html.count('<video class="lib-preview"')==2 and 'id="upload-form"' in html and '1920×1080 · 60 fps · 0:02' in html and 'lib-thumb__badge">0:02<' in html,'library lists videos with length, and a player and details in each panel')
check('<strong>Video gallery</strong> block' in html,'library explains where videos appear')
check('<strong>H.264</strong> video · <strong>AAC</strong> audio. Any frame rate' in html,'upload window states the export settings')
vid=row['id']
s,_,_=run('/admin/',{'csrf':csrf,'kind':'video','action':'poster','id':vid,'remove_poster':'1'},fetch=False)
check(con.execute('select thumbnail from uploads where id=?',(vid,)).fetchone()[0]=='' and not (root/'media/blowfishcms/video'/row['thumbnail']).exists(),'poster removed')
run('/admin/',{'csrf':csrf,'kind':'video','action':'poster','id':vid},files=[('poster','p.png','image/png',png(1920,1080))],fetch=False)
poster=con.execute('select thumbnail from uploads where id=?',(vid,)).fetchone()[0]
check(poster.endswith('.webp'),'poster replaced')
ids=[r[0] for r in con.execute("select id from uploads where kind='video' order by sort_order")]
run('/admin/',{'csrf':csrf,'kind':'video','action':'move','id':ids[1],'direction':'up'},fetch=False)
check([r[0] for r in con.execute("select id from uploads where kind='video' order by sort_order")]==ids[::-1],'videos reorder')
for i in ids:act('item_save',id=i,title='Renamed '+i[:4],collection='Tutorials',description='')
check(con.execute("select count(*) from uploads where kind='video' and title like 'Renamed %'").fetchone()[0]==2,'video titles edited from their panels')
s,r=act('upload_start',name='other.mp4',size='10')
s,body,_=run('/admin/',{'csrf':csrf,'kind':'photography','action':'upload_status','upload':r['upload']})
check(s==400 and 'another library' in json.loads(body)['message'],'an upload can only be finished in the library that started it')
act('upload_cancel',upload=r['upload'])
# ---- Public block ---------------------------------------------------------------------
s,html,_=run('/admin/?kind=page&page=music',fetch=False)
check('Video gallery' in html,'video gallery offered in the page builder')
s,_,hdr=run('/admin/',{'csrf':csrf,'kind':'page','page':'music','action':'block_add','type':'videos','width':'full'},fetch=False)
check(s==303,'video gallery block added to a page')
html=run('/music/',fetch=False,user='')[1]
check(html.count('class="video-card"')==2 and '>2 videos</div>' in html,'block shows the videos with a count')
check('controlslist="nodownload"' in html and 'download=' not in re.search(r'<div class="video-list">.*?</div></article></div>',html,re.S).group(0),'watch only: no download link')
check('poster="/media/video/'+poster+'" preload="none"' in html and 'preload="metadata"' in html and '#t=0.1' in html,'poster shown where set; first frame otherwise')
check('class="collection-filter"' in html and '<option value="Tutorials">' in html,'collection picker when videos have collections')
bid=[b for b in con.execute("select id,data from page_blocks where page='music' and type='videos'")][0][0]
blk=json.loads(con.execute('select data from page_blocks where id=?',(bid,)).fetchone()[0]);blk['collection']='Tutorials';blk['subtitle']=''
con.execute('update page_blocks set data=? where id=?',(json.dumps(blk),bid));con.commit()
check('>2 videos</div>' in run('/music/',fetch=False,user='')[1],'block limited to one collection')
# ---- Delete ----------------------------------------------------------------------------
run('/admin/',{'csrf':csrf,'kind':'video','action':'delete','id':vid},fetch=False)
check(not stored.exists() and not (root/'media/blowfishcms/video'/poster).exists() and con.execute('select count(*) from uploads where id=?',(vid,)).fetchone()[0]==0,'delete removes the video and its poster')
check(con.execute("select count(*) from uploads where kind<>'video'").fetchone()[0]==copied_uploads,'other libraries untouched')
# ---- Saved livestreams (0.39.3) ----------------------------------------------------------
# Live hands a stream over as its pieces joined in order (a fragmented MP4)
# with a note; root's runner moves both to videos-in/ and runs --import-videos.
def top(b):
# The top-level boxes of an MP4: their types, in order.
out,pos=[],0
while pos+8<=len(b):
n,t=struct.unpack('>I4s',b[pos:pos+8])
if n==1:n=struct.unpack('>Q',b[pos+8:pos+16])[0]
if n<8:break
out.append(t.decode());pos+=n
return out
live=fixtures/'live-stream'
pieces=[live/'init.mp4']+sorted(live.glob('seg*.m4s'),key=lambda p:int(p.stem[3:]))
vin=data/'videos-in';vin.mkdir(mode=0o700)
(vin/'live-20261123-201500.mp4').write_bytes(b''.join(p.read_bytes() for p in pieces))
(vin/'live-20261123-201500.json').write_text(json.dumps({'title':'Livestream, 23 November 2026, 20:15','tags':'pastlivestreams','started':1795465200}))
(vin/'live-gap.mp4').write_bytes(b''.join(p.read_bytes() for p in pieces if p.name!='seg1.m4s'));(vin/'live-gap.json').write_text('{"title":"A piece lost","tags":"pastlivestreams"}')
(vin/'live-junk.mp4').write_bytes(b'not a video at all'*50);(vin/'live-junk.json').write_text('{"title":"Junk"}')
r=subprocess.run(['perl',script,'--import-videos'],env=env,capture_output=True,text=True)
rows={x['title']:dict(x) for x in con.execute("select * from uploads where kind='video'")}
lv=rows.get('Livestream, 23 November 2026, 20:15')
check(r.returncode==1 and lv and lv['width']==160 and lv['height']==90 and 4.9<lv['duration']<5.2 and round(lv['fps'])==30,'a saved stream is added to Videos, with its size, frame rate and length: '+r.stdout+r.stderr)
joined=(root/'media/blowfishcms/video'/lv['filename']).read_bytes()
check(top(joined)==['ftyp','moov','mdat'] and lv['bytes']==len(joined),'its pieces are joined into an ordinary MP4, index first (fast start)')
check([t for (t,) in con.execute("select tag from item_tags where kind='video' and item=?",(lv['id'],))]==['pastlivestreams'],'tagged #pastlivestreams')
check(con.execute("select id from uploads where kind='video' order by sort_order limit 1").fetchone()[0] in (lv['id'],rows['A piece lost']['id']),'at the top of the library')
check(4.9<rows['A piece lost']['duration']<5.2,'a piece that never arrived leaves a still moment; the rest keeps its time')
check(not list(vin.glob('*.mp4')) and not list(vin.glob('*.json')),'what was added leaves videos-in/')
why=(vin/'failed/live-junk.why').read_text()
check((vin/'failed/live-junk.mp4').exists() and 'MP4' in why and 'Junk' not in rows,'one that can’t be added goes to failed/, with why')
html=run('/admin/',fetch=False)[1]
check('A saved stream couldn’t be added to Videos: '+why.strip().replace("'",''') in html,'the Overview says so')
check('Livestream, 23 November 2026, 20:15' in run('/tags/pastlivestreams/',fetch=False,user='')[1],'it’s on the #pastlivestreams page at once')
# An ordinary MP4 handed over is added as it is.
(vin/'clip.mp4').write_bytes(good);(vin/'clip.json').write_text('{"title":"Plain"}')
subprocess.run(['perl',script,'--import-videos'],env=env,capture_output=True)
plain=con.execute("select filename from uploads where title='Plain'").fetchone()
check(plain and (root/'media/blowfishcms/video'/plain[0]).read_bytes()==good,'an ordinary MP4 is added unchanged')
print(json.dumps({'checks':len(checks)}))