diaspora: Templates to setup domain name

This commit is contained in:
Joseph Nuthalpati 2017-03-17 16:09:07 +05:30 committed by James Valleroy
parent 747a02adf2
commit 5ffcf42278
No known key found for this signature in database
GPG Key ID: 77C0C75E7B650808
8 changed files with 284 additions and 86 deletions

View File

@ -16,7 +16,6 @@
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
Configuration helper for diaspora* pod.
"""
@ -36,27 +35,68 @@ def parse_arguments():
'pre-install',
help='Preseed debconf values before packages are installed.')
subparsers.add_parser('enable', help='Enable diaspora*')
subparsers.add_parser('disable', help='Disable diaspora*')
subparsers.add_parser('disable-ssl', help="Disable SSL on the diaspora* application server")
subparsers.add_parser('enable', help='Enable diaspora* web server')
subparsers.add_parser('disable', help='Disable diaspora* web server')
subparsers.add_parser('start-diaspora', help='Start diaspora* service')
subparsers.add_parser(
'disable-ssl', help="Disable SSL on the diaspora* application server")
setup = subparsers.add_parser(
'setup', help='Set Domain name for diaspora*')
setup.add_argument(
'--domain-name', help='The domain name that will be used by diaspora*')
return parser.parse_args()
def subcommand_setup(arguments):
"""Set the domain_name in diaspora configuration files"""
domain_name = arguments.domain_name
with open('/etc/diaspora/domain_name', 'w') as dnf:
dnf.write(domain_name)
set_domain_name(domain_name)
action_utils.service_start('diaspora')
action_utils.webserver_enable('diaspora-plinth')
def set_domain_name(domain_name):
"""Write a new domain name to diaspora configuration files"""
# This did not set the domain_name
# action_utils.dpkg_reconfigure('diaspora-common',
# {'url': domain_name})
# Manually changing the domain name in the conf files.
conf_file = '/etc/diaspora.conf'
with open(conf_file, 'r') as conf:
env_vars = conf.read().splitlines()
for index, line in enumerate(env_vars):
if "SERVER_NAME" in line:
env_vars[index] = "export SERVER_NAME={}".format(domain_name)
if "ENVIRONMENT_URL" in line:
env_vars[index] = "export ENVIRONMENT_URL=http://{}:3000".format(
domain_name)
with open(conf_file, 'w') as conf:
conf.write("\n".join(env_vars))
action_utils.service_start('diaspora')
def subcommand_disable_ssl(_):
"""
Disable ssl in the diaspora configuration
as the apache server takes care of ssl
"""
subprocess.call(["sed", "-i",
"s/#require_ssl: true/require_ssl: false/g",
"/etc/diaspora/diaspora.yml"])
subprocess.call([
"sed", "-i", "s/#require_ssl: true/require_ssl: false/g",
"/etc/diaspora/diaspora.yml"
])
def subcommand_pre_install(arguments):
def subcommand_pre_install(_):
"""Pre installation configuration for diaspora"""
presets= [
b'diaspora-common diaspora-common/url string http://localhost/diaspora',
presets = [
b'diaspora-common diaspora-common/url string dummy_domain_name',
b'diaspora-common diaspora-common/dbpass note ',
b'diaspora-common diaspora-common/enablessl boolean false',
b'diaspora-common diaspora-common/useletsencrypt string false',
@ -72,19 +112,17 @@ def subcommand_pre_install(arguments):
for preset in presets:
subprocess.check_output(['debconf-set-selections'], input=preset)
# hostname = arguments.hostname or socket.gethostname()
# subprocess.check_output(
# ['debconf-set-selections'],
# input=b'diaspora diaspora/url string ' + hostname.encode())
def subcommand_enable(_):
"""Enable web configuration and reload."""
action_utils.service_enable('diaspora')
action_utils.webserver_enable('diaspora-plinth')
def subcommand_disable(_):
"""Disable web configuration and reload."""
action_utils.webserver_disable('diaspora-plinth')
action_utils.service_disable('diaspora')
def main():
@ -98,4 +136,3 @@ def main():
if __name__ == '__main__':
main()

View File

@ -16,11 +16,35 @@
#
import subprocess
import os
from django.utils.translation import ugettext_lazy as _
from plinth.modules import names
from plinth.utils import format_lazy
from plinth import actions, action_utils, cfg, frontpage, service as service_module
domain_name_file = "/etc/diaspora/domain_name"
lazy_domain_name = None # To avoid repeatedly reading from file
def is_setup():
return os.path.exists(domain_name_file)
def get_configured_domain_name():
if lazy_domain_name:
return lazy_domain_name
if not is_setup():
return ""
with open(domain_name_file) as dnf:
global lazy_domain_name
lazy_domain_name = dnf.read().rstrip()
return lazy_domain_name
version = 1
title_en = 'Federated Social Network (diaspora*)'
@ -37,8 +61,11 @@ managed_packages = ['diaspora']
description = [
_('diaspora* is a decentralized social network where you can store and control your own data.'
), _('When enabled, the diaspora* pod will be available from '
'<a href="/diaspora">/diaspora</a> path on the web server.')
),
format_lazy(
'When enabled, the diaspora* pod will be available from '
'<a href="https://diaspora.{host}">diaspora.{host}</a> path on the web server.'.
format(host=get_configured_domain_name()))
]
@ -67,7 +94,8 @@ def setup(helper, old_version=None):
"""Install and configure the module."""
helper.call('pre', actions.superuser_run, 'diaspora', ['pre-install'])
helper.install(managed_packages)
helper.call('custom_config', actions.superuser_run, 'diaspora', ['disable-ssl'])
helper.call('custom_config', actions.superuser_run, 'diaspora',
['disable-ssl'])
helper.call('post', actions.superuser_run, 'diaspora', ['enable'])
global service
if service is None:
@ -83,10 +111,26 @@ def setup(helper, old_version=None):
helper.call('post', add_shortcut)
def get_domain_names():
"""Return the domain name(s)"""
results = []
for domain_type, domains in names.domains.items():
if domain_type == 'hiddenservice':
continue
for domain in domains:
results.append((domain, domain))
return results
def add_shortcut():
"""Add shortcut to diaspora on the Plinth homepage"""
frontpage.add_shortcut(
'diaspora', title, url='/diaspora', login_required=True)
'diaspora',
title,
url='https://diaspora.{}'.format(get_configured_domain_name()),
login_required=True)
def is_enabled():
@ -110,11 +154,16 @@ def diagnose():
"""Run diagnostics and return the results."""
results = []
# results.append(action_utils.service_is_enabled('diaspora'))
# results.append(action_utils.service_is_running('diaspora'))
# results.append(is_enabled())
results.extend(
action_utils.diagnose_url_on_all(
'https://{host}/diaspora', check_certificate=False))
results.append(
action_utils.diagnose_url(
'http://diaspora.localhost', kind='4', check_certificate=False))
results.append(
action_utils.diagnose_url(
'http://diaspora.localhost', kind='6', check_certificate=False))
results.append(
action_utils.diagnose_url(
'http://diaspora.{}'.format(get_configured_domain_name()),
kind='4',
check_certificate=False))
return results

View File

@ -8,18 +8,31 @@
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
Forms for configuring diaspora*
"""
from django import forms
from django.utils.translation import ugettext_lazy as _
from plinth.modules import diaspora
class DiasporaForm(forms.Form):
"""diaspora* configuration form."""
enabled = forms.BooleanField(
label='Enable diaspora',
required=False)
"""Form to do initial configuration of diaspora"""
domain_name = forms.ChoiceField(
label=_('Select the domain name to be used for diaspora*'),
help_text=_(
'Warning! Do not change the FreedomBox domain name after setting up diaspora*'
),
choices=[])
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['domain_name'].choices = diaspora.get_domain_names()

