Ejemplo n.º 1
0
def cache(request, cache, path):
    path = unquote(path)
    if cache not in fEs.CACHE_TYPES:
        raise Http404
    entity = fEs.by_path(path)
    if entity is None:
        raise Http404
    user = request.user if request.user.is_authenticated() else None
    if not entity.may_view(user):
        if user is None:
            # user is not logged in
            return redirect_to_login(request.get_full_path())
        raise PermissionDenied
    entity.ensure_cached(cache)
    st = os.stat(entity.get_cache_path(cache))
    lm = strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime(st.st_mtime))
    if request.META.get('HTTP_IF_MODIFIED_SINCE', None) == lm:
        return HttpResponseNotModified()
    cc = 'max-age=30780000'  # Cache-Control header
    if not entity.may_view(None):
        # not publicly cacheable
        cc = 'private, ' + cc
    resp = HttpResponse(FileWrapper(open(entity.get_cache_path(cache), 'rb')),
                        content_type=entity.get_cache_mimetype(cache))
    resp['Content-Length'] = str(st.st_size)
    resp['Last-Modified'] = lm
    resp['Cache-Control'] = cc
    return resp
Ejemplo n.º 2
0
def cache(request, cache, path):
    path = unquote(path)
    if cache not in fEs.CACHE_TYPES:
        raise Http404
    entity = fEs.by_path(path)
    if entity is None:
        raise Http404
    user = request.user if request.user.is_authenticated() else None
    if not entity.may_view(user):
        if user is None:
            # user is not logged in
            return redirect_to_login(request.get_full_path())
        raise PermissionDenied
    entity.ensure_cached(cache)
    st = os.stat(entity.get_cache_path(cache))
    lm = strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime(st.st_mtime))
    if request.META.get('HTTP_IF_MODIFIED_SINCE', None) == lm:
        return HttpResponseNotModified()
    cc = 'max-age=30780000'  # Cache-Control header
    if not entity.may_view(None):
        # not publicly cacheable
        cc = 'private, ' + cc
    resp = HttpResponse(FileWrapper(open(entity.get_cache_path(cache), 'rb')),
                        content_type=entity.get_cache_mimetype(cache))
    resp['Content-Length'] = str(st.st_size)
    resp['Last-Modified'] = lm
    resp['Cache-Control'] = cc
    return resp
Ejemplo n.º 3
0
def entity_from_request(data):
    if 'path' not in data:
        return 'Missing path attribute'
    if not isinstance(data['path'], six.string_types):
        return 'path should be string'
    entity = fEs.by_path(data['path'])
    if entity is None:
        return 'Object not found'
    return entity
Ejemplo n.º 4
0
def entity_from_request(data):
    if 'path' not in data:
        return 'Missing path attribute'
    if not isinstance(data['path'], basestring):
        return 'path should be string'
    entity = fEs.by_path(data['path'])
    if entity is None:
        return 'Object not found'
    return entity
Ejemplo n.º 5
0
def scan_fotos():
    album = fEs.by_path('')
    if album is None:
        album = fEs.entity({
            'type': 'album',
            'name': '',
            'path': None,
            'random': random.random(),
            'title': 'Karpe Noktem fotoalbum',
            'description': "De fotocollectie van Karpe Noktem",
            'visibility': ['world']
        })
        album.update_metadata(None)
        album.save()
    elif album.update_metadata(None):
        album.save()
    scan_album(album)
Ejemplo n.º 6
0
def scan_fotos():
    album = fEs.by_path('')
    if album is None:
        album = fEs.entity({
            'type': 'album',
            'name': '',
            'path': None,
            'random': random.random(),
            'title': 'Karpe Noktem fotoalbum',
            'description': "De fotocollectie van Karpe Noktem",
            'visibility': ['world']})
        album.update_metadata(None)
        album.save()
    elif album.update_metadata(None):
        album.save()
    scan_album(album)

    return {'success': True}
Ejemplo n.º 7
0
def scan_fotos():
    album = fEs.by_path("")
    if album is None:
        album = fEs.entity(
            {
                "type": "album",
                "name": "",
                "path": None,
                "random": random.random(),
                "title": "Karpe Noktem fotoalbum",
                "description": "De fotocollectie van Karpe Noktem",
                "visibility": ["world"],
            }
        )
        album.update_metadata(None)
        album.save()
    elif album.update_metadata(None):
        album.save()
    scan_album(album)

    return {"success": True}
