# Path: buttons.py
# class ButtonableModelAdmin(admin.ModelAdmin):
#     """
#         A subclass of this admin will let you add buttons (like history) in the
#         change view of an entry.
#     """
#     buttons = []
# 
#     def change_view(self, request, object_id, form_url='', extra_context=None):
#         if not extra_context:
#             extra_context = {'buttons' : []}
# 
#         for b in self.buttons:
#             extra_context['buttons'].append({'name' : b.short_description, 'url' : b.func_name})
# 
#         return super(ButtonableModelAdmin, self).change_view(request, object_id, form_url, extra_context)
# 
#     def get_urls(self):
#         urls = super(ButtonableModelAdmin, self).get_urls()
# 
#         my_urls = patterns('',)
#         for b in self.buttons:
#             my_urls += patterns('',
#                             url(r'^(?P<id>\d+)/%s/$' % b.func_name, self.admin_site.admin_view(b))
#                         )
# 
#         return my_urls + urls
# 
#     def __call__(self, request, url):
#         if url is not None:
#             res=re.match('(.*/)?(?P<id>\d+)/(?P<command>.*)/', url)
#             if res:
#                 if res.group('command') in [b.func_name for b in self.buttons]:
#                     obj = self.model._default_manager.get(pk=res.group('id'))
#                     getattr(self, res.group('command'))(obj)
#                     return HttpResponseRedirect(request.META['HTTP_REFERER'])
# 
#         return super(ButtonableModelAdmin, self).__call__(request, url)
# 
# Path: github.py
# def _get_user_repo(url):
#     """
#         Return the :user/:repo/ from a github.com url
#     """
#     if url.find('://github.com/') > -1:  # toplevel GitHub page
#         p = url.split('/')
#         return '%s/%s' % (p[3], p[4].replace('.git', ''))
#     elif url.find('.github.com/') > -1:  # GitHub project pages
#         p = url.split('/')
#         u = p[2].split('.')[0]
#         return '%s/%s' % (u, p[3])
# 
#     return None


import re
import sys
import bugs
import utils
import difio.tasks
from models import *
from django.contrib import admin
from django.contrib import messages
from django.shortcuts import render
from buttons import ButtonableModelAdmin
from datetime import datetime, timedelta
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.core.files.base import ContentFile
from django.contrib.admin import SimpleListFilter
from django.core.handlers.wsgi import WSGIRequest
from django.contrib.auth.models import AnonymousUser
from github import _get_user_repo as github_get_user_repo
    from django.contrib.messages import constants as message_levels
                        obj.assigned_to
                    )
        return text.replace("\n", "") # https://code.djangoproject.com/ticket/19226#comment:15
    package_status.short_description = 'Package'
    package_status.allow_tags = True

    def download_link(self, obj):
        return "<a href='%s'>GET</a>" % obj.download_url
    download_link.short_description = ""
    download_link.allow_tags = True

    def apps_count(self, obj):
        """
            Count how many Apps have this PV *INSTALLED*

            @obj - PackageVersion
            @return - int
        """
        # NB: installed packages are deleted when app is deleted so this is a good estimate
        return InstalledPackage.objects.filter(version=obj.pk).count()
    apps_count.short_description = "Apps #"


    def github_iframe(self, obj):
        """
            Show a commit which contains the version change
            or all commits list for easier searching.
        """
        url = None
        if obj.package.scmurl.find('github.com') > -1:

# Path: buttons.py
# class ButtonableModelAdmin(admin.ModelAdmin):
#     """
#         A subclass of this admin will let you add buttons (like history) in the
#         change view of an entry.
#     """
#     buttons = []
# 
#     def change_view(self, request, object_id, form_url='', extra_context=None):
#         if not extra_context:
#             extra_context = {'buttons' : []}
# 
#         for b in self.buttons:
#             extra_context['buttons'].append({'name' : b.short_description, 'url' : b.func_name})
# 
#         return super(ButtonableModelAdmin, self).change_view(request, object_id, form_url, extra_context)
# 
#     def get_urls(self):
#         urls = super(ButtonableModelAdmin, self).get_urls()
# 
#         my_urls = patterns('',)
#         for b in self.buttons:
#             my_urls += patterns('',
#                             url(r'^(?P<id>\d+)/%s/$' % b.func_name, self.admin_site.admin_view(b))
#                         )
# 
#         return my_urls + urls
# 
#     def __call__(self, request, url):
#         if url is not None:
#             res=re.match('(.*/)?(?P<id>\d+)/(?P<command>.*)/', url)
#             if res:
#                 if res.group('command') in [b.func_name for b in self.buttons]:
#                     obj = self.model._default_manager.get(pk=res.group('id'))
#                     getattr(self, res.group('command'))(obj)
#                     return HttpResponseRedirect(request.META['HTTP_REFERER'])
# 
#         return super(ButtonableModelAdmin, self).__call__(request, url)
# 
# Path: github.py
# def _get_user_repo(url):
#     """
#         Return the :user/:repo/ from a github.com url
#     """
#     if url.find('://github.com/') > -1:  # toplevel GitHub page
#         p = url.split('/')
#         return '%s/%s' % (p[3], p[4].replace('.git', ''))
#     elif url.find('.github.com/') > -1:  # GitHub project pages
#         p = url.split('/')
#         u = p[2].split('.')[0]
#         return '%s/%s' % (u, p[3])
# 
#     return None


# Path: admin.py
import re
import sys
import bugs
import utils
import difio.tasks
from models import *
from django.contrib import admin
from django.contrib import messages
from django.shortcuts import render
from buttons import ButtonableModelAdmin
from datetime import datetime, timedelta
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.core.files.base import ContentFile
from django.contrib.admin import SimpleListFilter
from django.core.handlers.wsgi import WSGIRequest
from django.contrib.auth.models import AnonymousUser
from github import _get_user_repo as github_get_user_repo
    from django.contrib.messages import constants as message_levels

                        obj.assigned_to
                    )
        return text.replace("\n", "") # https://code.djangoproject.com/ticket/19226#comment:15
    package_status.short_description = 'Package'
    package_status.allow_tags = True

    def download_link(self, obj):
        return "<a href='%s'>GET</a>" % obj.download_url
    download_link.short_description = ""
    download_link.allow_tags = True

    def apps_count(self, obj):
        """
            Count how many Apps have this PV *INSTALLED*

            @obj - PackageVersion
            @return - int
        """
        # NB: installed packages are deleted when app is deleted so this is a good estimate
        return InstalledPackage.objects.filter(version=obj.pk).count()
    apps_count.short_description = "Apps #"


    def github_iframe(self, obj):
        """
            Show a commit which contains the version change
            or all commits list for easier searching.
        """
        url = None
        if obj.package.scmurl.find('github.com') > -1:

            user_repo = github_get_user_repo(obj.package.scmurl)