def getUser(request): res = Result() data = {} if request.user.is_anonymous: res.isError = True data["prefs"] = DefaultPrefs elif request.GET.get("q"): return JsonResponse(res.asDict()) else: data["user"] = userToJson(request.user) data["user"]["isManager"] = (any( request.user.groups.filter(name="manager")) or request.user.is_staff) data["gallery"] = None personal = Gallery.objects.filter(owner=request.user, security=Gallery.PERSONAL) if personal: data["personal_gallery"] = personal[0].json() data["prefs"] = request.user.frog_prefs.get_or_create( user=request.user)[0].json() galleryid = request.GET.get("gallery") if galleryid is not None: gallery = Gallery.objects.filter(pk=galleryid, owner=request.user) if gallery: data["gallery"] = gallery[0].json() res.append(data) return JsonResponse(res.asDict())
def post(request): """Sets a key to a value on the currently logged in users preferences :param key: Key to set :type key: str :param val: Value to set :type val: primitive :returns: json """ data = request.POST or json.loads(request.body)['body'] key = data.get('key', None) val = data.get('val', None) res = Result() if key is not None and val is not None: obj, created = UserPref.objects.get_or_create(user=request.user) if created: obj.data = json.dumps(DefaultPrefs.copy()) obj.save() try: val = json.loads(val) except (TypeError, ValueError): pass obj.setKey(key, val) obj.save() res.append(obj.json()) return JsonResponse(res.asDict())
def post(request, obj): try: data = request.POST or json.loads(request.body)['body'] except RawPostDataException: data = request.POST tags = data.get('tags', '').split(',') resetthumbnail = data.get('reset-thumbnail', False) res = Result() for tag in tags: try: t = Tag.objects.get(pk=int(tag)) except ValueError: t, created = Tag.objects.get_or_create(name=tag) if created: res.append(t.json()) obj.tags.add(t) if request.FILES: # -- Handle thumbnail upload f = request.FILES.get('file') relativedest = Path(obj.source.name).parent / f.name dest = getRoot() / relativedest handle_uploaded_file(dest, f) obj.custom_thumbnail = relativedest obj.save() if resetthumbnail: obj.custom_thumbnail = None obj.save() res.value = obj.json() return JsonResponse(res.asDict())
def userList(request): res = Result() users = User.objects.filter(is_active=True) for user in users.order_by("first_name"): res.append(userToJson(user)) return JsonResponse(res.asDict())
def switchArtist(request): data = request.POST or json.loads(request.body)['body'] artist = data.get('artist', None) guids = data.get('guids', '').split(',') res = Result() if artist: if isinstance(artist, int): author = User.objects.get(pk=artist) tag = Tag.objects.get_or_create( name=author.get_full_name().lower(), defaults={'artist': True})[0] else: first, last = artist.lower().split(' ') author = User.objects.get_or_create(first_name=first, last_name=last, defaults={ 'username': '******' % (first[0], last), })[0] tag = Tag.objects.get_or_create(name=artist.lower(), defaults={'artist': True})[0] objects = getObjectsFromGuids(guids) for n in objects: n.author = author n.tagArtist(tag) res.append(userToJson(author)) res.value['tag'] = tag.id return JsonResponse(res.asDict())
def put(request, obj_id=None): """ Adds Image and Video objects to Gallery based on GUIDs """ data = json.loads(request.body)["body"] guids = data.get("guids", "").split(",") move = data.get("from") security = data.get("security") gallery = Gallery.objects.get(pk=obj_id) # Set the security first so subsequent securityChecks will get the correct security level if security is not None: gallery.security = json.loads(security) gallery.save() for child in gallery.gallery_set.all(): child.security = gallery.security child.save() if guids: items = getObjectsFromGuids(guids) gallery.addItems(items) if move: fromgallery = Gallery.objects.get(pk=move) fromgallery.removeItems(items) res = Result() res.append(gallery.json()) return JsonResponse(res.asDict())
def switchArtist(request): data = request.POST or json.loads(request.body)['body'] artist = data.get('artist', None) guids = data.get('guids', '').split(',') res = Result() if artist: if isinstance(artist, int): author = User.objects.get(pk=artist) tag = Tag.objects.get_or_create(name=author.get_full_name().lower(), defaults={'artist': True})[0] else: first, last = artist.lower().split(' ') author = User.objects.get_or_create(first_name=first, last_name=last, defaults={ 'username': '******' % (first[0], last), })[0] tag = Tag.objects.get_or_create(name=artist.lower(), defaults={'artist': True})[0] objects = getObjectsFromGuids(guids) for n in objects: n.author = author n.tagArtist(tag) res.append(userToJson(author)) res.value['tag'] = tag.id return JsonResponse(res.asDict())
def post(request): """Creates a tag object :param name: Name for tag :type name: str :returns: json """ res = Result() name = request.POST.get('name', None) if not name: res.isError = True res.message = "No name given" return JsonResponse(res) tag, created = Tag.objects.get_or_create(name=name) res.isSuccess = True if created: res.message = "Created" res.append(tag.json()) return JsonResponse(res)
def commentList(request): """Returns a rendered list of comments :returns: html """ if request.method == 'POST': return post(request) comments = [] guid = request.GET.get('guid', None) id = request.GET.get('id', 0) if guid: obj = getObjectsFromGuids([guid])[0] if obj.AssetType == 1: model = 'image' else: model = 'video' contentType = ContentType.objects.get(app_label="frog", model=model) comments = Comment.objects.filter(object_pk=obj.id, content_type=contentType) if request.GET.get('json'): res = Result() for comment in comments: res.append(commentToJson(comment)) return JsonResponse(res.asDict()) return render(request, 'frog/comment_list.html', {'comments': comments, 'guid': guid, 'id': id})
def get(request): res = Result() for badge in Badge.objects.all(): res.append(badge.json()) return JsonResponse(res.asDict())
def post(request): res = Result() data = json.loads(request.POST["body"]) tag = Tag.objects.get(name=data['tag']) badge = Badge.objects.get_or_create(tag=tag)[0] if request.FILES.get("image"): incomingfilename = pathlib.Path(request.FILES["image"].name) filename = '{}{}'.format(tag.name, incomingfilename.suffix) dest = getRoot() / "badges" / filename if not dest.parent.exists(): dest.parent.makedirs_p() handle_uploaded_file(dest, request.FILES["image"]) badge.image = "badges/{}".format(filename) if badge: badge.save() res.append(badge.json()) else: res.isError = True res.message = "No badge found" return JsonResponse(res.asDict())
def post(request): """Returns a serialized object""" data = request.POST or json.loads(request.body)['body'] guid = data.get('guid', None) res = Result() if guid: obj = getObjectsFromGuids([guid,])[0] comment = Comment() comment.comment = data.get('comment', 'No comment') comment.user = request.user comment.user_name = request.user.get_full_name() comment.user_email = request.user.email comment.content_object = obj comment.site_id = get_current_site(request).id comment.save() obj.comment_count += 1 obj.save() emailComment(comment, obj, request) res.append(commentToJson(comment)) else: res.isError = True res.message = "No guid provided" return JsonResponse(res.asDict())
def post(request): """Returns a serialized object""" data = request.POST or json.loads(request.body)['body'] guid = data.get('guid', None) res = Result() if guid: obj = getObjectsFromGuids([guid,])[0] comment = Comment() comment.comment = data.get('comment', 'No comment') comment.user = request.user comment.user_name = request.user.get_full_name() comment.user_email = request.user.email comment.content_object = obj comment.site_id = get_current_site(request).id comment.save() obj.comment_count += 1 obj.save() emailComment(comment, obj, request) res.append(commentToJson(comment)) return JsonResponse(res.asDict())
def post(request): """Sets a key to a value on the currently logged in users preferences :param key: Key to set :type key: str :param val: Value to set :type val: primitive :returns: json """ key = request.POST.get('key', None) val = request.POST.get('val', None) res = Result() if key and val: obj, created = UserPref.objects.get_or_create(user=request.user) if created: obj.data = json.dumps(DefaultPrefs.copy()) obj.save() val = json.loads(val) obj.setKey(key, val) obj.save() res.append(obj.json()) res.isSuccess = True else: res.isError = True res.message = 'No key and value provided' return JsonResponse(res)
def post(request): """Creates a tag object :param name: Name for tag :type name: str :returns: json """ res = Result() name = request.POST.get("name", None) if not name: res.isError = True res.message = "No name given" return JsonResponse(res) tag, created = Tag.objects.get_or_create(name=name) res.isSuccess = True if created: res.message = "Created" res.append(tag.json()) return JsonResponse(res)
def post(request): """Returns a serialized object :param obj_id: ID of comment object :type obj_id: int :returns: json """ guid = request.POST.get('guid', None) res = Result() if guid: obj = getObjectsFromGuids([ guid, ])[0] c = Comment() c.comment = request.POST.get('comment', 'No comment') c.user = request.user c.user_name = request.user.get_full_name() c.user_email = request.user.email c.content_object = obj c.site_id = 1 c.save() obj.comment_count = obj.comment_count + 1 obj.save() __email(c, obj) res.append({'id': c.id, 'comment': c.comment}) res.isSuccess = True else: res.isError = True res.message = "No guid provided" return JsonResponse(res)
def getUser(request): res = Result() data = {} if request.user.is_anonymous(): res.isError = True data['prefs'] = DefaultPrefs elif request.GET.get('q'): return JsonResponse(res.asDict()) else: data['user'] = userToJson(request.user) data['user']['isManager'] = any(request.user.groups.filter(name='manager')) or request.user.is_staff data['gallery'] = None personal = Gallery.objects.filter(owner=request.user, security=Gallery.PERSONAL) if personal: data['personal_gallery'] = personal[0].json() data['prefs'] = request.user.frog_prefs.get_or_create(user=request.user)[0].json() galleryid = request.GET.get('gallery') if galleryid is not None: gallery = Gallery.objects.filter(pk=galleryid, owner=request.user) if gallery: data['gallery'] = gallery[0].json() res.append(data) return JsonResponse(res.asDict())
def userList(request): res = Result() for user in User.objects.filter(is_active=True).order_by('first_name'): res.append(userToJson(user)) return JsonResponse(res.asDict())
def put(request, obj_id=None): """ Adds Image and Video objects to Gallery based on GUIDs """ data = request.PUT or json.loads(request.body)['body'] guids = data.get('guids', '').split(',') move = data.get('from') security = request.PUT.get('security') gallery = Gallery.objects.get(pk=obj_id) if guids: objects = getObjectsFromGuids(guids) images = filter(lambda x: isinstance(x, Image), objects) videos = filter(lambda x: isinstance(x, Video), objects) gallery.images.add(*images) gallery.videos.add(*videos) if move: fromgallery = Gallery.objects.get(pk=move) fromgallery.images.remove(*images) fromgallery.videos.remove(*videos) if security is not None: gallery.security = json.loads(security) gallery.save() for child in gallery.gallery_set.all(): child.security = gallery.security child.save() res = Result() res.append(gallery.json()) return JsonResponse(res.asDict())
def delete(request, obj): obj.deleted = True obj.save() res = Result() res.append(obj.json()) return JsonResponse(res.asDict())
def post(request): """Returns a serialized object""" data = json.loads(request.body)["body"] guid = data.get("guid", None) res = Result() if guid: obj = getObjectsFromGuids([guid])[0] comment = Comment() comment.comment = data.get("comment", "No comment") comment.user = request.user comment.user_name = request.user.get_full_name() comment.user_email = request.user.email comment.content_object = obj # For our purposes, we never have more than one site comment.site_id = 1 comment.save() obj.comment_count += 1 obj.save() emailComment(comment, obj, request) res.append(commentToJson(comment)) return JsonResponse(res.asDict())
def csrf(request): res = Result() try: res.append(request.COOKIES["csrftoken"]) except KeyError: pass return JsonResponse(res.asDict())
def switchArtist(request): data = request.POST or json.loads(request.body)["body"] artist = data.get("artist", None) guids = data.get("guids", "").split(",") res = Result() if artist: if isinstance(artist, int): author = User.objects.get(pk=artist) tag = Tag.objects.get_or_create( name=author.get_full_name().lower(), defaults={"artist": True})[0] else: first, last = artist.lower().split(" ") author = User.objects.get_or_create( first_name=first, last_name=last, defaults={"username": "******" % (first[0], last)}, )[0] tag = Tag.objects.get_or_create(name=artist.lower(), defaults={"artist": True})[0] objects = getObjectsFromGuids(guids) for n in objects: n.author = author n.tagArtist(tag) res.append(userToJson(author)) res.value["tag"] = tag.id return JsonResponse(res.asDict())
def post(request): """Returns a serialized object :param obj_id: ID of comment object :type obj_id: int :returns: json """ guid = request.POST.get('guid', None) res = Result() if guid: obj = getObjectsFromGuids([guid,])[0] c = Comment() c.comment = request.POST.get('comment', 'No comment') c.user = request.user c.user_name = request.user.get_full_name() c.user_email = request.user.email c.content_object = obj c.site_id = 1 c.save() obj.comment_count = obj.comment_count + 1 obj.save() __email(c, obj) res.append({'id': c.id, 'comment': c.comment}) res.isSuccess = True else: res.isError = True res.message = "No guid provided" return JsonResponse(res)
def post(request): """ Create a Gallery """ defaultname = 'New Gallery %i' % Gallery.objects.all().count() title = request.POST.get('title', defaultname) description = request.POST.get('description', '') security = int(request.POST.get('security', Gallery.PUBLIC)) parentid = request.POST.get('parent') if parentid: parent = Gallery.objects.get(pk=int(parentid)) g, created = parent.gallery_set.get_or_create(title=title) g.security = parent.security else: g, created = Gallery.objects.get_or_create(title=title) g.security = security g.description = description g.owner = request.user g.save() res = Result() res.isSuccess = True res.append(g.json()) res.message = 'Gallery created' if created else '' return JsonResponse(res)
def put(request, obj_id=None): """ Adds Image and Video objects to Gallery based on GUIDs """ guids = filter(None, request.PUT.get('guids', '').split(',')) security = request.PUT.get('security') object_ = Gallery.objects.get(pk=obj_id) if guids: objects = getObjectsFromGuids(guids) images = filter(lambda x: isinstance(x, Image), objects) videos = filter(lambda x: isinstance(x, Video), objects) object_.images.add(*images) object_.videos.add(*videos) if security is not None: object_.security = json.loads(security) object_.save() for child in object_.gallery_set.all(): child.security = object_.security child.save() res = Result() res.append(object_.json()) res.isSuccess = True return JsonResponse(res)
def post(request): res = Result() config = SiteConfig.getSiteConfig() try: data = json.loads(request.body)["body"] config.name = data.get("name", config.name) config.link = data.get("link", config.link) config.enable_likes = data.get("enable_likes", config.enable_likes) if data.get("default_gallery"): gallery = Gallery.objects.get(pk=data["default_gallery"]) config.default_gallery = gallery except RawPostDataException: if request.FILES.get("favicon"): dest = getRoot() / "favicon.ico" handle_uploaded_file(dest, request.FILES["favicon"]) config.favicon = "favicon.ico" if request.FILES.get("icon"): dest = getRoot() / request.FILES["icon"].name handle_uploaded_file(dest, request.FILES["icon"]) config.favicon = request.FILES["icon"].name config.save() res.append(SiteConfig.getSiteConfig().json()) return JsonResponse(res.asDict())
def post(request): """Creates a tag object :param name: Name for tag :type name: str :returns: json """ res = Result() data = request.POST or json.loads(request.body)['body'] name = data.get('name', None) if not name: res.isError = True res.message = "No name given" return JsonResponse(res.asDict()) tag, created = Tag.objects.get_or_create(name=name.lower()) if created: res.message = "Created" else: res.isError = True res.append(tag.json()) return JsonResponse(res.asDict())
def csrf(request): res = Result() try: res.append(request.COOKIES['csrftoken']) except KeyError: pass return JsonResponse(res.asDict())
def getGuids(request): res = Result() guids = request.GET.get('guids', '').split(',') for _ in getObjectsFromGuids(guids): res.append(_.json()) return JsonResponse(res.asDict())
def getGuids(request): res = Result() data = {} guids = request.GET.get('guids', '').split(',') for _ in getObjectsFromGuids(guids): res.append(_.json()) return JsonResponse(res.asDict())
def put(request, obj): data = request.POST or json.loads(request.body)['body'] obj.title = data.get('title', obj.title) obj.description = data.get('description', obj.description) obj.save() res = Result() res.append(obj.json()) return JsonResponse(res.asDict())
def resolve(request, name): res = Result() tag = Tag.objects.filter(name__iexact=name) if tag: res.append(tag[0].json()) else: res.isError = True return JsonResponse(res.asDict())
def get(request): """Gets the currently logged in users preferences :returns: json """ res = Result() obj, created = UserPref.objects.get_or_create(user=request.user, defaults={'data': json.dumps(DefaultPrefs.copy())}) res.append(obj.json()) return JsonResponse(res.asDict())
def manage(request): if request.method == 'GET': guids = request.GET.get('guids', '').split(',') guids = [guid for guid in guids if guid] objects = getObjectsFromGuids(guids) ids = [o.id for o in objects] imgtags = list(Tag.objects.filter(image__id__in=ids).exclude(artist=True)) vidtags = list(Tag.objects.filter(video__id__in=ids).exclude(artist=True)) tags = list(set(imgtags + vidtags)) if request.GET.get('json', False): res = Result() data = { 'queries': connection.queries, } res.append(data) return JsonResponse(res.asDict()) return render(request, 'frog/tag_manage.html', {'tags': tags}) else: res = Result() data = request.POST or json.loads(request.body)['body'] add = data.get('add', '').split(',') rem = data.get('rem', '').split(',') guids = data.get('guids', '').split(',') add = [a for a in add if a] rem = [r for r in rem if r] addList = [] for t in add: try: addList.append(int(t)) except ValueError: tag = Tag.objects.get_or_create(name=t.lower())[0] tag.save() addList.append(tag.id) objects = getObjectsFromGuids(guids) addTags = Tag.objects.filter(id__in=addList) remTags = Tag.objects.filter(id__in=rem) for o in objects: for a in addTags: o.tags.add(a) for r in remTags: o.tags.remove(r) res.append(o.json()) return JsonResponse(res.asDict())
def manage(request): if request.method == "GET": guids = request.GET.get("guids", "").split(",") guids = [guid for guid in guids if guid] objects = getObjectsFromGuids(guids) ids = [o.id for o in objects] imgtags = list( Tag.objects.filter(image__id__in=ids).exclude(artist=True)) vidtags = list( Tag.objects.filter(video__id__in=ids).exclude(artist=True)) tags = list(set(imgtags + vidtags)) if request.GET.get("json", False): res = Result() data = {"queries": connection.queries} res.append(data) return JsonResponse(res.asDict()) return render(request, "frog/tag_manage.html", {"tags": tags}) else: res = Result() data = request.POST or json.loads(request.body)["body"] add = data.get("add", "").split(",") rem = data.get("rem", "").split(",") guids = data.get("guids", "").split(",") add = [a for a in add if a] rem = [r for r in rem if r] addList = [] for t in add: try: addList.append(int(t)) except ValueError: tag = Tag.objects.get_or_create(name=t.lower())[0] tag.save() addList.append(tag.id) objects = getObjectsFromGuids(guids) addTags = Tag.objects.filter(id__in=addList) remTags = Tag.objects.filter(id__in=rem) for o in objects: for a in addTags: o.tags.add(a) for r in remTags: o.tags.remove(r) res.append(o.json()) return JsonResponse(res.asDict())
def get(request, obj_id): """Returns a serialized object :param obj_id: ID of comment object :type obj_id: int :returns: json """ res = Result() c = Comment.objects.get(pk=obj_id) res.append(commentToJson(c)) return JsonResponse(res.asDict())
def put(request, obj): for key, value in json.loads(request.body)["body"].items(): if hasattr(obj, key): setattr(obj, key, value) obj.save() res = Result() res.append(obj.json()) return JsonResponse(res.asDict())
def like(request, guid): obj = Piece.fromGuid(guid) res = Result() if obj.like(request): emailLike(request, obj) else: res.message = 'Cannot "like" things more than once' res.append(obj.json()) return JsonResponse(res.asDict())
def artistLookup(request): res = Result() query = request.GET.get('query', False) if query: users = User.objects.filter(first_name__icontains=query.lower()) else: users = User.objects.all() for user in users: res.append(userToJson(user)) return JsonResponse(res.values)
def releaseNotes(request): res = Result() lastid = request.GET.get('lastid', 0) today = datetime.datetime.today() relevent = today - datetime.timedelta(days=30) notes = ReleaseNotes.objects.filter(date__gte=relevent, pk__gt=lastid).order_by('-id') for note in notes: res.append(note.json()) return JsonResponse(res.asDict())
def like(request, guid): obj = Piece.fromGuid(guid) res = Result() if obj.like(request): emailLike(request, obj) else: res.isError = True res.message = 'Cannot "like" things more than once' res.append(obj.json()) return JsonResponse(res.asDict())
def data(request, guid): obj = Piece.fromGuid(guid) if request.method == "GET": res = Result() res.append(obj.json()) return JsonResponse(res.asDict()) elif request.method == "POST": return post(request, obj) elif request.method == "PUT": return put(request, obj) elif request.method == "DELETE": return delete(request, obj)
def get(request): """Gets the currently logged in users preferences :returns: json """ res = Result() obj, created = UserPref.objects.get_or_create(user=request.user, defaults={'data': json.dumps(DefaultPrefs.copy())}) data = obj.json() data['subscriptions'] = [_.json() for _ in GallerySubscription.objects.filter(user=request.user)] res.append(data) return JsonResponse(res.asDict())
def get(request): """Gets the currently logged in users preferences :returns: json """ res = Result() obj, created = UserPref.objects.get_or_create(user=request.user) if created: obj.data = json.dumps(DefaultPrefs.copy()) obj.save() res.append(obj.json()) res.isSuccess = True return JsonResponse(res)
def resolve(request, name): res = Result() tag = Tag.objects.filter(name__iexact=name) if not tag: try: tag = Tag.objects.filter(Q(id=name)) except ValueError: pass if tag: res.append(tag[0].json()) return JsonResponse(res.asDict())
def getUser(request): res = Result() if request.user.is_anonymous(): res.isError = True res.append(DefaultPrefs) else: galleryid = request.GET.get('gallery') if galleryid is not None: gallery = Gallery.objects.filter(pk=galleryid, owner=request.user) if gallery: res.append(gallery[0].json()) res.isSuccess = True return JsonResponse(res)
def data(request, guid): obj = Piece.fromGuid(guid) if request.method == 'GET': res = Result() res.append(obj.json()) return JsonResponse(res.asDict()) elif request.method == 'POST': return post(request, obj) elif request.method == 'PUT': getPutData(request) return put(request, obj) elif request.method == 'DELETE': getPutData(request) return delete(request, obj)