Ejemplo n.º 8
0
def main():
    fEs.ensure_indices()
    creds = settings.PHOTOS_MYSQL_SECRET
    dc = MySQLdb.connect(creds[0], user=creds[1], passwd=creds[2], db=creds[3])
    c = dc.cursor()

    if fEs.by_path('') is None:
        root = fEs.entity({
            'type': 'album',
            'path': None,
            'name': '',
            'title': 'Karpe Noktem fotoalbum',
            'description': "De fotocollectie van Karpe Noktem",
            'random': random.random(),
            'visibility': ['world']
        })
        root.update_metadata(None, save=False)
        root.save()

    print('albums')
    c.execute("SELECT id, name, path, humanname, visibility, description " +
              "FROM fa_albums ORDER BY path")
    for oldId, name, path, humanName, visibility, description in c.fetchall():
        if path and not path.endswith('/'):
            continue
        if fEs.by_oldId('album', oldId) is not None:
            continue

        data = {
            'type': 'album',
            'oldId': oldId,
            'path': path.strip('/'),
            'name': name,
            'title': humanName,
            'description': description,
            'random': random.random()
        }

        if visibility == 'lost':
            visibility = []
            data['lost'] = True
        elif visibility == 'deleted':
            visibility = []
        else:
            visibility = [visibility]
        data['visibility'] = visibility

        album = fEs.entity(data)
        album.update_metadata(album.get_parent(), save=False)
        album.save()

    print('fotos')
    c.execute("SELECT id, name, path, visibility, rotation FROM fa_photos")
    for oldId, name, path, visibility, rotation in c.fetchall():
        if fEs.by_oldId('foto', oldId) is not None:
            continue

        data = {
            'type': 'foto',
            'oldId': oldId,
            'path': path.strip('/'),
            'name': name,
            'random': random.random(),
            'rotation': rotation
        }

        if visibility == 'lost':
            visibility = []
            data['lost'] = True
        elif visibility == 'deleted':
            visibility = []
        else:
            visibility = [visibility]
        data['visibility'] = visibility

        foto = fEs.entity(data)
        foto.update_metadata(foto.get_parent(), save=False)
        foto.save()

    print('tags')
    c.execute("SELECT photo_id, username FROM fa_tags")
    for oldId, username in c.fetchall():
        foto = fEs.by_oldId('foto', oldId)
        if foto is None:
            continue

        user = Es.by_name(username)
        if user is None:
            continue

        if 'tags' not in foto._data:
            foto._data['tags'] = []
        if user._id not in foto._data['tags']:
            foto._data['tags'].append(user._id)
            foto.save()

    print('done')
Ejemplo n.º 9
0
def list_events():
    events = []
    for album in fEs.by_path('').list_all():
        events.append(album.name)
    events.sort(reverse=True)
    return events
Ejemplo n.º 10
0
def fotos(request, path=''):
    path = unquote(path)

    if any(k in request.GET for k in ['album', 'search_album', 'search_tag']):
        # redirect old URL
        path = request.GET.get('album', '')
        q = None
        if request.GET.get('search_album'):
            q = 'album:' + request.GET.get('search_album')
        if request.GET.get('search_tag'):
            q = 'tag:' + request.GET.get('search_tag')
        url = reverse('fotos', kwargs={'path': path})
        if q is not None:
            qs = QueryDict('', mutable=True)
            qs['q'] = q
            url += '?' + qs.urlencode()
        return redirect(url, permanent=True)

    album = fEs.by_path(path)
    if album is None:
        bits = path.rsplit('/', 1)
        if len(bits) == 2:
            path = bits[0]
            name = bits[1].replace('+', ' ')
            entity = fEs.by_path_and_name(path, name)
            if entity is not None:
                # Zen Photo used + signs in the filename part of the URL.
                url = reverse('fotos', kwargs={'path': path}) \
                    + '#' + filepath_to_uri(name)
                return redirect(url, permanent=True)
        raise Http404

    if album._type != 'album':
        # This is a photo, not an album.
        # Backwards compatibility, probably to Zen Photo.
        url = reverse('fotos', kwargs={'path': album.path}) \
            + '#' + filepath_to_uri(album.name)
        return redirect(url, permanent=True)

    user = request.user if request.user.is_authenticated() else None

    if not album.may_view(user) and user is None:
        # user is not logged in
        return redirect_to_login(request.get_full_path())

    if not album.may_view(user):
        # user is logged in, but may not view the album
        title = album.title
        if not title:
            title = album.name
        # respond with a nice error message
        response = render_to_response(
            'fotos/fotos.html',
            {'fotos': {'parents': album_parents_json(album)},
             'error': 'permission-denied'},
            context_instance=RequestContext(request)
        )
        response.status_code = 403
        return response

    if 'download' in request.GET:
        if album.is_root:
            # Downloading ALL photos would be way too much
            raise PermissionDenied
        download = ZipSeeker()
        add_download_files(download, album, album.full_path, user)
        response = StreamingHttpResponse(download.blocks(),
                                         content_type='application/zip')
        response['Content-Length'] = download.size()
        response['Last-Modified'] = http_date(download.lastModified())
        # TODO: human-readable download name?
        response['Content-Disposition'] = 'attachment; filename=' + \
            album.name + '.zip'
        return response

    people = None
    if fEs.is_admin(user):
        # Get all members (now or in the past), and sort them first
        # by whether they are active (active members first) and
        # then by their name.
        humanNames = {}
        active = []
        inactive = []
        for u in Es.users():
            humanNames[str(u.name)] = six.text_type(u.humanName)
            if u.is_active:
                active.append(str(u.name))
            else:
                inactive.append(str(u.name))
        active.sort()
        inactive.sort()
        people = []
        for name in active + inactive:
            people.append((name, humanNames[name]))

    fotos = album_json(album, user)
    return render_to_response('fotos/fotos.html',
                              {'fotos': fotos,
                               'fotos_admin': fEs.is_admin(user),
                               'people': people},
                              context_instance=RequestContext(request))