View File

@ -0,0 +1,40 @@
{% extends "service.html" %}
{% comment %}
#
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see
<http://www.gnu.org/licenses/>.
#
{% endcomment %}
{% load i18n %}
{% block description %}
{% for paragraph in description %}
<p>{{ paragraph|safe }}</p>
{% endfor %}
<p>
{% url 'config:index' as index_url %}
{% blocktrans trimmed with domain_name=domain_name %}
The diaspora* pod domain is set to <b>{{ domain_name }}</b>. User
IDs will look like <i>username@diaspora.{{ domain_name }}</i><br/>
If the FreedomBox domain name is changed, all data of the users
registered with the previous podname wouldn't be accessible. <br/>
You can access the diaspora* pod at <a href="https://diaspora.{{domain_name}}"> diaspora.{{domain_name}} </a>
{% endblocktrans %}
</p>
{% endblock %}

View File

@ -0,0 +1,62 @@
{% extends "base.html" %}
{% comment %}
#
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
{% endcomment %}
{% load bootstrap %}
{% load i18n %}
{% block content %}
{% block pagetitle %}
<h2>{{ title }}</h2>
{% endblock %}
{% block description %}
{% for paragraph in description %}
<p>{{ paragraph|safe }}</p>
{% endfor %}
{% endblock %}
<p>
{% url 'config:index' as index_url %}
{% if domain_names|length == 0 %}
No domain(s) are set. You can setup your domain on the system at
<a href="{{ index_url }}">Configure</a> page.
{% endif %}
</p>
{% block status %}
{% endblock %}
{% block diagnostics %}
{% endblock %}
{% block configuration %}
{% if domain_names|length > 0 %}
<h3>Configuration</h3>
<form class="form" method="post">
{% csrf_token %}
{{ form|bootstrap }}
<input type="submit" class="btn btn-primary"
value="{% trans "Update setup" %}"/>
</form>
{% endif %}
{% endblock %}
{% endblock %}

