We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
API: Device Synchronization API - Start / Stop Sync returning HTTP status 500
During my work on PR https://github.com/gpodder/mygpo/pull/122 is was testing the Device Synchronization API - Start / Stop Sync (https://gpoddernet.readthedocs.io/en/latest/api/reference/sync.html#post--api-2-sync-devices-(username).json)

I sent the following request
```json
{
  "synchronize": [
    [
      "my-desktop", "cellphone"
    ]
  ]
}
```

and it is returning HTTP 500
```html
<html>
    <head>
        <title>500 Internal server error (gpodder.net)</title>
        <link rel="stylesheet" type="text/css" href="/static/css/fail.css" />
    </head>
    <body>
        <div id="c">
            <div id="fail">
                <h1>500 - Internal server error.</h1>
                <p>
                The service is currently overloaded.
                Please try again later or contact us.
                </p>
            </div>
        </div>
        <img id="icon" src="/static/failpodder.png">
    </body>
</html>
```

as a reference, a previous call to https://gpoddernet.readthedocs.io/en/latest/api/reference/sync.html#get--api-2-sync-devices-(username).json was returning:
```json
{
  "synchronized": [],
  "not-synchronized": [
    "cellphone",
    "my-desktop"
  ]
}
```

I'm able ot sync this devices on the web ui though.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `mygpo/api/advanced/sync.py`
Content:
```
1 from django.http import HttpResponseBadRequest, HttpResponseNotFound
2 from django.views.decorators.csrf import csrf_exempt
3 from django.views.decorators.cache import never_cache
4 
5 from mygpo.decorators import allowed_methods, cors_origin
6 from mygpo.utils import parse_request_body
7 from mygpo.api.basic_auth import require_valid_user, check_username
8 from mygpo.api.httpresponse import JsonResponse
9 from mygpo.users.models import Client, UserProxy
10 from mygpo.users.tasks import sync_user
11 
12 
13 @csrf_exempt
14 @require_valid_user
15 @check_username
16 @never_cache
17 @allowed_methods(["GET", "POST"])
18 @cors_origin()
19 def main(request, username):
20     """ API Endpoint for Device Synchronisation """
21 
22     if request.method == "GET":
23         return JsonResponse(get_sync_status(request.user))
24 
25     else:
26         try:
27             actions = parse_request_body(request)
28         except ValueError as e:
29             return HttpResponseBadRequest(str(e))
30 
31         synclist = actions.get("synchronize", [])
32         stopsync = actions.get("stop-synchronize", [])
33 
34         try:
35             update_sync_status(request.user, synclist, stopsync)
36         except ValueError as e:
37             return HttpResponseBadRequest(str(e))
38         except Client.DoesNotExist as e:
39             return HttpResponseNotFound(str(e))
40 
41         return JsonResponse(get_sync_status(user))
42 
43 
44 def get_sync_status(user):
45     """ Returns the current Device Sync status """
46 
47     sync_groups = []
48     unsynced = []
49 
50     user = UserProxy.objects.from_user(user)
51     for group in user.get_grouped_devices():
52         uids = [device.uid for device in group.devices]
53 
54         if group.is_synced:
55             sync_groups.append(uids)
56 
57         else:
58             unsynced = uids
59 
60     return {"synchronized": sync_groups, "not-synchronized": unsynced}
61 
62 
63 def update_sync_status(user, synclist, stopsync):
64     """Updates the current Device Sync status
65 
66     Synchronisation between devices can be set up and stopped.  Devices are
67     identified by their UIDs. Unknown UIDs cause errors, no new devices are
68     created."""
69 
70     for devlist in synclist:
71 
72         if len(devlist) <= 1:
73             raise ValueError("at least two devices are needed to sync")
74 
75         # Setup all devices to sync with the first in the list
76         uid = devlist[0]
77         dev = user.client_set.get(uid=uid)
78 
79         for other_uid in devlist[1:]:
80             other = user.get_device_by_uid(other_uid)
81             dev.sync_with(other)
82 
83     for uid in stopsync:
84         dev = user.get_device_by_uid(uid)
85         try:
86             dev.stop_sync()
87         except ValueError:
88             # if all devices of a sync-group are un-synced,
89             # the last one will raise a ValueError, because it is no longer
90             # being synced -- we just ignore it
91             pass
92 
93     user.save()
94 
95     sync_user.delay(user)
96
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/mygpo/api/advanced/sync.py b/mygpo/api/advanced/sync.py
--- a/mygpo/api/advanced/sync.py
+++ b/mygpo/api/advanced/sync.py
@@ -38,7 +38,7 @@
         except Client.DoesNotExist as e:
             return HttpResponseNotFound(str(e))
 
-        return JsonResponse(get_sync_status(user))
+        return JsonResponse(get_sync_status(request.user))
 
 
 def get_sync_status(user):
@@ -77,11 +77,11 @@
         dev = user.client_set.get(uid=uid)
 
         for other_uid in devlist[1:]:
-            other = user.get_device_by_uid(other_uid)
+            other = user.client_set.get(uid=other_uid)
             dev.sync_with(other)
 
     for uid in stopsync:
-        dev = user.get_device_by_uid(uid)
+        dev = user.client_set.get(uid=uid)
         try:
             dev.stop_sync()
         except ValueError:

{"golden_diff": "diff --git a/mygpo/api/advanced/sync.py b/mygpo/api/advanced/sync.py\n--- a/mygpo/api/advanced/sync.py\n+++ b/mygpo/api/advanced/sync.py\n@@ -38,7 +38,7 @@\n         except Client.DoesNotExist as e:\n             return HttpResponseNotFound(str(e))\n \n-        return JsonResponse(get_sync_status(user))\n+        return JsonResponse(get_sync_status(request.user))\n \n \n def get_sync_status(user):\n@@ -77,11 +77,11 @@\n         dev = user.client_set.get(uid=uid)\n \n         for other_uid in devlist[1:]:\n-            other = user.get_device_by_uid(other_uid)\n+            other = user.client_set.get(uid=other_uid)\n             dev.sync_with(other)\n \n     for uid in stopsync:\n-        dev = user.get_device_by_uid(uid)\n+        dev = user.client_set.get(uid=uid)\n         try:\n             dev.stop_sync()\n         except ValueError:\n", "issue": "API: Device Synchronization API - Start / Stop Sync returning HTTP status 500\nDuring my work on PR https://github.com/gpodder/mygpo/pull/122 is was testing the Device Synchronization API - Start / Stop Sync (https://gpoddernet.readthedocs.io/en/latest/api/reference/sync.html#post--api-2-sync-devices-(username).json)\r\n\r\nI sent the following request\r\n```json\r\n{\r\n  \"synchronize\": [\r\n    [\r\n      \"my-desktop\", \"cellphone\"\r\n    ]\r\n  ]\r\n}\r\n```\r\n\r\nand it is returning HTTP 500\r\n```html\r\n<html>\r\n    <head>\r\n        <title>500 Internal server error (gpodder.net)</title>\r\n        <link rel=\"stylesheet\" type=\"text/css\" href=\"/static/css/fail.css\" />\r\n    </head>\r\n    <body>\r\n        <div id=\"c\">\r\n            <div id=\"fail\">\r\n                <h1>500 - Internal server error.</h1>\r\n                <p>\r\n                The service is currently overloaded.\r\n                Please try again later or contact us.\r\n                </p>\r\n            </div>\r\n        </div>\r\n        <img id=\"icon\" src=\"/static/failpodder.png\">\r\n    </body>\r\n</html>\r\n```\r\n\r\nas a reference, a previous call to https://gpoddernet.readthedocs.io/en/latest/api/reference/sync.html#get--api-2-sync-devices-(username).json was returning:\r\n```json\r\n{\r\n  \"synchronized\": [],\r\n  \"not-synchronized\": [\r\n    \"cellphone\",\r\n    \"my-desktop\"\r\n  ]\r\n}\r\n```\r\n\r\nI'm able ot sync this devices on the web ui though.\n", "before_files": [{"content": "from django.http import HttpResponseBadRequest, HttpResponseNotFound\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.decorators.cache import never_cache\n\nfrom mygpo.decorators import allowed_methods, cors_origin\nfrom mygpo.utils import parse_request_body\nfrom mygpo.api.basic_auth import require_valid_user, check_username\nfrom mygpo.api.httpresponse import JsonResponse\nfrom mygpo.users.models import Client, UserProxy\nfrom mygpo.users.tasks import sync_user\n\n\n@csrf_exempt\n@require_valid_user\n@check_username\n@never_cache\n@allowed_methods([\"GET\", \"POST\"])\n@cors_origin()\ndef main(request, username):\n    \"\"\" API Endpoint for Device Synchronisation \"\"\"\n\n    if request.method == \"GET\":\n        return JsonResponse(get_sync_status(request.user))\n\n    else:\n        try:\n            actions = parse_request_body(request)\n        except ValueError as e:\n            return HttpResponseBadRequest(str(e))\n\n        synclist = actions.get(\"synchronize\", [])\n        stopsync = actions.get(\"stop-synchronize\", [])\n\n        try:\n            update_sync_status(request.user, synclist, stopsync)\n        except ValueError as e:\n            return HttpResponseBadRequest(str(e))\n        except Client.DoesNotExist as e:\n            return HttpResponseNotFound(str(e))\n\n        return JsonResponse(get_sync_status(user))\n\n\ndef get_sync_status(user):\n    \"\"\" Returns the current Device Sync status \"\"\"\n\n    sync_groups = []\n    unsynced = []\n\n    user = UserProxy.objects.from_user(user)\n    for group in user.get_grouped_devices():\n        uids = [device.uid for device in group.devices]\n\n        if group.is_synced:\n            sync_groups.append(uids)\n\n        else:\n            unsynced = uids\n\n    return {\"synchronized\": sync_groups, \"not-synchronized\": unsynced}\n\n\ndef update_sync_status(user, synclist, stopsync):\n    \"\"\"Updates the current Device Sync status\n\n    Synchronisation between devices can be set up and stopped.  Devices are\n    identified by their UIDs. Unknown UIDs cause errors, no new devices are\n    created.\"\"\"\n\n    for devlist in synclist:\n\n        if len(devlist) <= 1:\n            raise ValueError(\"at least two devices are needed to sync\")\n\n        # Setup all devices to sync with the first in the list\n        uid = devlist[0]\n        dev = user.client_set.get(uid=uid)\n\n        for other_uid in devlist[1:]:\n            other = user.get_device_by_uid(other_uid)\n            dev.sync_with(other)\n\n    for uid in stopsync:\n        dev = user.get_device_by_uid(uid)\n        try:\n            dev.stop_sync()\n        except ValueError:\n            # if all devices of a sync-group are un-synced,\n            # the last one will raise a ValueError, because it is no longer\n            # being synced -- we just ignore it\n            pass\n\n    user.save()\n\n    sync_user.delay(user)\n", "path": "mygpo/api/advanced/sync.py"}], "after_files": [{"content": "from django.http import HttpResponseBadRequest, HttpResponseNotFound\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.decorators.cache import never_cache\n\nfrom mygpo.decorators import allowed_methods, cors_origin\nfrom mygpo.utils import parse_request_body\nfrom mygpo.api.basic_auth import require_valid_user, check_username\nfrom mygpo.api.httpresponse import JsonResponse\nfrom mygpo.users.models import Client, UserProxy\nfrom mygpo.users.tasks import sync_user\n\n\n@csrf_exempt\n@require_valid_user\n@check_username\n@never_cache\n@allowed_methods([\"GET\", \"POST\"])\n@cors_origin()\ndef main(request, username):\n    \"\"\" API Endpoint for Device Synchronisation \"\"\"\n\n    if request.method == \"GET\":\n        return JsonResponse(get_sync_status(request.user))\n\n    else:\n        try:\n            actions = parse_request_body(request)\n        except ValueError as e:\n            return HttpResponseBadRequest(str(e))\n\n        synclist = actions.get(\"synchronize\", [])\n        stopsync = actions.get(\"stop-synchronize\", [])\n\n        try:\n            update_sync_status(request.user, synclist, stopsync)\n        except ValueError as e:\n            return HttpResponseBadRequest(str(e))\n        except Client.DoesNotExist as e:\n            return HttpResponseNotFound(str(e))\n\n        return JsonResponse(get_sync_status(request.user))\n\n\ndef get_sync_status(user):\n    \"\"\" Returns the current Device Sync status \"\"\"\n\n    sync_groups = []\n    unsynced = []\n\n    user = UserProxy.objects.from_user(user)\n    for group in user.get_grouped_devices():\n        uids = [device.uid for device in group.devices]\n\n        if group.is_synced:\n            sync_groups.append(uids)\n\n        else:\n            unsynced = uids\n\n    return {\"synchronized\": sync_groups, \"not-synchronized\": unsynced}\n\n\ndef update_sync_status(user, synclist, stopsync):\n    \"\"\"Updates the current Device Sync status\n\n    Synchronisation between devices can be set up and stopped.  Devices are\n    identified by their UIDs. Unknown UIDs cause errors, no new devices are\n    created.\"\"\"\n\n    for devlist in synclist:\n\n        if len(devlist) <= 1:\n            raise ValueError(\"at least two devices are needed to sync\")\n\n        # Setup all devices to sync with the first in the list\n        uid = devlist[0]\n        dev = user.client_set.get(uid=uid)\n\n        for other_uid in devlist[1:]:\n            other = user.client_set.get(uid=other_uid)\n            dev.sync_with(other)\n\n    for uid in stopsync:\n        dev = user.client_set.get(uid=uid)\n        try:\n            dev.stop_sync()\n        except ValueError:\n            # if all devices of a sync-group are un-synced,\n            # the last one will raise a ValueError, because it is no longer\n            # being synced -- we just ignore it\n            pass\n\n    user.save()\n\n    sync_user.delay(user)\n", "path": "mygpo/api/advanced/sync.py"}]}