Ejemplo n.º 11
0
def fotos(request, path=''):
    path = unquote(path)

    if any(k in request.GET for k in ['album', 'search_album', 'search_tag']):
        # redirect old URL
        path = request.GET.get('album', '')
        q = None
        if request.GET.get('search_album'):
            q = 'album:' + request.GET.get('search_album')
        if request.GET.get('search_tag'):
            q = 'tag:' + request.GET.get('search_tag')
        url = reverse('fotos', kwargs={'path':path})
        if q is not None:
            qs = QueryDict('', mutable=True)
            qs['q'] = q
            url += '?' + qs.urlencode()
        return redirect(url, permanent=True)

    album = fEs.by_path(path)
    if album is None:
        bits = path.rsplit('/', 1)
        if len(bits) == 2:
            path = bits[0]
            name = bits[1].replace('+', ' ')
            entity = fEs.by_path_and_name(path, name)
            if entity is not None:
                # Zen Photo used + signs in the filename part of the URL.
                url = reverse('fotos', kwargs={'path':path}) \
                        + '#'+filepath_to_uri(name)
                return redirect(url, permanent=True)
        raise Http404

    if album._type != 'album':
        # This is a photo, not an album.
        # Backwards compatibility, probably to Zen Photo.
        url = reverse('fotos', kwargs={'path':album.path}) \
                + '#'+filepath_to_uri(album.name)
        return redirect(url, permanent=True)

    user = request.user if request.user.is_authenticated() else None

    if not album.may_view(user) and user is None:
        # user is not logged in
        return redirect_to_login(request.get_full_path())

    if not album.may_view(user):
        # user is logged in, but may not view the album
        title = album.title
        if not title:
            title = album.name
        # respond with a nice error message
        response = render_to_response('fotos/fotos.html',
                  {'fotos': {'parents': album_parents_json(album)},
                   'error': 'permission-denied'},
                  context_instance=RequestContext(request))
        response.status_code = 403
        return response

    people = None
    if fEs.is_admin(user):
        # Get all members (now or in the past), and sort them first by whether they
        # are active (active members first) and then by their name.
        humanNames = {}
        active = []
        inactive = []
        for u in Es.users():
            humanNames[str(u.name)] = unicode(u.humanName)
            if u.is_active:
                active.append(str(u.name))
            else:
                inactive.append(str(u.name))
        active.sort()
        inactive.sort()
        people = []
        for name in active+inactive:
            people.append((name, humanNames[name]))

    fotos = album_json(album, user)
    return render_to_response('fotos/fotos.html',
             {'fotos': fotos,
              'fotos_admin': fEs.is_admin(user),
              'people': people},
             context_instance=RequestContext(request))
