~launchpad-pqm/launchpad/devel

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
# Copyright 2009 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

"""Browser views for Soyuz publishing records."""

__metaclass__ = type

__all__ = [
    'BinaryPublishingRecordView',
    'SourcePublicationURL',
    'SourcePublishingRecordSelectableView',
    'SourcePublishingRecordView',
    ]

from operator import attrgetter

from lazr.delegates import delegates
from zope.interface import implements

from canonical.launchpad.browser.librarian import ProxiedLibraryFileAlias
from canonical.launchpad.webapp.authorization import check_permission
from canonical.launchpad.webapp.interfaces import ICanonicalUrlData
from canonical.launchpad.webapp.menu import structured
from canonical.launchpad.webapp.publisher import (
    canonical_url,
    LaunchpadView,
    )
from lp.services.propertycache import cachedproperty
from lp.soyuz.enums import PackagePublishingStatus
from lp.soyuz.interfaces.binarypackagebuild import BuildSetStatus
from lp.soyuz.interfaces.packagediff import IPackageDiff
from lp.soyuz.interfaces.publishing import (
    IBinaryPackagePublishingHistory,
    ISourcePackagePublishingHistory,
    )


class PublicationURLBase:
    """Dynamic URL declaration for `I*PackagePublishingHistory`"""
    implements(ICanonicalUrlData)
    rootsite = None

    def __init__(self, context):
        self.context = context

    @property
    def inside(self):
        return self.context.archive


class SourcePublicationURL(PublicationURLBase):
    """Dynamic URL declaration for `ISourcePackagePublishingHistory`"""
    @property
    def path(self):
        return u"+sourcepub/%s" % self.context.id


class BinaryPublicationURL(PublicationURLBase):
    """Dynamic URL declaration for `IBinaryPackagePublishingHistory`"""
    @property
    def path(self):
        return u"+binarypub/%s" % self.context.id


class ProxiedPackageDiff:
    """A `PackageDiff` extension.

    Instead of `LibraryFileAlias` returns `ProxiedLibraryFileAlias`, so
    their 'http_url' attribute can be used in the template.
    """
    delegates(IPackageDiff)

    def __init__(self, context, parent):
        self.context = context
        self.parent = parent

    @property
    def diff_content(self):
        library_file = self.context.diff_content
        if library_file is None:
            return None
        return ProxiedLibraryFileAlias(library_file, self.parent)


