Here is a function that can do for you.
Note, the passage on the group node is multi-pass, as the group nodes can contain other group nodes in turn, so a single pass is not sufficient in that case
orphan_ob = [o for o in bpy.data.objects if not o.users]
orphan_mesh = [m for m in bpy.data.meshes if not m.users]
orphan_mat = [m for m in bpy.data.materials if not m.users]
orphan_node_group = [g for g in bpy.data.node_groups if not g.users]
if [g for g in bpy.data.node_groups if not g.users]: purge_node_groups()
orphan_texture = [t for t in bpy.data.textures if not t.users]
orphan_images = [i for i in bpy.data.images if not i.users]
orphan_cameras = [c for c in bpy.data.cameras if not c.users]
while orphan_cameras :
mega_purge() #call the function
You can put many other things into this function
for example bpy.data.scenes, bpy.data.lights etc. in the same way you see this function structured.
Another important thing is the hierarchy of this cleanup, if we started with deleting a Material, it wouldn't work. Even worse if starting from an image.
This is because the image can be linked to a material or texture, and as long as the material or texture is not deleted, it will turn out that that image is still linked to something so it will not be deleted.