Ejemplo n.º 12
0
def fotos(request, path=''):
    path = unquote(path)

    if any(k in request.GET for k in ['album', 'search_album', 'search_tag']):
        # redirect old URL
        path = request.GET.get('album', '')
        q = None
        if request.GET.get('search_album'):
            q = 'album:' + request.GET.get('search_album')
        if request.GET.get('search_tag'):
            q = 'tag:' + request.GET.get('search_tag')
        url = reverse('fotos', kwargs={'path': path})
        if q is not None:
            qs = QueryDict('', mutable=True)
            qs['q'] = q
            url += '?' + qs.urlencode()
        return redirect(url, permanent=True)

    album = fEs.by_path(path)
    if album is None:
        bits = path.rsplit('/', 1)
        if len(bits) == 2:
            path = bits[0]
            name = bits[1].replace('+', ' ')
            entity = fEs.by_path_and_name(path, name)
            if entity is not None:
                # Zen Photo used + signs in the filename part of the URL.
                url = reverse('fotos', kwargs={'path': path}) \
                    + '#' + filepath_to_uri(name)
                return redirect(url, permanent=True)
        raise Http404

    if album._type != 'album':
        # This is a photo, not an album.
        # Backwards compatibility, probably to Zen Photo.
        url = reverse('fotos', kwargs={'path': album.path}) \
            + '#' + filepath_to_uri(album.name)
        return redirect(url, permanent=True)

    user = request.user if request.user.is_authenticated() else None

    if not album.may_view(user) and user is None:
        # user is not logged in
        return redirect_to_login(request.get_full_path())

    if not album.may_view(user):
        # user is logged in, but may not view the album
        title = album.title
        if not title:
            title = album.name
        # respond with a nice error message
        response = render(
            request,
            'fotos/fotos.html',
            {'fotos': {'parents': album_parents_json(album)},
             'error': 'permission-denied'},
        )
        response.status_code = 403
        return response

    if 'download' in request.GET:
        if album.is_root:
            # Downloading ALL photos would be way too much
            raise PermissionDenied
        download = ZipSeeker()
        add_download_files(download, album, album.full_path, user)
        response = StreamingHttpResponse(download.blocks(),
                                         content_type='application/zip')
        response['Content-Length'] = download.size()
        response['Last-Modified'] = http_date(download.lastModified())
        # TODO: human-readable download name?
        response['Content-Disposition'] = 'attachment; filename=' + \
            album.name + '.zip'
        return response

    people = None
    if fEs.is_admin(user):
        # Get all members (now or in the past), and sort them first
        # by whether they are active (active members first) and
        # then by their name.
        humanNames = {}
        active = []
        inactive = []
        for u in Es.users():
            humanNames[str(u.name)] = six.text_type(u.humanName)
            if u.is_active:
                active.append(str(u.name))
            else:
                inactive.append(str(u.name))
        active.sort()
        inactive.sort()
        people = []
        for name in active + inactive:
            people.append((name, humanNames[name]))

    fotos = album_json(album, user)
    return render(request, 'fotos/fotos.html',
                  {'fotos': fotos,
                   'fotos_admin': fEs.is_admin(user),
                   'people': people})
Ejemplo n.º 13
0
def list_events():
    events = []
    for album in fEs.by_path('').list_all():
        events.append(album.name)
    events.sort(reverse=True)
    return events
def main():
    fEs.ensure_indices()
    creds = settings.PHOTOS_MYSQL_SECRET
    dc = MySQLdb.connect(creds[0], user=creds[1], passwd=creds[2], db=creds[3])
    c = dc.cursor()

    if fEs.by_path('') is None:
        root = fEs.entity({
            'type': 'album',
            'path': None,
            'name': '',
            'title': 'Karpe Noktem fotoalbum',
            'description': "De fotocollectie van Karpe Noktem",
            'random': random.random(),
            'visibility': ['world']})
        root.update_metadata(None, save=False)
        root.save()

    print 'albums'
    c.execute("SELECT id, name, path, humanname, visibility, description "
                        + "FROM fa_albums ORDER BY path")
    for oldId, name, path, humanName, visibility, description in c.fetchall():
        if path and not path.endswith('/'):
            continue
        if fEs.by_oldId('album', oldId) is not None:
            continue

        data = {'type': 'album',
                'oldId': oldId,
                'path': path.strip('/'),
                'name': name,
                'title': humanName,
                'description': description,
                'random': random.random()}

        if visibility == 'lost':
            visibility = []
            data['lost'] = True
        elif visibility == 'deleted':
            visibility = []
        else:
            visibility = [visibility]
        data['visibility'] = visibility

        album = fEs.entity(data)
        album.update_metadata(album.get_parent(), save=False)
        album.save()

    print 'fotos'
    c.execute("SELECT id, name, path, visibility, rotation FROM fa_photos")
    for oldId, name, path, visibility, rotation in c.fetchall():
        if fEs.by_oldId('foto', oldId) is not None:
            continue

        data = {'type': 'foto',
                'oldId': oldId,
                'path': path.strip('/'),
                'name': name,
                'random': random.random(),
                'rotation': rotation}

        if visibility == 'lost':
            visibility = []
            data['lost'] = True
        elif visibility == 'deleted':
            visibility = []
        else:
            visibility = [visibility]
        data['visibility'] = visibility

        foto = fEs.entity(data)
        foto.update_metadata(foto.get_parent(), save=False)
        foto.save()

    print 'tags'
    c.execute("SELECT photo_id, username FROM fa_tags")
    for oldId, username in c.fetchall():
        foto = fEs.by_oldId('foto', oldId)
        if foto is None:
            continue

        user = Es.by_name(username)
        if user is None:
            continue

        if not 'tags' in foto._data:
            foto._data['tags'] = []
        if not user._id in foto._data['tags']:
            foto._data['tags'].append(user._id)
            foto.save()

    print 'done'