Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Iframe support in the dom #11

Merged
merged 4 commits into from
Nov 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ SQLAlchemy==2.0.36
uWSGI==2.0.27
Werkzeug==2.2.2
WTForms==2.2.1
urllib3==2.2.3
61 changes: 44 additions & 17 deletions src/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from data import User, PR, add_pr, fix_date
from forms import PRForm, ModifyPRForm
from werkzeug.utils import secure_filename
from urllib.parse import quote

admin_page = Blueprint("admin", __name__)

Expand Down Expand Up @@ -40,8 +41,10 @@ def admin():

if form.validate_on_submit():
filename = form.file.data.filename
if not filename or not allowed_file(filename):
flash("File type not supported")
link = form.link.data

if link and filename:
flash("Both file and link")
return redirect("/admin")

# Check if start date is after end date
Expand All @@ -57,20 +60,43 @@ def admin():
flash(msg)
return redirect("/admin")

org_filename = secure_filename(filename)

# Generate random filename with correct extention
filename = str(uuid.uuid4()) + "." + \
org_filename.rsplit('.', 1)[1].lower()
form.file.data.save(os.path.join(
app.config['UPLOAD_FOLDER'], filename))
add_pr(file_name=filename,
desc=form.desc.data,
priority=form.priority.data,
start_date=form.start_date.data,
end_date=form.end_date.data,
user_id=current_user.id,
owner=current_user.username)
if link:
if not link.startswith("https://"):
flash("Link didn't start with https://")
return redirect("/admin")

if link.startswith("https://tv.dtek.se"):
flash("No links to tv-mannnen D:")
return redirect("/admin")

add_pr(file_name=link,
is_iframe=True,
desc=form.desc.data,
priority=form.priority.data,
start_date=form.start_date.data,
end_date=form.end_date.data,
user_id=current_user.id,
owner=current_user.username)
elif filename:
if (not filename or not allowed_file(filename)):
flash("File type not supported")
return redirect("/admin")

org_filename = secure_filename(filename)

# Generate random filename with correct extention
filename = str(uuid.uuid4()) + "." + \
org_filename.rsplit('.', 1)[1].lower()
form.file.data.save(os.path.join(
app.config['UPLOAD_FOLDER'], filename))
add_pr(file_name=filename,
is_iframe=False,
desc=form.desc.data,
priority=form.priority.data,
start_date=form.start_date.data,
end_date=form.end_date.data,
user_id=current_user.id,
owner=current_user.username)
return redirect("/admin")
else:
# Change the default start and end dates
Expand Down Expand Up @@ -107,7 +133,8 @@ def delete():
return redirect("/admin")

try:
os.remove(os.path.join(config.UPLOAD_FOLDER, pr.file_name))
if not pr.is_iframe:
os.remove(os.path.join(config.UPLOAD_FOLDER, pr.file_name))
except:
flash("PR wasn't found on disk but the database entry has been removed")

Expand Down
5 changes: 3 additions & 2 deletions src/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ def check_password(self, password):
class PR(db.Model):
id = db.Column(db.Integer, primary_key=True)
desc = db.Column(db.String())
is_iframe = db.Column(db.Boolean())
file_name = db.Column(db.String())
start_date = db.Column(db.DateTime, index=True, default=datetime.utcnow)
end_date = db.Column(db.DateTime, index=True)
Expand Down Expand Up @@ -53,10 +54,10 @@ def fix_date(start_date, end_date, priority):

return start, end