class BasePublishingRecordView(LaunchpadView):
    """Base Publishing view class."""

    @property
    def is_source(self):
        return ISourcePackagePublishingHistory.providedBy(self.context)

    @property
    def is_binary(self):
        return IBinaryPackagePublishingHistory.providedBy(self.context)

    # The reason we define the map below outside the only function that uses
    # it (date_last_changed()) is that this allows us to test whether the map
    # covers all PackagePublishingStatus enumeration values.
    # The pertinent tests in doc/publishing-pages.txt will fail if we add a
    # new value to the PackagePublishingStatus enumeration but do not update
    # this map.
    timestamp_map = {
        PackagePublishingStatus.DELETED: 'dateremoved',
        PackagePublishingStatus.OBSOLETE: 'scheduleddeletiondate',
        PackagePublishingStatus.PENDING: 'datecreated',
        PackagePublishingStatus.PUBLISHED: 'datepublished',
        PackagePublishingStatus.SUPERSEDED: 'datesuperseded'
    }

    @property
    def date_last_changed(self):
        """Return the date of last change considering the publishing status.

        The date returned is as follows:
            * pending        -> datecreated
            * published      -> datepublished
            * superseded     -> datesuperseded
            * deleted        -> dateremoved
            * obsolete       -> scheduleddeletiondate
        """
        accessor = attrgetter(self.timestamp_map[self.context.status])
        return accessor(self.context)


    def wasDeleted(self):
        """Whether or not a publishing record deletion was requested.

        A publishing record deletion represents the explicit request from a
        archive-administrator (self.remove_by) to purge the published contents
        of this record from the archive for an arbitrary reason
        (self.removal_comment).
        """
        return self.context.status == PackagePublishingStatus.DELETED

    def wasSuperseded(self):
        """Whether or not a publishing record was superseded.

        'Superseded' means that a new and higher version of this package was
        uploaded/built after it was published or the publishing attributes
        (section, component, priority/urgency) was modified.
        """
        return self.context.supersededby is not None

    def isPendingRemoval(self):
        """Whether or not a publishing record is marked for removal.

        This package will be removed from the archive respecting the Soyuz
        'death row' quarantine period and the absence of file references in
        the target archive.
        """
        return self.context.scheduleddeletiondate is not None

    def isRemoved(self):
        """Whether or not a publishing records was removed from the archive.

        A publishing record (all files related to it) is removed from the
        archive disk once it pass through its quarantine period and it's not
        referred by any other archive publishing record.
        Archive removal represents the act of having its content purged from
        archive disk, such situation can be triggered for different status,
        each one representing a distinct step in the Soyuz publishing workflow:

         * SUPERSEDED -> the publication is not necessary since there is already
           a newer/higher/modified version available

         * DELETED -> the publishing was explicitly marked for removal by a
           archive-administrator, it's not wanted in the archive.

         * OBSOLETE -> the publication has become obsolete because its targeted
           distroseries has become obsolete (not supported by its developers).
        """
        return self.context.dateremoved is not None

    @property
    def js_connector(self):
        """Return the javascript glue for expandable rows mechanism."""
        return """
        <script type="text/javascript">
           registerLaunchpadFunction(function() {
               // Set the style of the expander icon so that it appears
               // clickable when js is enabled:
               var view_icon = document.getElementById('pub%s-expander');
               view_icon.style.cursor = 'pointer';
               connect('pub%s-expander', 'onclick', function (e) {
                   toggleExpandableTableRow('pub%s');
                   });
               });
        </script>
        """ % (self.context.id, self.context.id, self.context.id)

    @property
    def removal_comment(self):
        """Return the removal comment or 'None provided'."""
        removal_comment = self.context.removal_comment
        if removal_comment is None or not removal_comment.strip():
            removal_comment = u'None provided.'

        return removal_comment