View File

@ -16,19 +16,16 @@
#
"""
URLs for the Diaspora module.
URLs for the diaspora module
"""
from django.conf.urls import url
from plinth.modules import diaspora
from plinth.views import ServiceView
from .views import DiasporaSetupView, DiasporaServiceView
urlpatterns = [
url(r'^apps/diaspora/$', ServiceView.as_view(
description=diaspora.description,
diagnostics_module_name="diaspora",
service_id=diaspora.managed_services[0]
), name='index'),
url(r'^apps/diaspora/setup$', DiasporaSetupView.as_view(),
name='setup'),
url(r'^apps/diaspora/$', DiasporaServiceView.as_view(),
name='index')
]

View File

@ -15,57 +15,57 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from .forms import DiasporaForm
"""
Views for the Matrix Synapse module
"""
from django.shortcuts import redirect
from django.urls import reverse_lazy
from django.views.generic import FormView
from plinth import actions
from plinth.modules import diaspora
from plinth import actions, package
from django.utils.translation import ugettext as _
from django.template.response import TemplateResponse
from django.contrib import messages
def get_status():
"""Get the current status"""
return {'enabled': diaspora.is_enabled()}
from plinth.modules.diaspora.forms import DiasporaForm
from plinth.views import ServiceView
def _apply_changes(request, old_status, new_status):
"""Apply the changes."""
modified = False
class DiasporaSetupView(FormView):
"""Show diaspora setup page."""
template_name = 'diaspora-pre-setup.html'
form_class = DiasporaForm
description = diaspora.description
title = diaspora.title
success_url = reverse_lazy('diaspora:index')
if old_status['enabled'] != new_status['enabled']:
sub_command = 'enable' if new_status['enabled'] else 'disable'
actions.superuser_run('diaspora', [sub_command])
modified = True
def form_valid(self, form):
domain_name = form.cleaned_data['domain_name']
actions.superuser_run('diaspora',
['setup', '--domain-name', domain_name])
if modified:
messages.success(request, 'Configuration updated')
else:
messages.info(request, 'Setting unchanged')
return super().form_valid(form)
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(**kwargs)
context['description'] = self.description
context['title'] = self.title
context['domain_names'] = diaspora.get_domain_names()
return context
# TODO
# If there are configuration tasks to be performed immediately before or after the package installation, Plinth provides hooks for it. The before_install= and
# on_install= parameters to the @package.required decorator take a callback methods that are called before installation of packages and after installation of
# packages respectively. See the reference section of this manual or the plinth.package module for details. Other modules in Plinth that use this feature provided
# example usage.
@package.required(['diaspora'])
def index(request):
"""Serve configuration page."""
status = get_status()
class DiasporaServiceView(ServiceView):
"""Show diaspora service page."""
service_id = diaspora.managed_services[0]
template_name = 'diaspora-post-setup.html'
diagnostics_module_name = 'diaspora'
form = None
def dispatch(self, request, *args, **kwargs):
if not diaspora.is_setup():
return redirect('diaspora:setup')
if request.method == 'POST':
form = DiasporaForm(request.POST, prefix='diaspora')
if form.is_valid():
_apply_changes(request, status, form.cleaned_data)
status = get_status()
form = DiasporaForm(initial=status, prefix='diaspora')
else:
form = DiasporaForm(initial=status, prefix='diaspora')
return super().dispatch(request, *args, **kwargs)
return TemplateResponse(request, 'diaspora.html',
{'title': _(diaspora.title_en),
'status': status,
'form': form})
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(**kwargs)
context['domain_name'] = diaspora.get_configured_domain_name()
return context

View File

@ -29,9 +29,9 @@
{% for shortcut in shortcuts %}
{% if not shortcut.hidden %}
{% if user.is_authenticated or not shortcut.login_required %}
<div class="col-sm-3">
<ul class="nav nav-pills nav-stacked">
{% if selected_id == shortcut.id %}
<div class="col-sm-3">
<ul class="nav nav-pills nav-stacked">
{% if selected_id == shortcut.id %}
<li class="active">
<a href="{{ shortcut.url }}" class="active">
{% else %}