def add_pr(file_name, desc, priority, start_date, end_date, user_id, owner):
def add_pr(file_name, is_iframe, desc, priority, start_date, end_date, user_id, owner):
# Fix date
start, end = fix_date(start_date, end_date, priority)
pr = PR(desc=desc, file_name=file_name, priority=priority,
pr = PR(desc=desc, is_iframe=is_iframe, file_name=file_name, priority=priority,
start_date=start, end_date=end, user_id=user_id, owner=owner)
db.session.add(pr)
db.session.commit()
Expand Down
6 changes: 4 additions & 2 deletions src/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,10 @@ def validate_username(self, username):
raise ValidationError('Username already taken')

class PRForm(FlaskForm):
file = FileField(label="File:",
validators=[DataRequired()])
file = FileField(label="File:")

link = StringField(label="Link:",
render_kw={"placeholder": "https://google.com"})

desc = StringField("Description:",
validators=[DataRequired(), Length(min=1, max=128)],
Expand Down
8 changes: 8 additions & 0 deletions src/migrations/02-iframe-support.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from tv import app, db
from sqlalchemy import text

def upgrade():
with app.app_context():

db.session.execute(text(f"ALTER TABLE pr ADD COLUMN is_iframe BOOLEAN DEFAULT FALSE"))
db.session.commit()
38 changes: 36 additions & 2 deletions src/templates/admin.html
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
</tr>
{% for pr in pr_list %}
<tr>
<td data-label="Description:"> <a href="/img/{{pr.file_name}}">{{ pr.desc }}</a></td>
<td data-label="Description:"> <a href={{ pr.file_name if pr.is_iframe else "/img/" + pr.file_name}}>{{ pr.desc }}</a></td>
<td data-label="Start time:"> {{ pr.start_date.strftime('%Y-%m-%d, %H:%M') }}</td>
<td data-label="End time:"> {{ pr.end_date.strftime('%Y-%m-%d, %H:%M') }}</td>
<td data-label="Priority:"> {{ pr.priority }}</td>
Expand Down Expand Up @@ -71,12 +71,26 @@ <h3 class="section">File</h3>
</div>
<div class="col-sm-12 col-md">
{{ form.file }}
<button type="button" id="clearFile" style="all: revert">
clear
</button>
{% for error in form.file.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</div>
</div>


<div class="center-row row responsive-label">
<div class="col-sm-12 col-md-2">
{{ form.link.label }}
</div>
<div class="col-sm-12 col-md">
{{ form.link }}
{% for error in form.link.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</div>
</div>

<div class="center-row row responsive-label">
<div class="col-sm-12 col-md-2">
Expand Down Expand Up @@ -131,4 +145,24 @@ <h3 class="section">File</h3>
</form>
</fieldset>

<script>
const file = document.getElementById("file"),
link = document.getElementById("link"),
clear = document.getElementById("clearFile");
file.addEventListener("change", (event) => {
link.disabled = file.value!=='';
}
)

link.addEventListener("input", (event) => {
file.disabled = link.value!=='';
}
)

clear.addEventListener("click", (event) => {
file.value = '';
link.disabled = false;
}
)
</script>
{% endblock %}
26 changes: 23 additions & 3 deletions src/templates/pr.html
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,15 @@
width: 100%;
height: 100%;
}

iframe {
display: block;
width: 100%;
border: none;
overflow-y: auto;
overflow-x: hidden;
pointer-events: none;
}
</style>

<script>
Expand All @@ -62,13 +71,24 @@
// If a pr has been deleted since last call
curr %= prs.length;

if (prs[curr].endsWith(".mp4")) {
if (prs[curr].iframe) {
body.innerHTML = ""
var iframe = document.createElement('iframe');
iframe.src = encodeURI(prs[curr].link);
iframe.width = "100%";
iframe.height = "100%";
iframe.style.background = 'white';
body.appendChild(iframe)
body.style.backgroundImage = "none";
var time_to_play = {{ pr_time }} * 1000;
timeout = setTimeout(next_pr, time_to_play);
} else if (prs[curr].link.endsWith(".mp4")) {
// Video (only mp4)
var video = document.createElement('video');
video.autoplay = true;
video.loop = true;
video.muted = true;
video.src = prs[curr];
video.src = prs[curr].link;
video.onloadedmetadata = () => {
var times_to_repeat = Math.ceil({{ pr_time }} / video.duration);
var time_to_play = Math.floor(times_to_repeat * video.duration * 1000);
Expand All @@ -82,7 +102,7 @@
else {
// Image
body.innerHTML = "";
body.style.backgroundImage = "url(" + prs[curr] + ")";
body.style.backgroundImage = "url(" + prs[curr].link + ")";
var time_to_play = {{ pr_time }} * 1000;
timeout = setTimeout(next_pr, time_to_play);
}
Expand Down
7 changes: 5 additions & 2 deletions src/tv.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,15 @@ def pr():
priority = PR.query.filter(PR.priority==1, PR.start_date < datetime.now()).first()
if priority != None:
return json.jsonify(
["/img/" + priority.file_name]
{ "iframe": priority.is_iframe,
"link": priority.file_name if priority.is_iframe else "/img/" + priority.file_name}
)

# Return all active PRs
return json.jsonify(
[("/img/" + user.file_name)
[{"iframe": user.is_iframe,
"link": user.file_name if user.is_iframe else "/img/" + user.file_name
}
for user in PR.query.filter(PR.start_date < datetime.now()).all()]
)

Expand Down
Loading