class SourcePublishingRecordView(BasePublishingRecordView):
    """View class for `ISourcePackagePublishingHistory`."""

    @cachedproperty
    def build_status_summary(self):
        """Returns a dict with a summary of the build status."""
        return self.context.getStatusSummaryForBuilds()

    @property
    def builds_successful_and_published(self):
        """Return whether all builds were successful and published."""
        status = self.build_status_summary['status']
        return status == BuildSetStatus.FULLYBUILT

    @property
    def builds_successful_and_pending(self):
        """Return whether builds were successful but not all published."""
        status = self.build_status_summary['status']
        return status == BuildSetStatus.FULLYBUILT_PENDING

    @property
    def pending_builds(self):
        """Return a list of successful builds pending publication."""
        if self.builds_successful_and_pending:
            return self.build_status_summary['builds']
        else:
            return []

    @property
    def build_status_img_src(self):
        """Return the image path for the current build status summary."""
        image_map = {
            BuildSetStatus.BUILDING: '/@@/processing',
            BuildSetStatus.NEEDSBUILD: '/@@/build-needed',
            BuildSetStatus.FAILEDTOBUILD: '/@@/no',
            BuildSetStatus.FULLYBUILT_PENDING: '/@@/build-success-publishing'
            }

        return image_map.get(self.build_status_summary['status'], '/@@/yes')

    def wasCopied(self):
        """Whether or not a source is published in its original location.

        A source is not in its original location when:

         * The publishing `Archive` is not the same than where the source
            was uploaded. (SSPPH -> SPR -> Archive != SSPPH -> Archive).
        Or

          * The publishing `DistroSeries` is not the same than where the
            source was uploaded (SSPPH -> SPR -> DS != SSPPH -> DS).
        """
        source = self.context.sourcepackagerelease

        if self.context.archive != source.upload_archive:
            return True

        if self.context.distroseries != source.upload_distroseries:
            return True

        return False

    @property
    def allow_selection(self):
        """Do not render the checkbox corresponding to this record."""
        return False

    @property
    def published_source_and_binary_files(self):
        """Return list of dictionaries representing published files."""
        files = sorted(
            (ProxiedLibraryFileAlias(lfa, self.context.archive)
             for lfa in self.context.getSourceAndBinaryLibraryFiles()),
            key=attrgetter('filename'))
        result = []
        urls = set()
        for library_file in files:
            url = library_file.http_url
            if url in urls:
                # Don't print out the same file multiple times. This
                # actually happens for arch-all builds, and is
                # particularly irritating for PPAs.
                continue
            urls.add(url)

            custom_dict = {}
            custom_dict["url"] = url
            custom_dict["filename"] = library_file.filename
            custom_dict["filesize"] = library_file.content.filesize
            if (library_file.filename.endswith('.deb') or
                library_file.filename.endswith('.udeb')):
                custom_dict['class'] = 'binary'
            else:
                custom_dict['class'] = 'source'

            result.append(custom_dict)

        return result

    @property
    def available_diffs(self):
        package_diffs = self.context.sourcepackagerelease.package_diffs
        return [
            ProxiedPackageDiff(package_diff, self.context.archive)
            for package_diff in package_diffs]

    @property
    def built_packages(self):
        """Return a list of dictionaries with package names and their summary.

        For each built package from this published source, return a
        dictionary with keys "binarypackagename" and "summary", where
        the binarypackagename is unique (i.e. it ignores the same package
        published in more than one place/architecture.)
        """
        results = []
        packagenames = set()
        for pub in self.context.getPublishedBinaries():
            package = pub.binarypackagerelease
            packagename = package.binarypackagename.name
            if packagename not in packagenames:
                entry = {
                    "binarypackagename" : packagename,
                    "summary" : package.summary,
                    }
                results.append(entry)
                packagenames.add(packagename)
        return results

    @cachedproperty
    def builds(self):
        """Return a list of Builds for the context published source."""
        return list(self.context.getBuilds())

    @property
    def linkify_source_archive(self):
        """Return True if the source's upload_archive should be linkified.

        The source archive is the upload_archive for any source that was
        copied.  It should be linkified only if it's a PPA and the user
        has permission to view that PPA.
        """
        archive = self.context.sourcepackagerelease.upload_archive

        if not archive.is_ppa:
            return False

        return check_permission('launchpad.View', archive)

    @property
    def recipe_build_details(self): 
        """Return a linkified string containing details about a
        SourcePackageRecipeBuild.
        """
        sprb = self.context.sourcepackagerelease.source_package_recipe_build
        if sprb is not None:
            if sprb.recipe is None:
                recipe = 'deleted recipe'
            else:
                recipe = structured(
                    'recipe <a href="%s">%s</a>',
                    canonical_url(sprb.recipe), sprb.recipe.name)
            return structured(
                '<a href="%s">Built</a> by %s for <a href="%s">%s</a>',
                    canonical_url(sprb), recipe,
                    canonical_url(sprb.requester),
                    sprb.requester.displayname).escapedtext
        return None


class SourcePublishingRecordSelectableView(SourcePublishingRecordView):
    """View class for a selectable `ISourcePackagePublishingHistory`."""

    @property
    def allow_selection(self):
        """Allow the checkbox corresponding to this record to be rendered."""
        return True


class BinaryPublishingRecordView(BasePublishingRecordView):
    """View class for `IBinaryPackagePublishingHistory`."""

    def wasCopied(self):
        """Whether or not a binary is published in its original location.

        A binary is not in its original location when:

         * The publishing `Archive` is not the same than where the binary
           was built. (SBPPH -> BPR -> Build -> Archive != SBPPH -> Archive).
        Or

          * The publishing `DistroArchSeries` is not the same than where
            the binary was built (SBPPH -> BPR -> B -> DAS != SBPPH -> DAS).

        Or

          * The publishing pocket is not the same than where the binary was
            built (SBPPH -> BPR -> B -> Pocket != SBPPH -> Pocket).

        """
        build = self.context.binarypackagerelease.build

        if self.context.archive != build.archive:
            return True

        if self.context.distroarchseries != build.distro_arch_series:
            return True

        if self.context.pocket != build.pocket:
            return True

        return False